StyleComputer.cpp 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/BinarySearch.h>
  10. #include <AK/Debug.h>
  11. #include <AK/Error.h>
  12. #include <AK/Find.h>
  13. #include <AK/Function.h>
  14. #include <AK/HashMap.h>
  15. #include <AK/Math.h>
  16. #include <AK/QuickSort.h>
  17. #include <AK/TemporaryChange.h>
  18. #include <LibGfx/Font/Font.h>
  19. #include <LibGfx/Font/FontDatabase.h>
  20. #include <LibGfx/Font/FontStyleMapping.h>
  21. #include <LibGfx/Font/OpenType/Typeface.h>
  22. #include <LibGfx/Font/ScaledFont.h>
  23. #include <LibGfx/Font/Typeface.h>
  24. #include <LibGfx/Font/WOFF/Typeface.h>
  25. #include <LibGfx/Font/WOFF2/Typeface.h>
  26. #include <LibWeb/Animations/AnimationEffect.h>
  27. #include <LibWeb/Animations/DocumentTimeline.h>
  28. #include <LibWeb/CSS/AnimationEvent.h>
  29. #include <LibWeb/CSS/CSSAnimation.h>
  30. #include <LibWeb/CSS/CSSFontFaceRule.h>
  31. #include <LibWeb/CSS/CSSImportRule.h>
  32. #include <LibWeb/CSS/CSSStyleRule.h>
  33. #include <LibWeb/CSS/Parser/Parser.h>
  34. #include <LibWeb/CSS/SelectorEngine.h>
  35. #include <LibWeb/CSS/StyleComputer.h>
  36. #include <LibWeb/CSS/StyleSheet.h>
  37. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  38. #include <LibWeb/CSS/StyleValues/BorderRadiusStyleValue.h>
  39. #include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
  40. #include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
  41. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  42. #include <LibWeb/CSS/StyleValues/EasingStyleValue.h>
  43. #include <LibWeb/CSS/StyleValues/FilterValueListStyleValue.h>
  44. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  45. #include <LibWeb/CSS/StyleValues/GridTrackPlacementStyleValue.h>
  46. #include <LibWeb/CSS/StyleValues/GridTrackSizeListStyleValue.h>
  47. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  48. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  49. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  50. #include <LibWeb/CSS/StyleValues/MathDepthStyleValue.h>
  51. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  52. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  53. #include <LibWeb/CSS/StyleValues/PositionStyleValue.h>
  54. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  55. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  56. #include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
  57. #include <LibWeb/CSS/StyleValues/StringStyleValue.h>
  58. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  59. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  60. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  61. #include <LibWeb/CSS/StyleValues/TransitionStyleValue.h>
  62. #include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
  63. #include <LibWeb/CSS/StyleValues/UnsetStyleValue.h>
  64. #include <LibWeb/DOM/Attr.h>
  65. #include <LibWeb/DOM/Document.h>
  66. #include <LibWeb/DOM/Element.h>
  67. #include <LibWeb/DOM/ShadowRoot.h>
  68. #include <LibWeb/HTML/HTMLBRElement.h>
  69. #include <LibWeb/HTML/HTMLHtmlElement.h>
  70. #include <LibWeb/HTML/Parser/HTMLParser.h>
  71. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  72. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  73. #include <LibWeb/Layout/Node.h>
  74. #include <LibWeb/Namespace.h>
  75. #include <LibWeb/Painting/PaintableBox.h>
  76. #include <LibWeb/Platform/FontPlugin.h>
  77. #include <LibWeb/ReferrerPolicy/AbstractOperations.h>
  78. #include <math.h>
  79. #include <stdio.h>
  80. namespace AK {
  81. // traits for FontFaceKey
  82. template<>
  83. struct Traits<Web::CSS::FontFaceKey> : public DefaultTraits<Web::CSS::FontFaceKey> {
  84. static unsigned hash(Web::CSS::FontFaceKey const& key) { return pair_int_hash(key.family_name.hash(), pair_int_hash(key.weight, key.slope)); }
  85. };
  86. }
  87. namespace Web::CSS {
  88. static DOM::Element const* element_to_inherit_style_from(DOM::Element const*, Optional<CSS::Selector::PseudoElement::Type>);
  89. StyleComputer::StyleComputer(DOM::Document& document)
  90. : m_document(document)
  91. , m_default_font_metrics(16, Platform::FontPlugin::the().default_font().pixel_metrics())
  92. , m_root_element_font_metrics(m_default_font_metrics)
  93. {
  94. }
  95. StyleComputer::~StyleComputer() = default;
  96. FontLoader::FontLoader(StyleComputer& style_computer, FlyString family_name, Vector<Gfx::UnicodeRange> unicode_ranges, Vector<URL::URL> urls, Function<void(FontLoader const&)> on_load, Function<void()> on_fail)
  97. : m_style_computer(style_computer)
  98. , m_family_name(move(family_name))
  99. , m_unicode_ranges(move(unicode_ranges))
  100. , m_urls(move(urls))
  101. , m_on_load(move(on_load))
  102. , m_on_fail(move(on_fail))
  103. {
  104. }
  105. FontLoader::~FontLoader() = default;
  106. void FontLoader::resource_did_load()
  107. {
  108. auto result = try_load_font();
  109. if (result.is_error()) {
  110. dbgln("Failed to parse font: {}", result.error());
  111. start_loading_next_url();
  112. return;
  113. }
  114. m_vector_font = result.release_value();
  115. m_style_computer.did_load_font(m_family_name);
  116. if (m_on_load)
  117. m_on_load(*this);
  118. }
  119. void FontLoader::resource_did_fail()
  120. {
  121. if (m_on_fail) {
  122. m_on_fail();
  123. }
  124. }
  125. RefPtr<Gfx::Font> FontLoader::font_with_point_size(float point_size)
  126. {
  127. if (!m_vector_font) {
  128. start_loading_next_url();
  129. return nullptr;
  130. }
  131. return m_vector_font->scaled_font(point_size);
  132. }
  133. void FontLoader::start_loading_next_url()
  134. {
  135. if (resource() && resource()->is_pending())
  136. return;
  137. if (m_urls.is_empty())
  138. return;
  139. LoadRequest request;
  140. request.set_url(m_urls.take_first());
  141. // HACK: We're crudely computing the referer value and shoving it into the
  142. // request until fetch infrastructure is used here.
  143. auto referrer_url = ReferrerPolicy::strip_url_for_use_as_referrer(m_style_computer.document().url());
  144. if (referrer_url.has_value() && !request.headers().contains("Referer"))
  145. request.set_header("Referer", referrer_url->serialize());
  146. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  147. }
  148. ErrorOr<NonnullRefPtr<Gfx::Typeface>> FontLoader::try_load_font()
  149. {
  150. // FIXME: This could maybe use the format() provided in @font-face as well, since often the mime type is just application/octet-stream and we have to try every format
  151. auto const& mime_type = resource()->mime_type();
  152. if (mime_type == "font/ttf"sv || mime_type == "application/x-font-ttf"sv) {
  153. if (auto result = OpenType::Typeface::try_load_from_externally_owned_memory(resource()->encoded_data()); !result.is_error()) {
  154. return result;
  155. }
  156. }
  157. if (mime_type == "font/woff"sv || mime_type == "application/font-woff"sv) {
  158. if (auto result = WOFF::Typeface::try_load_from_externally_owned_memory(resource()->encoded_data()); !result.is_error()) {
  159. return result;
  160. }
  161. }
  162. if (mime_type == "font/woff2"sv || mime_type == "application/font-woff2"sv) {
  163. if (auto result = WOFF2::Typeface::try_load_from_externally_owned_memory(resource()->encoded_data()); !result.is_error()) {
  164. return result;
  165. }
  166. }
  167. // We don't have the luxury of knowing the MIME type, so we have to try all formats.
  168. auto ttf = OpenType::Typeface::try_load_from_externally_owned_memory(resource()->encoded_data());
  169. if (!ttf.is_error())
  170. return ttf.release_value();
  171. auto woff = WOFF::Typeface::try_load_from_externally_owned_memory(resource()->encoded_data());
  172. if (!woff.is_error())
  173. return woff.release_value();
  174. auto woff2 = WOFF2::Typeface::try_load_from_externally_owned_memory(resource()->encoded_data());
  175. if (!woff2.is_error())
  176. return woff2.release_value();
  177. return Error::from_string_literal("Automatic format detection failed");
  178. }
  179. struct StyleComputer::MatchingFontCandidate {
  180. FontFaceKey key;
  181. Variant<FontLoaderList*, Gfx::Typeface const*> loader_or_typeface;
  182. [[nodiscard]] RefPtr<Gfx::FontCascadeList const> font_with_point_size(float point_size) const
  183. {
  184. RefPtr<Gfx::FontCascadeList> font_list = Gfx::FontCascadeList::create();
  185. if (auto* loader_list = loader_or_typeface.get_pointer<FontLoaderList*>(); loader_list) {
  186. for (auto const& loader : **loader_list) {
  187. if (auto font = loader->font_with_point_size(point_size); font)
  188. font_list->add(*font, loader->unicode_ranges());
  189. }
  190. return font_list;
  191. }
  192. font_list->add(loader_or_typeface.get<Gfx::Typeface const*>()->scaled_font(point_size));
  193. return font_list;
  194. }
  195. };
  196. static CSSStyleSheet& default_stylesheet(DOM::Document const& document)
  197. {
  198. static JS::Handle<CSSStyleSheet> sheet;
  199. if (!sheet.cell()) {
  200. extern StringView default_stylesheet_source;
  201. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), default_stylesheet_source));
  202. }
  203. return *sheet;
  204. }
  205. static CSSStyleSheet& quirks_mode_stylesheet(DOM::Document const& document)
  206. {
  207. static JS::Handle<CSSStyleSheet> sheet;
  208. if (!sheet.cell()) {
  209. extern StringView quirks_mode_stylesheet_source;
  210. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), quirks_mode_stylesheet_source));
  211. }
  212. return *sheet;
  213. }
  214. static CSSStyleSheet& mathml_stylesheet(DOM::Document const& document)
  215. {
  216. static JS::Handle<CSSStyleSheet> sheet;
  217. if (!sheet.cell()) {
  218. extern StringView mathml_stylesheet_source;
  219. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), mathml_stylesheet_source));
  220. }
  221. return *sheet;
  222. }
  223. static CSSStyleSheet& svg_stylesheet(DOM::Document const& document)
  224. {
  225. static JS::Handle<CSSStyleSheet> sheet;
  226. if (!sheet.cell()) {
  227. extern StringView svg_stylesheet_source;
  228. sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document), svg_stylesheet_source));
  229. }
  230. return *sheet;
  231. }
  232. template<typename Callback>
  233. void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const
  234. {
  235. if (cascade_origin == CascadeOrigin::UserAgent) {
  236. callback(default_stylesheet(document()), {});
  237. if (document().in_quirks_mode())
  238. callback(quirks_mode_stylesheet(document()), {});
  239. callback(mathml_stylesheet(document()), {});
  240. callback(svg_stylesheet(document()), {});
  241. }
  242. if (cascade_origin == CascadeOrigin::User) {
  243. if (m_user_style_sheet)
  244. callback(*m_user_style_sheet, {});
  245. }
  246. if (cascade_origin == CascadeOrigin::Author) {
  247. document().for_each_css_style_sheet([&](CSSStyleSheet& sheet) {
  248. callback(sheet, {});
  249. });
  250. const_cast<DOM::Document&>(document()).for_each_shadow_root([&](DOM::ShadowRoot& shadow_root) {
  251. shadow_root.for_each_css_style_sheet([&](CSSStyleSheet& sheet) {
  252. callback(sheet, &shadow_root);
  253. });
  254. });
  255. }
  256. }
  257. StyleComputer::RuleCache const& StyleComputer::rule_cache_for_cascade_origin(CascadeOrigin cascade_origin) const
  258. {
  259. switch (cascade_origin) {
  260. case CascadeOrigin::Author:
  261. return *m_author_rule_cache;
  262. case CascadeOrigin::User:
  263. return *m_user_rule_cache;
  264. case CascadeOrigin::UserAgent:
  265. return *m_user_agent_rule_cache;
  266. default:
  267. TODO();
  268. }
  269. }
  270. [[nodiscard]] static bool filter_namespace_rule(DOM::Element const& element, MatchingRule const& rule)
  271. {
  272. // FIXME: Filter out non-default namespace using prefixes
  273. if (auto namespace_rule = rule.sheet->default_namespace_rule()) {
  274. if (namespace_rule->namespace_uri() != element.namespace_uri())
  275. return false;
  276. }
  277. return true;
  278. }
  279. bool StyleComputer::should_reject_with_ancestor_filter(Selector const& selector) const
  280. {
  281. for (u32 hash : selector.ancestor_hashes()) {
  282. if (hash == 0)
  283. break;
  284. if (!m_ancestor_filter.may_contain(hash))
  285. return true;
  286. }
  287. return false;
  288. }
  289. Vector<MatchingRule> StyleComputer::collect_matching_rules(DOM::Element const& element, CascadeOrigin cascade_origin, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  290. {
  291. auto const& root_node = element.root();
  292. auto shadow_root = is<DOM::ShadowRoot>(root_node) ? static_cast<DOM::ShadowRoot const*>(&root_node) : nullptr;
  293. auto const& rule_cache = rule_cache_for_cascade_origin(cascade_origin);
  294. Vector<MatchingRule, 512> rules_to_run;
  295. auto add_rules_to_run = [&](Vector<MatchingRule> const& rules) {
  296. rules_to_run.grow_capacity(rules_to_run.size() + rules.size());
  297. if (pseudo_element.has_value()) {
  298. for (auto const& rule : rules) {
  299. if (rule.contains_pseudo_element && filter_namespace_rule(element, rule))
  300. rules_to_run.unchecked_append(rule);
  301. }
  302. } else {
  303. for (auto const& rule : rules) {
  304. if (!rule.contains_pseudo_element && filter_namespace_rule(element, rule))
  305. rules_to_run.unchecked_append(rule);
  306. }
  307. }
  308. };
  309. for (auto const& class_name : element.class_names()) {
  310. if (auto it = rule_cache.rules_by_class.find(class_name); it != rule_cache.rules_by_class.end())
  311. add_rules_to_run(it->value);
  312. }
  313. if (auto id = element.id(); id.has_value()) {
  314. if (auto it = rule_cache.rules_by_id.find(id.value()); it != rule_cache.rules_by_id.end())
  315. add_rules_to_run(it->value);
  316. }
  317. if (auto it = rule_cache.rules_by_tag_name.find(element.local_name()); it != rule_cache.rules_by_tag_name.end())
  318. add_rules_to_run(it->value);
  319. if (pseudo_element.has_value())
  320. add_rules_to_run(rule_cache.pseudo_element_rules);
  321. if (element.is_document_element())
  322. add_rules_to_run(rule_cache.root_rules);
  323. element.for_each_attribute([&](auto& name, auto&) {
  324. if (auto it = rule_cache.rules_by_attribute_name.find(name); it != rule_cache.rules_by_attribute_name.end()) {
  325. add_rules_to_run(it->value);
  326. }
  327. });
  328. add_rules_to_run(rule_cache.other_rules);
  329. Vector<MatchingRule> matching_rules;
  330. matching_rules.ensure_capacity(rules_to_run.size());
  331. for (auto const& rule_to_run : rules_to_run) {
  332. // FIXME: This needs to be revised when adding support for the :host and ::shadow selectors, which transition shadow tree boundaries
  333. auto rule_root = rule_to_run.shadow_root;
  334. auto from_user_agent_or_user_stylesheet = rule_to_run.cascade_origin == CascadeOrigin::UserAgent || rule_to_run.cascade_origin == CascadeOrigin::User;
  335. if (rule_root != shadow_root && !from_user_agent_or_user_stylesheet)
  336. continue;
  337. auto const& selector = rule_to_run.rule->selectors()[rule_to_run.selector_index];
  338. if (should_reject_with_ancestor_filter(*selector))
  339. continue;
  340. if (rule_to_run.can_use_fast_matches) {
  341. if (!SelectorEngine::fast_matches(selector, *rule_to_run.sheet, element))
  342. continue;
  343. } else {
  344. if (!SelectorEngine::matches(selector, *rule_to_run.sheet, element, pseudo_element))
  345. continue;
  346. }
  347. matching_rules.append(rule_to_run);
  348. }
  349. return matching_rules;
  350. }
  351. static void sort_matching_rules(Vector<MatchingRule>& matching_rules)
  352. {
  353. quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) {
  354. auto const& a_selector = a.rule->selectors()[a.selector_index];
  355. auto const& b_selector = b.rule->selectors()[b.selector_index];
  356. auto a_specificity = a_selector->specificity();
  357. auto b_specificity = b_selector->specificity();
  358. if (a_specificity == b_specificity) {
  359. if (a.style_sheet_index == b.style_sheet_index)
  360. return a.rule_index < b.rule_index;
  361. return a.style_sheet_index < b.style_sheet_index;
  362. }
  363. return a_specificity < b_specificity;
  364. });
  365. }
  366. void StyleComputer::for_each_property_expanding_shorthands(PropertyID property_id, StyleValue const& value, AllowUnresolved allow_unresolved, Function<void(PropertyID, StyleValue const&)> const& set_longhand_property)
  367. {
  368. auto map_logical_property_to_real_property = [](PropertyID property_id) -> Optional<PropertyID> {
  369. // FIXME: Honor writing-mode, direction and text-orientation.
  370. switch (property_id) {
  371. case PropertyID::MarginBlockStart:
  372. return PropertyID::MarginTop;
  373. case PropertyID::MarginBlockEnd:
  374. return PropertyID::MarginBottom;
  375. case PropertyID::MarginInlineStart:
  376. return PropertyID::MarginLeft;
  377. case PropertyID::MarginInlineEnd:
  378. return PropertyID::MarginRight;
  379. case PropertyID::PaddingBlockStart:
  380. return PropertyID::PaddingTop;
  381. case PropertyID::PaddingBlockEnd:
  382. return PropertyID::PaddingBottom;
  383. case PropertyID::PaddingInlineStart:
  384. return PropertyID::PaddingLeft;
  385. case PropertyID::PaddingInlineEnd:
  386. return PropertyID::PaddingRight;
  387. case PropertyID::InlineSize:
  388. return PropertyID::Width;
  389. case PropertyID::InsetBlockStart:
  390. return PropertyID::Top;
  391. case PropertyID::InsetBlockEnd:
  392. return PropertyID::Bottom;
  393. case PropertyID::InsetInlineStart:
  394. return PropertyID::Left;
  395. case PropertyID::InsetInlineEnd:
  396. return PropertyID::Right;
  397. case PropertyID::WebkitAppearance:
  398. return PropertyID::Appearance;
  399. default:
  400. return {};
  401. }
  402. };
  403. struct StartAndEndPropertyIDs {
  404. PropertyID start;
  405. PropertyID end;
  406. };
  407. auto map_logical_property_to_real_properties = [](PropertyID property_id) -> Optional<StartAndEndPropertyIDs> {
  408. // FIXME: Honor writing-mode, direction and text-orientation.
  409. switch (property_id) {
  410. case PropertyID::MarginBlock:
  411. return StartAndEndPropertyIDs { PropertyID::MarginTop, PropertyID::MarginBottom };
  412. case PropertyID::MarginInline:
  413. return StartAndEndPropertyIDs { PropertyID::MarginLeft, PropertyID::MarginRight };
  414. case PropertyID::PaddingBlock:
  415. return StartAndEndPropertyIDs { PropertyID::PaddingTop, PropertyID::PaddingBottom };
  416. case PropertyID::PaddingInline:
  417. return StartAndEndPropertyIDs { PropertyID::PaddingLeft, PropertyID::PaddingRight };
  418. case PropertyID::InsetBlock:
  419. return StartAndEndPropertyIDs { PropertyID::Top, PropertyID::Bottom };
  420. case PropertyID::InsetInline:
  421. return StartAndEndPropertyIDs { PropertyID::Left, PropertyID::Right };
  422. default:
  423. return {};
  424. }
  425. };
  426. if (auto real_property_id = map_logical_property_to_real_property(property_id); real_property_id.has_value()) {
  427. for_each_property_expanding_shorthands(real_property_id.value(), value, allow_unresolved, set_longhand_property);
  428. return;
  429. }
  430. if (auto real_property_ids = map_logical_property_to_real_properties(property_id); real_property_ids.has_value()) {
  431. if (value.is_value_list() && value.as_value_list().size() == 2) {
  432. auto const& start = value.as_value_list().values()[0];
  433. auto const& end = value.as_value_list().values()[1];
  434. for_each_property_expanding_shorthands(real_property_ids->start, start, allow_unresolved, set_longhand_property);
  435. for_each_property_expanding_shorthands(real_property_ids->end, end, allow_unresolved, set_longhand_property);
  436. return;
  437. }
  438. for_each_property_expanding_shorthands(real_property_ids->start, value, allow_unresolved, set_longhand_property);
  439. for_each_property_expanding_shorthands(real_property_ids->end, value, allow_unresolved, set_longhand_property);
  440. return;
  441. }
  442. if (value.is_shorthand()) {
  443. auto& shorthand_value = value.as_shorthand();
  444. auto& properties = shorthand_value.sub_properties();
  445. auto& values = shorthand_value.values();
  446. for (size_t i = 0; i < properties.size(); ++i)
  447. for_each_property_expanding_shorthands(properties[i], values[i], allow_unresolved, set_longhand_property);
  448. return;
  449. }
  450. auto assign_edge_values = [&](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) {
  451. if (values.size() == 4) {
  452. set_longhand_property(top_property, values[0]);
  453. set_longhand_property(right_property, values[1]);
  454. set_longhand_property(bottom_property, values[2]);
  455. set_longhand_property(left_property, values[3]);
  456. } else if (values.size() == 3) {
  457. set_longhand_property(top_property, values[0]);
  458. set_longhand_property(right_property, values[1]);
  459. set_longhand_property(bottom_property, values[2]);
  460. set_longhand_property(left_property, values[1]);
  461. } else if (values.size() == 2) {
  462. set_longhand_property(top_property, values[0]);
  463. set_longhand_property(right_property, values[1]);
  464. set_longhand_property(bottom_property, values[0]);
  465. set_longhand_property(left_property, values[1]);
  466. } else if (values.size() == 1) {
  467. set_longhand_property(top_property, values[0]);
  468. set_longhand_property(right_property, values[0]);
  469. set_longhand_property(bottom_property, values[0]);
  470. set_longhand_property(left_property, values[0]);
  471. }
  472. };
  473. if (property_id == CSS::PropertyID::Border) {
  474. for_each_property_expanding_shorthands(CSS::PropertyID::BorderTop, value, allow_unresolved, set_longhand_property);
  475. for_each_property_expanding_shorthands(CSS::PropertyID::BorderRight, value, allow_unresolved, set_longhand_property);
  476. for_each_property_expanding_shorthands(CSS::PropertyID::BorderBottom, value, allow_unresolved, set_longhand_property);
  477. for_each_property_expanding_shorthands(CSS::PropertyID::BorderLeft, value, allow_unresolved, set_longhand_property);
  478. // FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands
  479. return;
  480. }
  481. if (property_id == CSS::PropertyID::BorderStyle) {
  482. if (value.is_value_list()) {
  483. auto const& values_list = value.as_value_list();
  484. assign_edge_values(PropertyID::BorderTopStyle, PropertyID::BorderRightStyle, PropertyID::BorderBottomStyle, PropertyID::BorderLeftStyle, values_list.values());
  485. return;
  486. }
  487. set_longhand_property(CSS::PropertyID::BorderTopStyle, value);
  488. set_longhand_property(CSS::PropertyID::BorderRightStyle, value);
  489. set_longhand_property(CSS::PropertyID::BorderBottomStyle, value);
  490. set_longhand_property(CSS::PropertyID::BorderLeftStyle, value);
  491. return;
  492. }
  493. if (property_id == CSS::PropertyID::BorderWidth) {
  494. if (value.is_value_list()) {
  495. auto const& values_list = value.as_value_list();
  496. assign_edge_values(PropertyID::BorderTopWidth, PropertyID::BorderRightWidth, PropertyID::BorderBottomWidth, PropertyID::BorderLeftWidth, values_list.values());
  497. return;
  498. }
  499. set_longhand_property(CSS::PropertyID::BorderTopWidth, value);
  500. set_longhand_property(CSS::PropertyID::BorderRightWidth, value);
  501. set_longhand_property(CSS::PropertyID::BorderBottomWidth, value);
  502. set_longhand_property(CSS::PropertyID::BorderLeftWidth, value);
  503. return;
  504. }
  505. if (property_id == CSS::PropertyID::BorderColor) {
  506. if (value.is_value_list()) {
  507. auto const& values_list = value.as_value_list();
  508. assign_edge_values(PropertyID::BorderTopColor, PropertyID::BorderRightColor, PropertyID::BorderBottomColor, PropertyID::BorderLeftColor, values_list.values());
  509. return;
  510. }
  511. set_longhand_property(CSS::PropertyID::BorderTopColor, value);
  512. set_longhand_property(CSS::PropertyID::BorderRightColor, value);
  513. set_longhand_property(CSS::PropertyID::BorderBottomColor, value);
  514. set_longhand_property(CSS::PropertyID::BorderLeftColor, value);
  515. return;
  516. }
  517. if (property_id == CSS::PropertyID::BackgroundPosition) {
  518. if (value.is_position()) {
  519. auto const& position = value.as_position();
  520. set_longhand_property(CSS::PropertyID::BackgroundPositionX, position.edge_x());
  521. set_longhand_property(CSS::PropertyID::BackgroundPositionY, position.edge_y());
  522. } else if (value.is_value_list()) {
  523. // Expand background-position layer list into separate lists for x and y positions:
  524. auto const& values_list = value.as_value_list();
  525. StyleValueVector x_positions {};
  526. StyleValueVector y_positions {};
  527. x_positions.ensure_capacity(values_list.size());
  528. y_positions.ensure_capacity(values_list.size());
  529. for (auto& layer : values_list.values()) {
  530. if (layer->is_position()) {
  531. auto const& position = layer->as_position();
  532. x_positions.unchecked_append(position.edge_x());
  533. y_positions.unchecked_append(position.edge_y());
  534. } else {
  535. x_positions.unchecked_append(layer);
  536. y_positions.unchecked_append(layer);
  537. }
  538. }
  539. set_longhand_property(CSS::PropertyID::BackgroundPositionX, StyleValueList::create(move(x_positions), values_list.separator()));
  540. set_longhand_property(CSS::PropertyID::BackgroundPositionY, StyleValueList::create(move(y_positions), values_list.separator()));
  541. } else {
  542. set_longhand_property(CSS::PropertyID::BackgroundPositionX, value);
  543. set_longhand_property(CSS::PropertyID::BackgroundPositionY, value);
  544. }
  545. return;
  546. }
  547. if (property_id == CSS::PropertyID::Inset) {
  548. if (value.is_value_list()) {
  549. auto const& values_list = value.as_value_list();
  550. assign_edge_values(PropertyID::Top, PropertyID::Right, PropertyID::Bottom, PropertyID::Left, values_list.values());
  551. return;
  552. }
  553. set_longhand_property(CSS::PropertyID::Top, value);
  554. set_longhand_property(CSS::PropertyID::Right, value);
  555. set_longhand_property(CSS::PropertyID::Bottom, value);
  556. set_longhand_property(CSS::PropertyID::Left, value);
  557. return;
  558. }
  559. if (property_id == CSS::PropertyID::Margin) {
  560. if (value.is_value_list()) {
  561. auto const& values_list = value.as_value_list();
  562. assign_edge_values(PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, values_list.values());
  563. return;
  564. }
  565. set_longhand_property(CSS::PropertyID::MarginTop, value);
  566. set_longhand_property(CSS::PropertyID::MarginRight, value);
  567. set_longhand_property(CSS::PropertyID::MarginBottom, value);
  568. set_longhand_property(CSS::PropertyID::MarginLeft, value);
  569. return;
  570. }
  571. if (property_id == CSS::PropertyID::Padding) {
  572. if (value.is_value_list()) {
  573. auto const& values_list = value.as_value_list();
  574. assign_edge_values(PropertyID::PaddingTop, PropertyID::PaddingRight, PropertyID::PaddingBottom, PropertyID::PaddingLeft, values_list.values());
  575. return;
  576. }
  577. set_longhand_property(CSS::PropertyID::PaddingTop, value);
  578. set_longhand_property(CSS::PropertyID::PaddingRight, value);
  579. set_longhand_property(CSS::PropertyID::PaddingBottom, value);
  580. set_longhand_property(CSS::PropertyID::PaddingLeft, value);
  581. return;
  582. }
  583. if (property_id == CSS::PropertyID::Gap || property_id == CSS::PropertyID::GridGap) {
  584. if (value.is_value_list()) {
  585. auto const& values_list = value.as_value_list();
  586. set_longhand_property(CSS::PropertyID::RowGap, values_list.values()[0]);
  587. set_longhand_property(CSS::PropertyID::ColumnGap, values_list.values()[1]);
  588. return;
  589. }
  590. set_longhand_property(CSS::PropertyID::RowGap, value);
  591. set_longhand_property(CSS::PropertyID::ColumnGap, value);
  592. return;
  593. }
  594. if (property_id == CSS::PropertyID::RowGap || property_id == CSS::PropertyID::GridRowGap) {
  595. set_longhand_property(CSS::PropertyID::RowGap, value);
  596. return;
  597. }
  598. if (property_id == CSS::PropertyID::ColumnGap || property_id == CSS::PropertyID::GridColumnGap) {
  599. set_longhand_property(CSS::PropertyID::ColumnGap, value);
  600. return;
  601. }
  602. if (property_id == CSS::PropertyID::MaxInlineSize || property_id == CSS::PropertyID::MinInlineSize) {
  603. // FIXME: Use writing-mode to determine if we should set width or height.
  604. bool is_horizontal = true;
  605. if (is_horizontal) {
  606. if (property_id == CSS::PropertyID::MaxInlineSize) {
  607. set_longhand_property(CSS::PropertyID::MaxWidth, value);
  608. } else {
  609. set_longhand_property(CSS::PropertyID::MinWidth, value);
  610. }
  611. } else {
  612. if (property_id == CSS::PropertyID::MaxInlineSize) {
  613. set_longhand_property(CSS::PropertyID::MaxHeight, value);
  614. } else {
  615. set_longhand_property(CSS::PropertyID::MinHeight, value);
  616. }
  617. }
  618. return;
  619. }
  620. if (property_id == CSS::PropertyID::Transition) {
  621. if (!value.is_transition()) {
  622. // Handle `none` as a shorthand for `all 0s ease 0s`.
  623. set_longhand_property(CSS::PropertyID::TransitionProperty, IdentifierStyleValue::create(CSS::ValueID::All));
  624. set_longhand_property(CSS::PropertyID::TransitionDuration, TimeStyleValue::create(CSS::Time::make_seconds(0)));
  625. set_longhand_property(CSS::PropertyID::TransitionDelay, TimeStyleValue::create(CSS::Time::make_seconds(0)));
  626. set_longhand_property(CSS::PropertyID::TransitionTimingFunction, IdentifierStyleValue::create(CSS::ValueID::Ease));
  627. return;
  628. }
  629. auto const& transitions = value.as_transition().transitions();
  630. Array<Vector<ValueComparingNonnullRefPtr<StyleValue const>>, 4> transition_values;
  631. for (auto const& transition : transitions) {
  632. transition_values[0].append(*transition.property_name);
  633. transition_values[1].append(transition.duration.as_style_value());
  634. transition_values[2].append(transition.delay.as_style_value());
  635. if (transition.easing)
  636. transition_values[3].append(*transition.easing);
  637. }
  638. set_longhand_property(CSS::PropertyID::TransitionProperty, StyleValueList::create(move(transition_values[0]), StyleValueList::Separator::Comma));
  639. set_longhand_property(CSS::PropertyID::TransitionDuration, StyleValueList::create(move(transition_values[1]), StyleValueList::Separator::Comma));
  640. set_longhand_property(CSS::PropertyID::TransitionDelay, StyleValueList::create(move(transition_values[2]), StyleValueList::Separator::Comma));
  641. set_longhand_property(CSS::PropertyID::TransitionTimingFunction, StyleValueList::create(move(transition_values[3]), StyleValueList::Separator::Comma));
  642. return;
  643. }
  644. if (property_id == CSS::PropertyID::Float) {
  645. auto ident = value.to_identifier();
  646. // FIXME: Honor writing-mode, direction and text-orientation.
  647. if (ident == CSS::ValueID::InlineStart) {
  648. set_longhand_property(CSS::PropertyID::Float, IdentifierStyleValue::create(CSS::ValueID::Left));
  649. return;
  650. } else if (ident == CSS::ValueID::InlineEnd) {
  651. set_longhand_property(CSS::PropertyID::Float, IdentifierStyleValue::create(CSS::ValueID::Right));
  652. return;
  653. }
  654. }
  655. if (property_is_shorthand(property_id)) {
  656. // ShorthandStyleValue was handled already.
  657. // That means if we got here, that `value` must be a CSS-wide keyword, which we should apply to our longhand properties.
  658. // We don't directly call `set_longhand_property()` because the longhands might have longhands of their own.
  659. // (eg `grid` -> `grid-template` -> `grid-template-areas` & `grid-template-rows` & `grid-template-columns`)
  660. // Forget this requirement if we're ignoring unresolved values and the value is unresolved.
  661. VERIFY(value.is_css_wide_keyword() || (allow_unresolved == AllowUnresolved::Yes && value.is_unresolved()));
  662. for (auto longhand : longhands_for_shorthand(property_id))
  663. for_each_property_expanding_shorthands(longhand, value, allow_unresolved, set_longhand_property);
  664. return;
  665. }
  666. set_longhand_property(property_id, value);
  667. }
  668. void StyleComputer::set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, CSS::CSSStyleDeclaration const* declaration, StyleProperties::PropertyValues const& properties_for_revert, StyleProperties::Important important)
  669. {
  670. for_each_property_expanding_shorthands(property_id, value, AllowUnresolved::No, [&](PropertyID shorthand_id, StyleValue const& shorthand_value) {
  671. if (shorthand_value.is_revert()) {
  672. auto& property_in_previous_cascade_origin = properties_for_revert[to_underlying(shorthand_id)];
  673. if (property_in_previous_cascade_origin.style)
  674. style.set_property(shorthand_id, *property_in_previous_cascade_origin.style, property_in_previous_cascade_origin.declaration, StyleProperties::Inherited::No, important);
  675. } else {
  676. style.set_property(shorthand_id, shorthand_value, declaration, StyleProperties::Inherited::No, important);
  677. }
  678. });
  679. }
  680. void StyleComputer::set_all_properties(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, StyleProperties& style, StyleValue const& value, DOM::Document& document, CSS::CSSStyleDeclaration const* declaration, StyleProperties::PropertyValues const& properties_for_revert, StyleProperties::Important important) const
  681. {
  682. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  683. auto property_id = (CSS::PropertyID)i;
  684. if (value.is_revert()) {
  685. style.m_property_values[to_underlying(property_id)] = properties_for_revert[to_underlying(property_id)];
  686. style.m_property_values[to_underlying(property_id)].important = important;
  687. continue;
  688. }
  689. if (value.is_unset()) {
  690. if (is_inherited_property(property_id))
  691. style.m_property_values[to_underlying(property_id)] = { get_inherit_value(document.realm(), property_id, &element, pseudo_element), nullptr };
  692. else
  693. style.m_property_values[to_underlying(property_id)] = { property_initial_value(document.realm(), property_id), nullptr };
  694. style.m_property_values[to_underlying(property_id)].important = important;
  695. continue;
  696. }
  697. NonnullRefPtr<StyleValue> property_value = value;
  698. if (property_value->is_unresolved())
  699. property_value = Parser::Parser::resolve_unresolved_style_value(Parser::ParsingContext { document }, element, pseudo_element, property_id, property_value->as_unresolved());
  700. if (!property_value->is_unresolved())
  701. set_property_expanding_shorthands(style, property_id, property_value, declaration, properties_for_revert);
  702. style.m_property_values[to_underlying(property_id)].important = important;
  703. set_property_expanding_shorthands(style, property_id, value, declaration, properties_for_revert, important);
  704. }
  705. }
  706. void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, Vector<MatchingRule> const& matching_rules, CascadeOrigin cascade_origin, Important important) const
  707. {
  708. auto properties_for_revert = style.properties();
  709. for (auto const& match : matching_rules) {
  710. for (auto const& property : match.rule->declaration().properties()) {
  711. if (important != property.important)
  712. continue;
  713. if (property.property_id == CSS::PropertyID::All) {
  714. set_all_properties(element, pseudo_element, style, property.value, m_document, &match.rule->declaration(), properties_for_revert, important == Important::Yes ? StyleProperties::Important::Yes : StyleProperties::Important::No);
  715. continue;
  716. }
  717. auto property_value = property.value;
  718. if (property.value->is_unresolved())
  719. property_value = Parser::Parser::resolve_unresolved_style_value(Parser::ParsingContext { document() }, element, pseudo_element, property.property_id, property.value->as_unresolved());
  720. if (!property_value->is_unresolved())
  721. set_property_expanding_shorthands(style, property.property_id, property_value, &match.rule->declaration(), properties_for_revert, important == Important::Yes ? StyleProperties::Important::Yes : StyleProperties::Important::No);
  722. }
  723. }
  724. if (cascade_origin == CascadeOrigin::Author && !pseudo_element.has_value()) {
  725. if (auto const inline_style = element.inline_style()) {
  726. for (auto const& property : inline_style->properties()) {
  727. if (important != property.important)
  728. continue;
  729. if (property.property_id == CSS::PropertyID::All) {
  730. set_all_properties(element, pseudo_element, style, property.value, m_document, inline_style, properties_for_revert, important == Important::Yes ? StyleProperties::Important::Yes : StyleProperties::Important::No);
  731. continue;
  732. }
  733. auto property_value = property.value;
  734. if (property.value->is_unresolved())
  735. property_value = Parser::Parser::resolve_unresolved_style_value(Parser::ParsingContext { document() }, element, pseudo_element, property.property_id, property.value->as_unresolved());
  736. if (!property_value->is_unresolved())
  737. set_property_expanding_shorthands(style, property.property_id, property_value, inline_style, properties_for_revert, important == Important::Yes ? StyleProperties::Important::Yes : StyleProperties::Important::No);
  738. }
  739. }
  740. }
  741. }
  742. static void cascade_custom_properties(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, Vector<MatchingRule> const& matching_rules)
  743. {
  744. size_t needed_capacity = 0;
  745. for (auto const& matching_rule : matching_rules)
  746. needed_capacity += matching_rule.rule->declaration().custom_properties().size();
  747. if (!pseudo_element.has_value()) {
  748. if (auto const inline_style = element.inline_style())
  749. needed_capacity += inline_style->custom_properties().size();
  750. }
  751. HashMap<FlyString, StyleProperty> custom_properties;
  752. custom_properties.ensure_capacity(needed_capacity);
  753. for (auto const& matching_rule : matching_rules) {
  754. for (auto const& it : matching_rule.rule->declaration().custom_properties())
  755. custom_properties.set(it.key, it.value);
  756. }
  757. if (!pseudo_element.has_value()) {
  758. if (auto const inline_style = element.inline_style()) {
  759. for (auto const& it : inline_style->custom_properties())
  760. custom_properties.set(it.key, it.value);
  761. }
  762. }
  763. element.set_custom_properties(pseudo_element, move(custom_properties));
  764. }
  765. static NonnullRefPtr<StyleValue const> interpolate_value(DOM::Element& element, StyleValue const& from, StyleValue const& to, float delta);
  766. template<typename T>
  767. static T interpolate_raw(T from, T to, float delta)
  768. {
  769. if constexpr (IsSame<T, double>) {
  770. return from + (to - from) * static_cast<double>(delta);
  771. } else {
  772. return static_cast<RemoveCVReference<T>>(from + (to - from) * delta);
  773. }
  774. }
  775. // A null return value means the interpolated matrix was not invertible or otherwise invalid
  776. static RefPtr<StyleValue const> interpolate_transform(DOM::Element& element, StyleValue const& from, StyleValue const& to, float delta)
  777. {
  778. // Note that the spec uses column-major notation, so all the matrix indexing is reversed.
  779. static constexpr auto make_transformation = [](TransformationStyleValue const& transformation) -> Optional<Transformation> {
  780. Vector<TransformValue> values;
  781. for (auto const& value : transformation.values()) {
  782. switch (value->type()) {
  783. case StyleValue::Type::Angle:
  784. values.append(AngleOrCalculated { value->as_angle().angle() });
  785. break;
  786. case StyleValue::Type::Calculated:
  787. values.append(LengthPercentage { value->as_calculated() });
  788. break;
  789. case StyleValue::Type::Length:
  790. values.append(LengthPercentage { value->as_length().length() });
  791. break;
  792. case StyleValue::Type::Percentage:
  793. values.append(LengthPercentage { value->as_percentage().percentage() });
  794. break;
  795. case StyleValue::Type::Number:
  796. values.append(NumberPercentage { Number(Number::Type::Number, value->as_number().number()) });
  797. break;
  798. default:
  799. return {};
  800. }
  801. }
  802. return Transformation { transformation.transform_function(), move(values) };
  803. };
  804. static constexpr auto transformation_style_value_to_matrix = [](DOM::Element& element, TransformationStyleValue const& value) -> Optional<FloatMatrix4x4> {
  805. auto transformation = make_transformation(value.as_transformation());
  806. if (!transformation.has_value())
  807. return {};
  808. Optional<Painting::PaintableBox const&> paintable_box;
  809. if (auto layout_node = element.layout_node()) {
  810. if (auto paintable = layout_node->paintable(); paintable && is<Painting::PaintableBox>(paintable))
  811. paintable_box = *static_cast<Painting::PaintableBox*>(paintable);
  812. }
  813. if (auto matrix = transformation->to_matrix(paintable_box); !matrix.is_error())
  814. return matrix.value();
  815. return {};
  816. };
  817. static constexpr auto style_value_to_matrix = [](DOM::Element& element, StyleValue const& value) -> FloatMatrix4x4 {
  818. if (value.is_transformation())
  819. return transformation_style_value_to_matrix(element, value.as_transformation()).value_or(FloatMatrix4x4::identity());
  820. // This encompasses both the allowed value "none" and any invalid values
  821. if (!value.is_value_list())
  822. return FloatMatrix4x4::identity();
  823. auto matrix = FloatMatrix4x4::identity();
  824. for (auto const& value_element : value.as_value_list().values()) {
  825. if (value_element->is_transformation()) {
  826. if (auto value_matrix = transformation_style_value_to_matrix(element, value_element->as_transformation()); value_matrix.has_value())
  827. matrix = matrix * value_matrix.value();
  828. }
  829. }
  830. return matrix;
  831. };
  832. struct DecomposedValues {
  833. FloatVector3 translation;
  834. FloatVector3 scale;
  835. FloatVector3 skew;
  836. FloatVector4 rotation;
  837. FloatVector4 perspective;
  838. };
  839. // https://drafts.csswg.org/css-transforms-2/#decomposing-a-3d-matrix
  840. static constexpr auto decompose = [](FloatMatrix4x4 matrix) -> Optional<DecomposedValues> {
  841. // https://drafts.csswg.org/css-transforms-1/#supporting-functions
  842. static constexpr auto combine = [](auto a, auto b, float ascl, float bscl) {
  843. return FloatVector3 {
  844. ascl * a[0] + bscl * b[0],
  845. ascl * a[1] + bscl * b[1],
  846. ascl * a[2] + bscl * b[2],
  847. };
  848. };
  849. // Normalize the matrix.
  850. if (matrix(3, 3) == 0.f)
  851. return {};
  852. for (int i = 0; i < 4; i++)
  853. for (int j = 0; j < 4; j++)
  854. matrix(i, j) /= matrix(3, 3);
  855. // perspectiveMatrix is used to solve for perspective, but it also provides
  856. // an easy way to test for singularity of the upper 3x3 component.
  857. auto perspective_matrix = matrix;
  858. for (int i = 0; i < 3; i++)
  859. perspective_matrix(3, i) = 0.f;
  860. perspective_matrix(3, 3) = 1.f;
  861. if (!perspective_matrix.is_invertible())
  862. return {};
  863. DecomposedValues values;
  864. // First, isolate perspective.
  865. if (matrix(3, 0) != 0.f || matrix(3, 1) != 0.f || matrix(3, 2) != 0.f) {
  866. // rightHandSide is the right hand side of the equation.
  867. // Note: It is the bottom side in a row-major matrix
  868. FloatVector4 bottom_side = {
  869. matrix(3, 0),
  870. matrix(3, 1),
  871. matrix(3, 2),
  872. matrix(3, 3),
  873. };
  874. // Solve the equation by inverting perspectiveMatrix and multiplying
  875. // rightHandSide by the inverse.
  876. auto inverse_perspective_matrix = perspective_matrix.inverse();
  877. auto transposed_inverse_perspective_matrix = inverse_perspective_matrix.transpose();
  878. values.perspective = transposed_inverse_perspective_matrix * bottom_side;
  879. } else {
  880. // No perspective.
  881. values.perspective = { 0.0, 0.0, 0.0, 1.0 };
  882. }
  883. // Next take care of translation
  884. for (int i = 0; i < 3; i++)
  885. values.translation[i] = matrix(i, 3);
  886. // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
  887. FloatVector3 row[3];
  888. for (int i = 0; i < 3; i++)
  889. row[i] = { matrix(0, i), matrix(1, i), matrix(2, i) };
  890. // Compute X scale factor and normalize first row.
  891. values.scale[0] = row[0].length();
  892. row[0].normalize();
  893. // Compute XY shear factor and make 2nd row orthogonal to 1st.
  894. values.skew[0] = row[0].dot(row[1]);
  895. row[1] = combine(row[1], row[0], 1.f, -values.skew[0]);
  896. // Now, compute Y scale and normalize 2nd row.
  897. values.scale[1] = row[1].length();
  898. row[1].normalize();
  899. values.skew[0] /= values.scale[1];
  900. // Compute XZ and YZ shears, orthogonalize 3rd row
  901. values.skew[1] = row[0].dot(row[2]);
  902. row[2] = combine(row[2], row[0], 1.f, -values.skew[1]);
  903. values.skew[2] = row[1].dot(row[2]);
  904. row[2] = combine(row[2], row[1], 1.f, -values.skew[2]);
  905. // Next, get Z scale and normalize 3rd row.
  906. values.scale[2] = row[2].length();
  907. row[2].normalize();
  908. values.skew[1] /= values.scale[2];
  909. values.skew[2] /= values.scale[2];
  910. // At this point, the matrix (in rows) is orthonormal.
  911. // Check for a coordinate system flip. If the determinant
  912. // is -1, then negate the matrix and the scaling factors.
  913. auto pdum3 = row[1].cross(row[2]);
  914. if (row[0].dot(pdum3) < 0.f) {
  915. for (int i = 0; i < 3; i++) {
  916. values.scale[i] *= -1.f;
  917. row[i][0] *= -1.f;
  918. row[i][1] *= -1.f;
  919. row[i][2] *= -1.f;
  920. }
  921. }
  922. // Now, get the rotations out
  923. values.rotation[0] = 0.5f * sqrt(max(1.f + row[0][0] - row[1][1] - row[2][2], 0.f));
  924. values.rotation[1] = 0.5f * sqrt(max(1.f - row[0][0] + row[1][1] - row[2][2], 0.f));
  925. values.rotation[2] = 0.5f * sqrt(max(1.f - row[0][0] - row[1][1] + row[2][2], 0.f));
  926. values.rotation[3] = 0.5f * sqrt(max(1.f + row[0][0] + row[1][1] + row[2][2], 0.f));
  927. if (row[2][1] > row[1][2])
  928. values.rotation[0] = -values.rotation[0];
  929. if (row[0][2] > row[2][0])
  930. values.rotation[1] = -values.rotation[1];
  931. if (row[1][0] > row[0][1])
  932. values.rotation[2] = -values.rotation[2];
  933. // FIXME: This accounts for the fact that the browser coordinate system is left-handed instead of right-handed.
  934. // The reason for this is that the positive Y-axis direction points down instead of up. To fix this, we
  935. // invert the Y axis. However, it feels like the spec pseudo-code above should have taken something like
  936. // this into account, so we're probably doing something else wrong.
  937. values.rotation[2] *= -1;
  938. return values;
  939. };
  940. // https://drafts.csswg.org/css-transforms-2/#recomposing-to-a-3d-matrix
  941. static constexpr auto recompose = [](DecomposedValues const& values) -> FloatMatrix4x4 {
  942. auto matrix = FloatMatrix4x4::identity();
  943. // apply perspective
  944. for (int i = 0; i < 4; i++)
  945. matrix(3, i) = values.perspective[i];
  946. // apply translation
  947. for (int i = 0; i < 4; i++) {
  948. for (int j = 0; j < 3; j++)
  949. matrix(i, 3) += values.translation[j] * matrix(i, j);
  950. }
  951. // apply rotation
  952. auto x = values.rotation[0];
  953. auto y = values.rotation[1];
  954. auto z = values.rotation[2];
  955. auto w = values.rotation[3];
  956. // Construct a composite rotation matrix from the quaternion values
  957. // rotationMatrix is a identity 4x4 matrix initially
  958. auto rotation_matrix = FloatMatrix4x4::identity();
  959. rotation_matrix(0, 0) = 1.f - 2.f * (y * y + z * z);
  960. rotation_matrix(1, 0) = 2.f * (x * y - z * w);
  961. rotation_matrix(2, 0) = 2.f * (x * z + y * w);
  962. rotation_matrix(0, 1) = 2.f * (x * y + z * w);
  963. rotation_matrix(1, 1) = 1.f - 2.f * (x * x + z * z);
  964. rotation_matrix(2, 1) = 2.f * (y * z - x * w);
  965. rotation_matrix(0, 2) = 2.f * (x * z - y * w);
  966. rotation_matrix(1, 2) = 2.f * (y * z + x * w);
  967. rotation_matrix(2, 2) = 1.f - 2.f * (x * x + y * y);
  968. matrix = matrix * rotation_matrix;
  969. // apply skew
  970. // temp is a identity 4x4 matrix initially
  971. auto temp = FloatMatrix4x4::identity();
  972. if (values.skew[2] != 0.f) {
  973. temp(1, 2) = values.skew[2];
  974. matrix = matrix * temp;
  975. }
  976. if (values.skew[1] != 0.f) {
  977. temp(1, 2) = 0.f;
  978. temp(0, 2) = values.skew[1];
  979. matrix = matrix * temp;
  980. }
  981. if (values.skew[0] != 0.f) {
  982. temp(0, 2) = 0.f;
  983. temp(0, 1) = values.skew[0];
  984. matrix = matrix * temp;
  985. }
  986. // apply scale
  987. for (int i = 0; i < 3; i++) {
  988. for (int j = 0; j < 4; j++)
  989. matrix(j, i) *= values.scale[i];
  990. }
  991. return matrix;
  992. };
  993. // https://drafts.csswg.org/css-transforms-2/#interpolation-of-decomposed-3d-matrix-values
  994. static constexpr auto interpolate = [](DecomposedValues& from, DecomposedValues& to, float delta) -> DecomposedValues {
  995. auto product = clamp(from.rotation.dot(to.rotation), -1.0f, 1.0f);
  996. FloatVector4 interpolated_rotation;
  997. if (fabsf(product) == 1.0f) {
  998. interpolated_rotation = from.rotation;
  999. } else {
  1000. auto theta = acos(product);
  1001. auto w = sin(delta * theta) / sqrtf(1.0f - product * product);
  1002. for (int i = 0; i < 4; i++) {
  1003. from.rotation[i] *= cos(delta * theta) - product * w;
  1004. to.rotation[i] *= w;
  1005. interpolated_rotation[i] = from.rotation[i] + to.rotation[i];
  1006. }
  1007. }
  1008. return {
  1009. interpolate_raw(from.translation, to.translation, delta),
  1010. interpolate_raw(from.scale, to.scale, delta),
  1011. interpolate_raw(from.skew, to.skew, delta),
  1012. interpolated_rotation,
  1013. interpolate_raw(from.perspective, to.perspective, delta),
  1014. };
  1015. };
  1016. auto from_matrix = style_value_to_matrix(element, from);
  1017. auto to_matrix = style_value_to_matrix(element, to);
  1018. auto from_decomposed = decompose(from_matrix);
  1019. auto to_decomposed = decompose(to_matrix);
  1020. if (!from_decomposed.has_value() || !to_decomposed.has_value())
  1021. return {};
  1022. auto interpolated_decomposed = interpolate(from_decomposed.value(), to_decomposed.value(), delta);
  1023. auto interpolated = recompose(interpolated_decomposed);
  1024. StyleValueVector values;
  1025. values.ensure_capacity(16);
  1026. for (int i = 0; i < 16; i++)
  1027. values.append(NumberStyleValue::create(static_cast<double>(interpolated(i % 4, i / 4))));
  1028. return StyleValueList::create({ TransformationStyleValue::create(TransformFunction::Matrix3d, move(values)) }, StyleValueList::Separator::Comma);
  1029. }
  1030. static Color interpolate_color(Color from, Color to, float delta)
  1031. {
  1032. // https://drafts.csswg.org/css-color/#interpolation-space
  1033. // If the host syntax does not define what color space interpolation should take place in, it defaults to Oklab.
  1034. auto from_oklab = from.to_oklab();
  1035. auto to_oklab = to.to_oklab();
  1036. auto color = Color::from_oklab(
  1037. interpolate_raw(from_oklab.L, to_oklab.L, delta),
  1038. interpolate_raw(from_oklab.a, to_oklab.a, delta),
  1039. interpolate_raw(from_oklab.b, to_oklab.b, delta));
  1040. color.set_alpha(interpolate_raw(from.alpha(), to.alpha(), delta));
  1041. return color;
  1042. }
  1043. static NonnullRefPtr<StyleValue const> interpolate_box_shadow(DOM::Element& element, StyleValue const& from, StyleValue const& to, float delta)
  1044. {
  1045. // https://drafts.csswg.org/css-backgrounds/#box-shadow
  1046. // Animation type: by computed value, treating none as a zero-item list and appending blank shadows
  1047. // (transparent 0 0 0 0) with a corresponding inset keyword as needed to match the longer list if
  1048. // the shorter list is otherwise compatible with the longer one
  1049. static constexpr auto process_list = [](StyleValue const& value) {
  1050. StyleValueVector shadows;
  1051. if (value.is_value_list()) {
  1052. for (auto const& element : value.as_value_list().values()) {
  1053. if (element->is_shadow())
  1054. shadows.append(element);
  1055. }
  1056. } else if (value.is_shadow()) {
  1057. shadows.append(value);
  1058. } else if (!value.is_identifier() || value.as_identifier().id() != ValueID::None) {
  1059. VERIFY_NOT_REACHED();
  1060. }
  1061. return shadows;
  1062. };
  1063. static constexpr auto extend_list_if_necessary = [](StyleValueVector& values, StyleValueVector const& other) {
  1064. values.ensure_capacity(other.size());
  1065. for (size_t i = values.size(); i < other.size(); i++) {
  1066. values.unchecked_append(ShadowStyleValue::create(
  1067. Color::Transparent,
  1068. LengthStyleValue::create(Length::make_px(0)),
  1069. LengthStyleValue::create(Length::make_px(0)),
  1070. LengthStyleValue::create(Length::make_px(0)),
  1071. LengthStyleValue::create(Length::make_px(0)),
  1072. other[i]->as_shadow().placement()));
  1073. }
  1074. };
  1075. StyleValueVector from_shadows = process_list(from);
  1076. StyleValueVector to_shadows = process_list(to);
  1077. extend_list_if_necessary(from_shadows, to_shadows);
  1078. extend_list_if_necessary(to_shadows, from_shadows);
  1079. VERIFY(from_shadows.size() == to_shadows.size());
  1080. StyleValueVector result_shadows;
  1081. result_shadows.ensure_capacity(from_shadows.size());
  1082. for (size_t i = 0; i < from_shadows.size(); i++) {
  1083. auto const& from_shadow = from_shadows[i]->as_shadow();
  1084. auto const& to_shadow = to_shadows[i]->as_shadow();
  1085. auto result_shadow = ShadowStyleValue::create(
  1086. interpolate_color(from_shadow.color(), to_shadow.color(), delta),
  1087. interpolate_value(element, from_shadow.offset_x(), to_shadow.offset_x(), delta),
  1088. interpolate_value(element, from_shadow.offset_y(), to_shadow.offset_y(), delta),
  1089. interpolate_value(element, from_shadow.blur_radius(), to_shadow.blur_radius(), delta),
  1090. interpolate_value(element, from_shadow.spread_distance(), to_shadow.spread_distance(), delta),
  1091. delta >= 0.5f ? to_shadow.placement() : from_shadow.placement());
  1092. result_shadows.unchecked_append(result_shadow);
  1093. }
  1094. return StyleValueList::create(move(result_shadows), StyleValueList::Separator::Comma);
  1095. }
  1096. static NonnullRefPtr<StyleValue const> interpolate_value(DOM::Element& element, StyleValue const& from, StyleValue const& to, float delta)
  1097. {
  1098. if (from.type() != to.type()) {
  1099. // Handle mixed percentage and dimension types
  1100. // https://www.w3.org/TR/css-values-4/#mixed-percentages
  1101. struct NumericBaseTypeAndDefault {
  1102. CSSNumericType::BaseType base_type;
  1103. ValueComparingNonnullRefPtr<CSS::StyleValue> default_value;
  1104. };
  1105. static constexpr auto numeric_base_type_and_default = [](StyleValue const& value) -> Optional<NumericBaseTypeAndDefault> {
  1106. switch (value.type()) {
  1107. case StyleValue::Type::Angle: {
  1108. static auto default_angle_value = AngleStyleValue::create(Angle::make_degrees(0));
  1109. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Angle, default_angle_value };
  1110. }
  1111. case StyleValue::Type::Frequency: {
  1112. static auto default_frequency_value = FrequencyStyleValue::create(Frequency::make_hertz(0));
  1113. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Frequency, default_frequency_value };
  1114. }
  1115. case StyleValue::Type::Length: {
  1116. static auto default_length_value = LengthStyleValue::create(Length::make_px(0));
  1117. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Length, default_length_value };
  1118. }
  1119. case StyleValue::Type::Percentage: {
  1120. static auto default_percentage_value = PercentageStyleValue::create(Percentage { 0.0 });
  1121. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Percent, default_percentage_value };
  1122. }
  1123. case StyleValue::Type::Time: {
  1124. static auto default_time_value = TimeStyleValue::create(Time::make_seconds(0));
  1125. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Time, default_time_value };
  1126. }
  1127. default:
  1128. return {};
  1129. }
  1130. };
  1131. static constexpr auto to_calculation_node = [](StyleValue const& value) -> NonnullOwnPtr<CalculationNode> {
  1132. switch (value.type()) {
  1133. case StyleValue::Type::Angle:
  1134. return NumericCalculationNode::create(value.as_angle().angle());
  1135. case StyleValue::Type::Frequency:
  1136. return NumericCalculationNode::create(value.as_frequency().frequency());
  1137. case StyleValue::Type::Length:
  1138. return NumericCalculationNode::create(value.as_length().length());
  1139. case StyleValue::Type::Percentage:
  1140. return NumericCalculationNode::create(value.as_percentage().percentage());
  1141. case StyleValue::Type::Time:
  1142. return NumericCalculationNode::create(value.as_time().time());
  1143. default:
  1144. VERIFY_NOT_REACHED();
  1145. }
  1146. };
  1147. auto from_base_type_and_default = numeric_base_type_and_default(from);
  1148. auto to_base_type_and_default = numeric_base_type_and_default(to);
  1149. if (from_base_type_and_default.has_value() && to_base_type_and_default.has_value() && (from_base_type_and_default->base_type == CSSNumericType::BaseType::Percent || to_base_type_and_default->base_type == CSSNumericType::BaseType::Percent)) {
  1150. // This is an interpolation from a numeric unit to a percentage, or vice versa. The trick here is to
  1151. // interpolate two separate values. For example, consider an interpolation from 30px to 80%. It's quite
  1152. // hard to understand how this interpolation works, but if instead we rewrite the values as "30px + 0%" and
  1153. // "0px + 80%", then it is very simple to understand; we just interpolate each component separately.
  1154. auto interpolated_from = interpolate_value(element, from, from_base_type_and_default->default_value, delta);
  1155. auto interpolated_to = interpolate_value(element, to_base_type_and_default->default_value, to, delta);
  1156. Vector<NonnullOwnPtr<CalculationNode>> values;
  1157. values.ensure_capacity(2);
  1158. values.unchecked_append(to_calculation_node(interpolated_from));
  1159. values.unchecked_append(to_calculation_node(interpolated_to));
  1160. auto calc_node = SumCalculationNode::create(move(values));
  1161. return CalculatedStyleValue::create(move(calc_node), CSSNumericType { to_base_type_and_default->base_type, 1 });
  1162. }
  1163. return delta >= 0.5f ? to : from;
  1164. }
  1165. switch (from.type()) {
  1166. case StyleValue::Type::Angle:
  1167. return AngleStyleValue::create(Angle::make_degrees(interpolate_raw(from.as_angle().angle().to_degrees(), to.as_angle().angle().to_degrees(), delta)));
  1168. case StyleValue::Type::Color:
  1169. return ColorStyleValue::create(interpolate_color(from.as_color().color(), to.as_color().color(), delta));
  1170. case StyleValue::Type::Integer:
  1171. return IntegerStyleValue::create(interpolate_raw(from.as_integer().integer(), to.as_integer().integer(), delta));
  1172. case StyleValue::Type::Length: {
  1173. auto& from_length = from.as_length().length();
  1174. auto& to_length = to.as_length().length();
  1175. return LengthStyleValue::create(Length(interpolate_raw(from_length.raw_value(), to_length.raw_value(), delta), from_length.type()));
  1176. }
  1177. case StyleValue::Type::Number:
  1178. return NumberStyleValue::create(interpolate_raw(from.as_number().number(), to.as_number().number(), delta));
  1179. case StyleValue::Type::Percentage:
  1180. return PercentageStyleValue::create(Percentage(interpolate_raw(from.as_percentage().percentage().value(), to.as_percentage().percentage().value(), delta)));
  1181. case StyleValue::Type::Position: {
  1182. // https://www.w3.org/TR/css-values-4/#combine-positions
  1183. // FIXME: Interpolation of <position> is defined as the independent interpolation of each component (x, y) normalized as an offset from the top left corner as a <length-percentage>.
  1184. auto& from_position = from.as_position();
  1185. auto& to_position = to.as_position();
  1186. return PositionStyleValue::create(
  1187. interpolate_value(element, from_position.edge_x(), to_position.edge_x(), delta)->as_edge(),
  1188. interpolate_value(element, from_position.edge_y(), to_position.edge_y(), delta)->as_edge());
  1189. }
  1190. case StyleValue::Type::Ratio: {
  1191. auto from_ratio = from.as_ratio().ratio();
  1192. auto to_ratio = to.as_ratio().ratio();
  1193. // The interpolation of a <ratio> is defined by converting each <ratio> to a number by dividing the first value
  1194. // by the second (so a ratio of 3 / 2 would become 1.5), taking the logarithm of that result (so the 1.5 would
  1195. // become approximately 0.176), then interpolating those values. The result during the interpolation is
  1196. // converted back to a <ratio> by inverting the logarithm, then interpreting the result as a <ratio> with the
  1197. // result as the first value and 1 as the second value.
  1198. auto from_number = log(from_ratio.value());
  1199. auto to_number = log(to_ratio.value());
  1200. auto interp_number = interpolate_raw(from_number, to_number, delta);
  1201. return RatioStyleValue::create(Ratio(pow(M_E, interp_number)));
  1202. }
  1203. case StyleValue::Type::Rect: {
  1204. auto from_rect = from.as_rect().rect();
  1205. auto to_rect = to.as_rect().rect();
  1206. return RectStyleValue::create({
  1207. Length(interpolate_raw(from_rect.top_edge.raw_value(), to_rect.top_edge.raw_value(), delta), from_rect.top_edge.type()),
  1208. Length(interpolate_raw(from_rect.right_edge.raw_value(), to_rect.right_edge.raw_value(), delta), from_rect.right_edge.type()),
  1209. Length(interpolate_raw(from_rect.bottom_edge.raw_value(), to_rect.bottom_edge.raw_value(), delta), from_rect.bottom_edge.type()),
  1210. Length(interpolate_raw(from_rect.left_edge.raw_value(), to_rect.left_edge.raw_value(), delta), from_rect.left_edge.type()),
  1211. });
  1212. }
  1213. case StyleValue::Type::Transformation:
  1214. VERIFY_NOT_REACHED();
  1215. case StyleValue::Type::ValueList: {
  1216. auto& from_list = from.as_value_list();
  1217. auto& to_list = to.as_value_list();
  1218. if (from_list.size() != to_list.size())
  1219. return from;
  1220. StyleValueVector interpolated_values;
  1221. interpolated_values.ensure_capacity(from_list.size());
  1222. for (size_t i = 0; i < from_list.size(); ++i)
  1223. interpolated_values.append(interpolate_value(element, from_list.values()[i], to_list.values()[i], delta));
  1224. return StyleValueList::create(move(interpolated_values), from_list.separator());
  1225. }
  1226. default:
  1227. return from;
  1228. }
  1229. }
  1230. static ValueComparingRefPtr<StyleValue const> interpolate_property(DOM::Element& element, PropertyID property_id, StyleValue const& from, StyleValue const& to, float delta)
  1231. {
  1232. auto animation_type = animation_type_from_longhand_property(property_id);
  1233. switch (animation_type) {
  1234. case AnimationType::ByComputedValue:
  1235. return interpolate_value(element, from, to, delta);
  1236. case AnimationType::None:
  1237. return to;
  1238. case AnimationType::Custom: {
  1239. if (property_id == PropertyID::Transform) {
  1240. if (auto interpolated_transform = interpolate_transform(element, from, to, delta))
  1241. return *interpolated_transform;
  1242. // https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  1243. // In some cases, an animation might cause a transformation matrix to be singular or non-invertible.
  1244. // For example, an animation in which scale moves from 1 to -1. At the time when the matrix is in
  1245. // such a state, the transformed element is not rendered.
  1246. return {};
  1247. }
  1248. if (property_id == PropertyID::BoxShadow)
  1249. return interpolate_box_shadow(element, from, to, delta);
  1250. // FIXME: Handle all custom animatable properties
  1251. [[fallthrough]];
  1252. }
  1253. // FIXME: Handle repeatable-list animatable properties
  1254. case AnimationType::RepeatableList:
  1255. case AnimationType::Discrete:
  1256. default:
  1257. return delta >= 0.5f ? to : from;
  1258. }
  1259. }
  1260. void StyleComputer::collect_animation_into(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, JS::NonnullGCPtr<Animations::KeyframeEffect> effect, StyleProperties& style_properties, AnimationRefresh refresh) const
  1261. {
  1262. auto animation = effect->associated_animation();
  1263. if (!animation)
  1264. return;
  1265. auto output_progress = effect->transformed_progress();
  1266. if (!output_progress.has_value())
  1267. return;
  1268. if (!effect->key_frame_set())
  1269. return;
  1270. auto& keyframes = effect->key_frame_set()->keyframes_by_key;
  1271. auto key = static_cast<u64>(output_progress.value() * 100.0 * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor);
  1272. auto matching_keyframe_it = keyframes.find_largest_not_above_iterator(key);
  1273. if (matching_keyframe_it.is_end()) {
  1274. if constexpr (LIBWEB_CSS_ANIMATION_DEBUG) {
  1275. dbgln(" Did not find any start keyframe for the current state ({}) :(", key);
  1276. dbgln(" (have {} keyframes)", keyframes.size());
  1277. for (auto it = keyframes.begin(); it != keyframes.end(); ++it)
  1278. dbgln(" - {}", it.key());
  1279. }
  1280. return;
  1281. }
  1282. auto keyframe_start = matching_keyframe_it.key();
  1283. auto keyframe_values = *matching_keyframe_it;
  1284. auto initial_keyframe_it = matching_keyframe_it;
  1285. auto keyframe_end_it = ++matching_keyframe_it;
  1286. if (keyframe_end_it.is_end())
  1287. keyframe_end_it = initial_keyframe_it;
  1288. auto keyframe_end = keyframe_end_it.key();
  1289. auto keyframe_end_values = *keyframe_end_it;
  1290. auto progress_in_keyframe = [&] {
  1291. if (keyframe_start == keyframe_end)
  1292. return 0.f;
  1293. return static_cast<float>(key - keyframe_start) / static_cast<float>(keyframe_end - keyframe_start);
  1294. }();
  1295. if constexpr (LIBWEB_CSS_ANIMATION_DEBUG) {
  1296. auto valid_properties = keyframe_values.properties.size();
  1297. dbgln("Animation {} contains {} properties to interpolate, progress = {}%", animation->id(), valid_properties, progress_in_keyframe * 100);
  1298. }
  1299. for (auto const& it : keyframe_values.properties) {
  1300. auto resolve_property = [&](auto& property) {
  1301. return property.visit(
  1302. [&](Animations::KeyframeEffect::KeyFrameSet::UseInitial) -> RefPtr<StyleValue const> {
  1303. if (refresh == AnimationRefresh::Yes)
  1304. return {};
  1305. return style_properties.maybe_null_property(it.key);
  1306. },
  1307. [&](RefPtr<StyleValue const> value) -> RefPtr<StyleValue const> {
  1308. if (value->is_unresolved())
  1309. return Parser::Parser::resolve_unresolved_style_value(Parser::ParsingContext { element.document() }, element, pseudo_element, it.key, value->as_unresolved());
  1310. return value;
  1311. });
  1312. };
  1313. auto resolved_start_property = resolve_property(it.value);
  1314. auto const& end_property = keyframe_end_values.properties.get(it.key);
  1315. if (!end_property.has_value()) {
  1316. if (resolved_start_property) {
  1317. style_properties.set_animated_property(it.key, *resolved_start_property);
  1318. dbgln_if(LIBWEB_CSS_ANIMATION_DEBUG, "No end property for property {}, using {}", string_from_property_id(it.key), resolved_start_property->to_string());
  1319. }
  1320. continue;
  1321. }
  1322. auto resolved_end_property = resolve_property(end_property.value());
  1323. if (resolved_end_property && !resolved_start_property)
  1324. resolved_start_property = CSS::property_initial_value(document().realm(), it.key);
  1325. if (!resolved_start_property || !resolved_end_property)
  1326. continue;
  1327. auto start = resolved_start_property.release_nonnull();
  1328. auto end = resolved_end_property.release_nonnull();
  1329. if (style_properties.is_property_important(it.key)) {
  1330. continue;
  1331. }
  1332. if (auto next_value = interpolate_property(*effect->target(), it.key, *start, *end, progress_in_keyframe)) {
  1333. dbgln_if(LIBWEB_CSS_ANIMATION_DEBUG, "Interpolated value for property {} at {}: {} -> {} = {}", string_from_property_id(it.key), progress_in_keyframe, start->to_string(), end->to_string(), next_value->to_string());
  1334. style_properties.set_animated_property(it.key, *next_value);
  1335. } else {
  1336. // If interpolate_property() fails, the element should not be rendered
  1337. dbgln_if(LIBWEB_CSS_ANIMATION_DEBUG, "Interpolated value for property {} at {}: {} -> {} is invalid", string_from_property_id(it.key), progress_in_keyframe, start->to_string(), end->to_string());
  1338. style_properties.set_animated_property(PropertyID::Visibility, IdentifierStyleValue::create(ValueID::Hidden));
  1339. }
  1340. }
  1341. }
  1342. static void apply_animation_properties(DOM::Document& document, StyleProperties& style, Animations::Animation& animation)
  1343. {
  1344. auto& effect = verify_cast<Animations::KeyframeEffect>(*animation.effect());
  1345. Optional<CSS::Time> duration;
  1346. if (auto duration_value = style.maybe_null_property(PropertyID::AnimationDuration); duration_value) {
  1347. if (duration_value->is_time()) {
  1348. duration = duration_value->as_time().time();
  1349. } else if (duration_value->is_identifier() && duration_value->as_identifier().id() == ValueID::Auto) {
  1350. // We use empty optional to represent "auto".
  1351. duration = {};
  1352. }
  1353. }
  1354. CSS::Time delay { 0, CSS::Time::Type::S };
  1355. if (auto delay_value = style.maybe_null_property(PropertyID::AnimationDelay); delay_value && delay_value->is_time())
  1356. delay = delay_value->as_time().time();
  1357. double iteration_count = 1.0;
  1358. if (auto iteration_count_value = style.maybe_null_property(PropertyID::AnimationIterationCount); iteration_count_value) {
  1359. if (iteration_count_value->is_identifier() && iteration_count_value->to_identifier() == ValueID::Infinite)
  1360. iteration_count = HUGE_VAL;
  1361. else if (iteration_count_value->is_number())
  1362. iteration_count = iteration_count_value->as_number().number();
  1363. }
  1364. CSS::AnimationFillMode fill_mode { CSS::AnimationFillMode::None };
  1365. if (auto fill_mode_property = style.maybe_null_property(PropertyID::AnimationFillMode); fill_mode_property && fill_mode_property->is_identifier()) {
  1366. if (auto fill_mode_value = value_id_to_animation_fill_mode(fill_mode_property->to_identifier()); fill_mode_value.has_value())
  1367. fill_mode = *fill_mode_value;
  1368. }
  1369. CSS::AnimationDirection direction { CSS::AnimationDirection::Normal };
  1370. if (auto direction_property = style.maybe_null_property(PropertyID::AnimationDirection); direction_property && direction_property->is_identifier()) {
  1371. if (auto direction_value = value_id_to_animation_direction(direction_property->to_identifier()); direction_value.has_value())
  1372. direction = *direction_value;
  1373. }
  1374. CSS::AnimationPlayState play_state { CSS::AnimationPlayState::Running };
  1375. if (auto play_state_property = style.maybe_null_property(PropertyID::AnimationPlayState); play_state_property && play_state_property->is_identifier()) {
  1376. if (auto play_state_value = value_id_to_animation_play_state(play_state_property->to_identifier()); play_state_value.has_value())
  1377. play_state = *play_state_value;
  1378. }
  1379. CSS::EasingStyleValue::Function timing_function { CSS::EasingStyleValue::CubicBezier::ease() };
  1380. if (auto timing_property = style.maybe_null_property(PropertyID::AnimationTimingFunction); timing_property && timing_property->is_easing())
  1381. timing_function = timing_property->as_easing().function();
  1382. auto iteration_duration = duration.has_value()
  1383. ? Variant<double, String> { duration.release_value().to_milliseconds() }
  1384. : "auto"_string;
  1385. effect.set_iteration_duration(iteration_duration);
  1386. effect.set_start_delay(delay.to_milliseconds());
  1387. effect.set_iteration_count(iteration_count);
  1388. effect.set_timing_function(move(timing_function));
  1389. effect.set_fill_mode(Animations::css_fill_mode_to_bindings_fill_mode(fill_mode));
  1390. effect.set_playback_direction(Animations::css_animation_direction_to_bindings_playback_direction(direction));
  1391. if (play_state != effect.last_css_animation_play_state()) {
  1392. if (play_state == CSS::AnimationPlayState::Running && animation.play_state() == Bindings::AnimationPlayState::Paused) {
  1393. HTML::TemporaryExecutionContext context(document.relevant_settings_object());
  1394. animation.play().release_value_but_fixme_should_propagate_errors();
  1395. } else if (play_state == CSS::AnimationPlayState::Paused && animation.play_state() != Bindings::AnimationPlayState::Paused) {
  1396. HTML::TemporaryExecutionContext context(document.relevant_settings_object());
  1397. animation.pause().release_value_but_fixme_should_propagate_errors();
  1398. }
  1399. effect.set_last_css_animation_play_state(play_state);
  1400. }
  1401. }
  1402. static void apply_dimension_attribute(StyleProperties& style, DOM::Element const& element, FlyString const& attribute_name, CSS::PropertyID property_id)
  1403. {
  1404. auto attribute = element.attribute(attribute_name);
  1405. if (!attribute.has_value())
  1406. return;
  1407. auto parsed_value = HTML::parse_dimension_value(*attribute);
  1408. if (!parsed_value)
  1409. return;
  1410. style.set_property(property_id, parsed_value.release_nonnull());
  1411. }
  1412. // https://www.w3.org/TR/css-cascade/#cascading
  1413. void StyleComputer::compute_cascaded_values(StyleProperties& style, DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, bool& did_match_any_pseudo_element_rules, ComputeStyleMode mode) const
  1414. {
  1415. // First, we collect all the CSS rules whose selectors match `element`:
  1416. MatchingRuleSet matching_rule_set;
  1417. matching_rule_set.user_agent_rules = collect_matching_rules(element, CascadeOrigin::UserAgent, pseudo_element);
  1418. sort_matching_rules(matching_rule_set.user_agent_rules);
  1419. matching_rule_set.user_rules = collect_matching_rules(element, CascadeOrigin::User, pseudo_element);
  1420. sort_matching_rules(matching_rule_set.user_rules);
  1421. matching_rule_set.author_rules = collect_matching_rules(element, CascadeOrigin::Author, pseudo_element);
  1422. sort_matching_rules(matching_rule_set.author_rules);
  1423. if (mode == ComputeStyleMode::CreatePseudoElementStyleIfNeeded) {
  1424. VERIFY(pseudo_element.has_value());
  1425. if (matching_rule_set.author_rules.is_empty() && matching_rule_set.user_rules.is_empty() && matching_rule_set.user_agent_rules.is_empty()) {
  1426. did_match_any_pseudo_element_rules = false;
  1427. return;
  1428. }
  1429. did_match_any_pseudo_element_rules = true;
  1430. }
  1431. // Then we resolve all the CSS custom properties ("variables") for this element:
  1432. cascade_custom_properties(element, pseudo_element, matching_rule_set.author_rules);
  1433. // Then we apply the declarations from the matched rules in cascade order:
  1434. // Normal user agent declarations
  1435. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::No);
  1436. // Normal user declarations
  1437. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_rules, CascadeOrigin::User, Important::No);
  1438. // Author presentational hints (NOTE: The spec doesn't say exactly how to prioritize these.)
  1439. if (!pseudo_element.has_value()) {
  1440. element.apply_presentational_hints(style);
  1441. if (element.supports_dimension_attributes()) {
  1442. apply_dimension_attribute(style, element, HTML::AttributeNames::width, CSS::PropertyID::Width);
  1443. apply_dimension_attribute(style, element, HTML::AttributeNames::height, CSS::PropertyID::Height);
  1444. }
  1445. // SVG presentation attributes are parsed as CSS values, so we need to handle potential custom properties here.
  1446. if (element.is_svg_element()) {
  1447. // FIXME: This is not very efficient, we should only resolve the custom properties that are actually used.
  1448. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  1449. auto property_id = (CSS::PropertyID)i;
  1450. auto& property = style.m_property_values[i];
  1451. if (property.style && property.style->is_unresolved())
  1452. property.style = Parser::Parser::resolve_unresolved_style_value(Parser::ParsingContext { document() }, element, pseudo_element, property_id, property.style->as_unresolved());
  1453. }
  1454. }
  1455. }
  1456. // Normal author declarations
  1457. cascade_declarations(style, element, pseudo_element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::No);
  1458. // Animation declarations [css-animations-2]
  1459. auto animation_name = [&]() -> Optional<String> {
  1460. auto animation_name = style.maybe_null_property(PropertyID::AnimationName);
  1461. if (animation_name.is_null())
  1462. return OptionalNone {};
  1463. if (animation_name->is_string())
  1464. return animation_name->as_string().string_value();
  1465. return animation_name->to_string();
  1466. }();
  1467. if (animation_name.has_value()) {
  1468. if (auto source_declaration = style.property_source_declaration(PropertyID::AnimationName); source_declaration) {
  1469. auto& realm = element.realm();
  1470. if (source_declaration != element.cached_animation_name_source()) {
  1471. // This animation name is new, so we need to create a new animation for it.
  1472. if (auto existing_animation = element.cached_animation_name_animation())
  1473. existing_animation->cancel(Animations::Animation::ShouldInvalidate::No);
  1474. element.set_cached_animation_name_source(source_declaration);
  1475. auto effect = Animations::KeyframeEffect::create(realm);
  1476. auto animation = CSSAnimation::create(realm);
  1477. animation->set_id(animation_name.release_value());
  1478. animation->set_timeline(m_document->timeline());
  1479. animation->set_owning_element(element);
  1480. animation->set_effect(effect);
  1481. apply_animation_properties(m_document, style, animation);
  1482. if (pseudo_element.has_value())
  1483. effect->set_pseudo_element(Selector::PseudoElement { pseudo_element.value() });
  1484. auto const& rule_cache = rule_cache_for_cascade_origin(CascadeOrigin::Author);
  1485. if (auto keyframe_set = rule_cache.rules_by_animation_keyframes.get(animation->id()); keyframe_set.has_value())
  1486. effect->set_key_frame_set(keyframe_set.value());
  1487. effect->set_target(&element);
  1488. element.set_cached_animation_name_animation(animation);
  1489. HTML::TemporaryExecutionContext context(m_document->relevant_settings_object());
  1490. animation->play().release_value_but_fixme_should_propagate_errors();
  1491. } else {
  1492. // The animation hasn't changed, but some properties of the animation may have
  1493. apply_animation_properties(m_document, style, *element.cached_animation_name_animation());
  1494. }
  1495. }
  1496. } else {
  1497. // If the element had an existing animation, cancel it
  1498. if (auto existing_animation = element.cached_animation_name_animation()) {
  1499. existing_animation->cancel(Animations::Animation::ShouldInvalidate::No);
  1500. element.set_cached_animation_name_animation({});
  1501. element.set_cached_animation_name_source({});
  1502. }
  1503. }
  1504. auto animations = element.get_animations({ .subtree = false });
  1505. for (auto& animation : animations) {
  1506. if (auto effect = animation->effect(); effect && effect->is_keyframe_effect()) {
  1507. auto& keyframe_effect = *static_cast<Animations::KeyframeEffect*>(effect.ptr());
  1508. if (keyframe_effect.pseudo_element_type() == pseudo_element)
  1509. collect_animation_into(element, pseudo_element, keyframe_effect, style);
  1510. }
  1511. }
  1512. // Important author declarations
  1513. cascade_declarations(style, element, pseudo_element, matching_rule_set.author_rules, CascadeOrigin::Author, Important::Yes);
  1514. // Important user declarations
  1515. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_rules, CascadeOrigin::User, Important::Yes);
  1516. // Important user agent declarations
  1517. cascade_declarations(style, element, pseudo_element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, Important::Yes);
  1518. // FIXME: Transition declarations [css-transitions-1]
  1519. }
  1520. DOM::Element const* element_to_inherit_style_from(DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element)
  1521. {
  1522. // Pseudo-elements treat their originating element as their parent.
  1523. DOM::Element const* parent_element = nullptr;
  1524. if (pseudo_element.has_value()) {
  1525. parent_element = element;
  1526. } else if (element) {
  1527. parent_element = element->parent_or_shadow_host_element();
  1528. }
  1529. return parent_element;
  1530. }
  1531. NonnullRefPtr<StyleValue const> StyleComputer::get_inherit_value(JS::Realm& initial_value_context_realm, CSS::PropertyID property_id, DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element)
  1532. {
  1533. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  1534. if (!parent_element || !parent_element->computed_css_values())
  1535. return property_initial_value(initial_value_context_realm, property_id);
  1536. return parent_element->computed_css_values()->property(property_id);
  1537. }
  1538. void StyleComputer::compute_defaulted_property_value(StyleProperties& style, DOM::Element const* element, CSS::PropertyID property_id, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  1539. {
  1540. // FIXME: If we don't know the correct initial value for a property, we fall back to InitialStyleValue.
  1541. auto& value_slot = style.m_property_values[to_underlying(property_id)];
  1542. if (!value_slot.style) {
  1543. if (is_inherited_property(property_id))
  1544. style.m_property_values[to_underlying(property_id)] = { get_inherit_value(document().realm(), property_id, element, pseudo_element), nullptr, StyleProperties::Important::No, StyleProperties::Inherited::Yes };
  1545. else
  1546. style.m_property_values[to_underlying(property_id)] = { property_initial_value(document().realm(), property_id), nullptr };
  1547. return;
  1548. }
  1549. if (value_slot.style->is_initial()) {
  1550. value_slot.style = property_initial_value(document().realm(), property_id);
  1551. return;
  1552. }
  1553. if (value_slot.style->is_inherit()) {
  1554. value_slot.style = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  1555. value_slot.inherited = StyleProperties::Inherited::Yes;
  1556. return;
  1557. }
  1558. // https://www.w3.org/TR/css-cascade-4/#inherit-initial
  1559. // If the cascaded value of a property is the unset keyword,
  1560. if (value_slot.style->is_unset()) {
  1561. if (is_inherited_property(property_id)) {
  1562. // then if it is an inherited property, this is treated as inherit,
  1563. value_slot.style = get_inherit_value(document().realm(), property_id, element, pseudo_element);
  1564. value_slot.inherited = StyleProperties::Inherited::Yes;
  1565. } else {
  1566. // and if it is not, this is treated as initial.
  1567. value_slot.style = property_initial_value(document().realm(), property_id);
  1568. }
  1569. }
  1570. }
  1571. // https://www.w3.org/TR/css-cascade/#defaulting
  1572. void StyleComputer::compute_defaulted_values(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  1573. {
  1574. // Walk the list of all known CSS properties and:
  1575. // - Add them to `style` if they are missing.
  1576. // - Resolve `inherit` and `initial` as needed.
  1577. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  1578. auto property_id = (CSS::PropertyID)i;
  1579. compute_defaulted_property_value(style, element, property_id, pseudo_element);
  1580. }
  1581. // https://www.w3.org/TR/css-color-4/#resolving-other-colors
  1582. // In the color property, the used value of currentcolor is the inherited value.
  1583. auto color = style.property(CSS::PropertyID::Color);
  1584. if (color->to_identifier() == CSS::ValueID::Currentcolor) {
  1585. color = get_inherit_value(document().realm(), CSS::PropertyID::Color, element, pseudo_element);
  1586. style.set_property(CSS::PropertyID::Color, color);
  1587. }
  1588. }
  1589. Length::FontMetrics StyleComputer::calculate_root_element_font_metrics(StyleProperties const& style) const
  1590. {
  1591. auto root_value = style.property(CSS::PropertyID::FontSize);
  1592. auto font_pixel_metrics = style.first_available_computed_font().pixel_metrics();
  1593. Length::FontMetrics font_metrics { m_default_font_metrics.font_size, font_pixel_metrics };
  1594. font_metrics.font_size = root_value->as_length().length().to_px(viewport_rect(), font_metrics, font_metrics);
  1595. font_metrics.line_height = style.compute_line_height(viewport_rect(), font_metrics, font_metrics);
  1596. return font_metrics;
  1597. }
  1598. RefPtr<Gfx::FontCascadeList const> StyleComputer::find_matching_font_weight_ascending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive)
  1599. {
  1600. using Fn = AK::Function<bool(MatchingFontCandidate const&)>;
  1601. auto pred = inclusive ? Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight >= target_weight; })
  1602. : Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight > target_weight; });
  1603. auto it = find_if(candidates.begin(), candidates.end(), pred);
  1604. for (; it != candidates.end(); ++it) {
  1605. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1606. return found_font;
  1607. }
  1608. return {};
  1609. }
  1610. RefPtr<Gfx::FontCascadeList const> StyleComputer::find_matching_font_weight_descending(Vector<MatchingFontCandidate> const& candidates, int target_weight, float font_size_in_pt, bool inclusive)
  1611. {
  1612. using Fn = AK::Function<bool(MatchingFontCandidate const&)>;
  1613. auto pred = inclusive ? Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight <= target_weight; })
  1614. : Fn([&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight < target_weight; });
  1615. auto it = find_if(candidates.rbegin(), candidates.rend(), pred);
  1616. for (; it != candidates.rend(); ++it) {
  1617. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1618. return found_font;
  1619. }
  1620. return {};
  1621. }
  1622. // Partial implementation of the font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
  1623. // FIXME: This should be replaced by the full CSS font selection algorithm.
  1624. RefPtr<Gfx::FontCascadeList const> StyleComputer::font_matching_algorithm(FontFaceKey const& key, float font_size_in_pt) const
  1625. {
  1626. // If a font family match occurs, the user agent assembles the set of font faces in that family and then
  1627. // narrows the set to a single face using other font properties in the order given below.
  1628. Vector<MatchingFontCandidate> matching_family_fonts;
  1629. for (auto const& font_key_and_loader : m_loaded_fonts) {
  1630. if (font_key_and_loader.key.family_name.equals_ignoring_ascii_case(key.family_name))
  1631. matching_family_fonts.empend(font_key_and_loader.key, const_cast<FontLoaderList*>(&font_key_and_loader.value));
  1632. }
  1633. Gfx::FontDatabase::the().for_each_typeface_with_family_name(key.family_name, [&](Gfx::Typeface const& typeface) {
  1634. matching_family_fonts.empend(
  1635. FontFaceKey {
  1636. .family_name = typeface.family(),
  1637. .weight = static_cast<int>(typeface.weight()),
  1638. .slope = typeface.slope(),
  1639. },
  1640. &typeface);
  1641. });
  1642. quick_sort(matching_family_fonts, [](auto const& a, auto const& b) {
  1643. return a.key.weight < b.key.weight;
  1644. });
  1645. // FIXME: 1. font-stretch is tried first.
  1646. // FIXME: 2. font-style is tried next.
  1647. // We don't have complete support of italic and oblique fonts, so matching on font-style can be simplified to:
  1648. // If a matching slope is found, all faces which don't have that matching slope are excluded from the matching set.
  1649. auto style_it = find_if(matching_family_fonts.begin(), matching_family_fonts.end(),
  1650. [&](auto const& matching_font_candidate) { return matching_font_candidate.key.slope == key.slope; });
  1651. if (style_it != matching_family_fonts.end()) {
  1652. matching_family_fonts.remove_all_matching([&](auto const& matching_font_candidate) {
  1653. return matching_font_candidate.key.slope != key.slope;
  1654. });
  1655. }
  1656. // 3. font-weight is matched next.
  1657. // If the desired weight is inclusively between 400 and 500, weights greater than or equal to the target weight
  1658. // are checked in ascending order until 500 is hit and checked, followed by weights less than the target weight
  1659. // in descending order, followed by weights greater than 500, until a match is found.
  1660. if (key.weight >= 400 && key.weight <= 500) {
  1661. auto it = find_if(matching_family_fonts.begin(), matching_family_fonts.end(),
  1662. [&](auto const& matching_font_candidate) { return matching_font_candidate.key.weight >= key.weight; });
  1663. for (; it != matching_family_fonts.end() && it->key.weight <= 500; ++it) {
  1664. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1665. return found_font;
  1666. }
  1667. if (auto found_font = find_matching_font_weight_descending(matching_family_fonts, key.weight, font_size_in_pt, false))
  1668. return found_font;
  1669. for (; it != matching_family_fonts.end(); ++it) {
  1670. if (auto found_font = it->font_with_point_size(font_size_in_pt))
  1671. return found_font;
  1672. }
  1673. }
  1674. // If the desired weight is less than 400, weights less than or equal to the desired weight are checked in descending order
  1675. // followed by weights above the desired weight in ascending order until a match is found.
  1676. if (key.weight < 400) {
  1677. if (auto found_font = find_matching_font_weight_descending(matching_family_fonts, key.weight, font_size_in_pt, true))
  1678. return found_font;
  1679. if (auto found_font = find_matching_font_weight_ascending(matching_family_fonts, key.weight, font_size_in_pt, false))
  1680. return found_font;
  1681. }
  1682. // If the desired weight is greater than 500, weights greater than or equal to the desired weight are checked in ascending order
  1683. // followed by weights below the desired weight in descending order until a match is found.
  1684. if (key.weight > 500) {
  1685. if (auto found_font = find_matching_font_weight_ascending(matching_family_fonts, key.weight, font_size_in_pt, true))
  1686. return found_font;
  1687. if (auto found_font = find_matching_font_weight_descending(matching_family_fonts, key.weight, font_size_in_pt, false))
  1688. return found_font;
  1689. }
  1690. return {};
  1691. }
  1692. RefPtr<Gfx::FontCascadeList const> StyleComputer::compute_font_for_style_values(DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, StyleValue const& font_family, StyleValue const& font_size, StyleValue const& font_style, StyleValue const& font_weight, StyleValue const& font_stretch, int math_depth) const
  1693. {
  1694. auto* parent_element = element_to_inherit_style_from(element, pseudo_element);
  1695. auto width = font_stretch.to_font_stretch_width();
  1696. auto weight = font_weight.to_font_weight();
  1697. bool bold = weight > Gfx::FontWeight::Regular;
  1698. // FIXME: Should be based on "user's default font size"
  1699. CSSPixels font_size_in_px = 16;
  1700. Gfx::FontPixelMetrics font_pixel_metrics;
  1701. if (parent_element && parent_element->computed_css_values())
  1702. font_pixel_metrics = parent_element->computed_css_values()->first_available_computed_font().pixel_metrics();
  1703. else
  1704. font_pixel_metrics = Platform::FontPlugin::the().default_font().pixel_metrics();
  1705. auto parent_font_size = [&]() -> CSSPixels {
  1706. if (!parent_element || !parent_element->computed_css_values())
  1707. return font_size_in_px;
  1708. auto value = parent_element->computed_css_values()->property(CSS::PropertyID::FontSize);
  1709. if (value->is_length()) {
  1710. auto length = value->as_length().length();
  1711. if (length.is_absolute() || length.is_relative()) {
  1712. Length::FontMetrics font_metrics { font_size_in_px, font_pixel_metrics };
  1713. return length.to_px(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1714. }
  1715. }
  1716. return font_size_in_px;
  1717. };
  1718. Length::FontMetrics font_metrics { parent_font_size(), font_pixel_metrics };
  1719. if (font_size.is_identifier()) {
  1720. // https://w3c.github.io/csswg-drafts/css-fonts/#absolute-size-mapping
  1721. auto get_absolute_size_mapping = [](Web::CSS::ValueID identifier) -> CSSPixelFraction {
  1722. switch (identifier) {
  1723. case CSS::ValueID::XxSmall:
  1724. return CSSPixels(3) / 5;
  1725. case CSS::ValueID::XSmall:
  1726. return CSSPixels(3) / 4;
  1727. case CSS::ValueID::Small:
  1728. return CSSPixels(8) / 9;
  1729. case CSS::ValueID::Medium:
  1730. return 1;
  1731. case CSS::ValueID::Large:
  1732. return CSSPixels(6) / 5;
  1733. case CSS::ValueID::XLarge:
  1734. return CSSPixels(3) / 2;
  1735. case CSS::ValueID::XxLarge:
  1736. return 2;
  1737. case CSS::ValueID::XxxLarge:
  1738. return 3;
  1739. case CSS::ValueID::Smaller:
  1740. return CSSPixels(4) / 5;
  1741. case CSS::ValueID::Larger:
  1742. return CSSPixels(5) / 4;
  1743. default:
  1744. return 1;
  1745. }
  1746. };
  1747. auto const identifier = static_cast<IdentifierStyleValue const&>(font_size).id();
  1748. if (identifier == ValueID::Math) {
  1749. auto math_scaling_factor = [&]() {
  1750. // https://w3c.github.io/mathml-core/#the-math-script-level-property
  1751. // If the specified value font-size is math then the computed value of font-size is obtained by multiplying
  1752. // the inherited value of font-size by a nonzero scale factor calculated by the following procedure:
  1753. // 1. Let A be the inherited math-depth value, B the computed math-depth value, C be 0.71 and S be 1.0
  1754. int inherited_math_depth = parent_element && parent_element->computed_css_values()
  1755. ? parent_element->computed_css_values()->math_depth()
  1756. : InitialValues::math_depth();
  1757. int computed_math_depth = math_depth;
  1758. auto size_ratio = 0.71;
  1759. auto scale = 1.0;
  1760. // 2. If A = B then return S.
  1761. bool invert_scale_factor = false;
  1762. if (inherited_math_depth == computed_math_depth) {
  1763. return scale;
  1764. }
  1765. // If B < A, swap A and B and set InvertScaleFactor to true.
  1766. else if (computed_math_depth < inherited_math_depth) {
  1767. AK::swap(inherited_math_depth, computed_math_depth);
  1768. invert_scale_factor = true;
  1769. }
  1770. // Otherwise B > A and set InvertScaleFactor to false.
  1771. else {
  1772. invert_scale_factor = false;
  1773. }
  1774. // 3. Let E be B - A > 0.
  1775. double e = (computed_math_depth - inherited_math_depth) > 0;
  1776. // FIXME: 4. If the inherited first available font has an OpenType MATH table:
  1777. // - If A ≤ 0 and B ≥ 2 then multiply S by scriptScriptPercentScaleDown and decrement E by 2.
  1778. // - Otherwise if A = 1 then multiply S by scriptScriptPercentScaleDown / scriptPercentScaleDown and decrement E by 1.
  1779. // - Otherwise if B = 1 then multiply S by scriptPercentScaleDown and decrement E by 1.
  1780. // 5. Multiply S by C^E.
  1781. scale *= AK::pow(size_ratio, e);
  1782. // 6. Return S if InvertScaleFactor is false and 1/S otherwise.
  1783. if (!invert_scale_factor)
  1784. return scale;
  1785. return 1.0 / scale;
  1786. };
  1787. font_size_in_px = parent_font_size().scale_by(math_scaling_factor());
  1788. } else {
  1789. // https://w3c.github.io/csswg-drafts/css-fonts/#valdef-font-size-relative-size
  1790. // TODO: If the parent element has a keyword font size in the absolute size keyword mapping table,
  1791. // larger may compute the font size to the next entry in the table,
  1792. // and smaller may compute the font size to the previous entry in the table.
  1793. if (identifier == CSS::ValueID::Smaller || identifier == CSS::ValueID::Larger) {
  1794. if (parent_element && parent_element->computed_css_values()) {
  1795. font_size_in_px = CSSPixels::nearest_value_for(parent_element->computed_css_values()->first_available_computed_font().pixel_metrics().size);
  1796. }
  1797. }
  1798. font_size_in_px *= get_absolute_size_mapping(identifier);
  1799. }
  1800. } else {
  1801. Length::ResolutionContext const length_resolution_context {
  1802. .viewport_rect = viewport_rect(),
  1803. .font_metrics = font_metrics,
  1804. .root_font_metrics = m_root_element_font_metrics,
  1805. };
  1806. Optional<Length> maybe_length;
  1807. if (font_size.is_percentage()) {
  1808. // Percentages refer to parent element's font size
  1809. maybe_length = Length::make_px(CSSPixels::nearest_value_for(font_size.as_percentage().percentage().as_fraction() * parent_font_size().to_double()));
  1810. } else if (font_size.is_length()) {
  1811. maybe_length = font_size.as_length().length();
  1812. } else if (font_size.is_calculated()) {
  1813. if (font_size.as_calculated().contains_percentage()) {
  1814. maybe_length = font_size.as_calculated().resolve_length_percentage(length_resolution_context, Length::make_px(parent_font_size()));
  1815. } else {
  1816. maybe_length = font_size.as_calculated().resolve_length(length_resolution_context);
  1817. }
  1818. }
  1819. if (maybe_length.has_value()) {
  1820. font_size_in_px = maybe_length.value().to_px(length_resolution_context);
  1821. }
  1822. }
  1823. auto slope = font_style.to_font_slope();
  1824. // FIXME: Implement the full font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
  1825. // Note: This is modified by the find_font() lambda
  1826. bool monospace = false;
  1827. float const font_size_in_pt = font_size_in_px * 0.75f;
  1828. auto find_font = [&](FlyString const& family) -> RefPtr<Gfx::FontCascadeList const> {
  1829. FontFaceKey key {
  1830. .family_name = family,
  1831. .weight = weight,
  1832. .slope = slope,
  1833. };
  1834. auto result = Gfx::FontCascadeList::create();
  1835. if (auto it = m_loaded_fonts.find(key); it != m_loaded_fonts.end()) {
  1836. auto const& loaders = it->value;
  1837. for (auto const& loader : loaders) {
  1838. if (auto found_font = loader->font_with_point_size(font_size_in_pt))
  1839. result->add(*found_font, loader->unicode_ranges());
  1840. }
  1841. return result;
  1842. }
  1843. if (auto found_font = font_matching_algorithm(key, font_size_in_pt); found_font && !found_font->is_empty()) {
  1844. return found_font;
  1845. }
  1846. if (auto found_font = Gfx::FontDatabase::the().get(family, font_size_in_pt, weight, width, slope)) {
  1847. result->add(*found_font);
  1848. return result;
  1849. }
  1850. return {};
  1851. };
  1852. auto find_generic_font = [&](ValueID font_id) -> RefPtr<Gfx::FontCascadeList const> {
  1853. Platform::GenericFont generic_font {};
  1854. switch (font_id) {
  1855. case ValueID::Monospace:
  1856. case ValueID::UiMonospace:
  1857. generic_font = Platform::GenericFont::Monospace;
  1858. monospace = true;
  1859. break;
  1860. case ValueID::Serif:
  1861. generic_font = Platform::GenericFont::Serif;
  1862. break;
  1863. case ValueID::Fantasy:
  1864. generic_font = Platform::GenericFont::Fantasy;
  1865. break;
  1866. case ValueID::SansSerif:
  1867. generic_font = Platform::GenericFont::SansSerif;
  1868. break;
  1869. case ValueID::Cursive:
  1870. generic_font = Platform::GenericFont::Cursive;
  1871. break;
  1872. case ValueID::UiSerif:
  1873. generic_font = Platform::GenericFont::UiSerif;
  1874. break;
  1875. case ValueID::UiSansSerif:
  1876. generic_font = Platform::GenericFont::UiSansSerif;
  1877. break;
  1878. case ValueID::UiRounded:
  1879. generic_font = Platform::GenericFont::UiRounded;
  1880. break;
  1881. default:
  1882. return {};
  1883. }
  1884. return find_font(Platform::FontPlugin::the().generic_font_name(generic_font));
  1885. };
  1886. auto font_list = Gfx::FontCascadeList::create();
  1887. if (font_family.is_value_list()) {
  1888. auto const& family_list = static_cast<StyleValueList const&>(font_family).values();
  1889. for (auto const& family : family_list) {
  1890. RefPtr<Gfx::FontCascadeList const> other_font_list;
  1891. if (family->is_identifier()) {
  1892. other_font_list = find_generic_font(family->to_identifier());
  1893. } else if (family->is_string()) {
  1894. other_font_list = find_font(family->as_string().string_value());
  1895. } else if (family->is_custom_ident()) {
  1896. other_font_list = find_font(family->as_custom_ident().custom_ident());
  1897. }
  1898. if (other_font_list)
  1899. font_list->extend(*other_font_list);
  1900. }
  1901. } else if (font_family.is_identifier()) {
  1902. if (auto other_font_list = find_generic_font(font_family.to_identifier()))
  1903. font_list->extend(*other_font_list);
  1904. } else if (font_family.is_string()) {
  1905. if (auto other_font_list = find_font(font_family.as_string().string_value()))
  1906. font_list->extend(*other_font_list);
  1907. } else if (font_family.is_custom_ident()) {
  1908. if (auto other_font_list = find_font(font_family.as_custom_ident().custom_ident()))
  1909. font_list->extend(*other_font_list);
  1910. }
  1911. auto found_font = StyleProperties::font_fallback(monospace, bold);
  1912. font_list->add(found_font->with_size(font_size_in_pt));
  1913. return font_list;
  1914. }
  1915. void StyleComputer::compute_font(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  1916. {
  1917. // To compute the font, first ensure that we've defaulted the relevant CSS font properties.
  1918. // FIXME: This should be more sophisticated.
  1919. compute_defaulted_property_value(style, element, CSS::PropertyID::FontFamily, pseudo_element);
  1920. compute_defaulted_property_value(style, element, CSS::PropertyID::FontSize, pseudo_element);
  1921. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStretch, pseudo_element);
  1922. compute_defaulted_property_value(style, element, CSS::PropertyID::FontStyle, pseudo_element);
  1923. compute_defaulted_property_value(style, element, CSS::PropertyID::FontWeight, pseudo_element);
  1924. compute_defaulted_property_value(style, element, CSS::PropertyID::LineHeight, pseudo_element);
  1925. auto font_family = style.property(CSS::PropertyID::FontFamily);
  1926. auto font_size = style.property(CSS::PropertyID::FontSize);
  1927. auto font_style = style.property(CSS::PropertyID::FontStyle);
  1928. auto font_weight = style.property(CSS::PropertyID::FontWeight);
  1929. auto font_stretch = style.property(CSS::PropertyID::FontStretch);
  1930. auto font_list = compute_font_for_style_values(element, pseudo_element, font_family, font_size, font_style, font_weight, font_stretch, style.math_depth());
  1931. VERIFY(font_list);
  1932. VERIFY(!font_list->is_empty());
  1933. RefPtr<Gfx::Font const> const found_font = font_list->first();
  1934. style.set_property(CSS::PropertyID::FontSize, LengthStyleValue::create(CSS::Length::make_px(CSSPixels::nearest_value_for(found_font->pixel_size()))), nullptr);
  1935. style.set_property(CSS::PropertyID::FontWeight, NumberStyleValue::create(font_weight->to_font_weight()));
  1936. style.set_computed_font_list(*font_list);
  1937. if (element && is<HTML::HTMLHtmlElement>(*element)) {
  1938. const_cast<StyleComputer&>(*this).m_root_element_font_metrics = calculate_root_element_font_metrics(style);
  1939. }
  1940. }
  1941. Gfx::Font const& StyleComputer::initial_font() const
  1942. {
  1943. // FIXME: This is not correct.
  1944. return StyleProperties::font_fallback(false, false);
  1945. }
  1946. void StyleComputer::absolutize_values(StyleProperties& style) const
  1947. {
  1948. Length::FontMetrics font_metrics {
  1949. m_root_element_font_metrics.font_size,
  1950. style.first_available_computed_font().pixel_metrics()
  1951. };
  1952. auto font_size = style.property(CSS::PropertyID::FontSize)->as_length().length().to_px(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1953. font_metrics.font_size = font_size;
  1954. // NOTE: Percentage line-height values are relative to the font-size of the element.
  1955. // We have to resolve them right away, so that the *computed* line-height is ready for inheritance.
  1956. // We can't simply absolutize *all* percentage values against the font size,
  1957. // because most percentages are relative to containing block metrics.
  1958. auto& line_height_value_slot = style.m_property_values[to_underlying(CSS::PropertyID::LineHeight)].style;
  1959. if (line_height_value_slot && line_height_value_slot->is_percentage()) {
  1960. line_height_value_slot = LengthStyleValue::create(
  1961. Length::make_px(CSSPixels::nearest_value_for(font_size * static_cast<double>(line_height_value_slot->as_percentage().percentage().as_fraction()))));
  1962. }
  1963. auto line_height = style.compute_line_height(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1964. font_metrics.line_height = line_height;
  1965. // NOTE: line-height might be using lh which should be resolved against the parent line height (like we did here already)
  1966. if (line_height_value_slot && line_height_value_slot->is_length())
  1967. line_height_value_slot = LengthStyleValue::create(Length::make_px(line_height));
  1968. for (size_t i = 0; i < style.m_property_values.size(); ++i) {
  1969. auto& value_slot = style.m_property_values[i];
  1970. if (!value_slot.style)
  1971. continue;
  1972. value_slot.style = value_slot.style->absolutized(viewport_rect(), font_metrics, m_root_element_font_metrics);
  1973. }
  1974. style.set_line_height({}, line_height);
  1975. }
  1976. void StyleComputer::resolve_effective_overflow_values(StyleProperties& style) const
  1977. {
  1978. // https://www.w3.org/TR/css-overflow-3/#overflow-control
  1979. // The visible/clip values of overflow compute to auto/hidden (respectively) if one of overflow-x or
  1980. // overflow-y is neither visible nor clip.
  1981. auto overflow_x = value_id_to_overflow(style.property(PropertyID::OverflowX)->to_identifier());
  1982. auto overflow_y = value_id_to_overflow(style.property(PropertyID::OverflowY)->to_identifier());
  1983. auto overflow_x_is_visible_or_clip = overflow_x == Overflow::Visible || overflow_x == Overflow::Clip;
  1984. auto overflow_y_is_visible_or_clip = overflow_y == Overflow::Visible || overflow_y == Overflow::Clip;
  1985. if (!overflow_x_is_visible_or_clip || !overflow_y_is_visible_or_clip) {
  1986. if (overflow_x == CSS::Overflow::Visible)
  1987. style.set_property(CSS::PropertyID::OverflowX, IdentifierStyleValue::create(CSS::ValueID::Auto), nullptr);
  1988. if (overflow_x == CSS::Overflow::Clip)
  1989. style.set_property(CSS::PropertyID::OverflowX, IdentifierStyleValue::create(CSS::ValueID::Hidden), nullptr);
  1990. if (overflow_y == CSS::Overflow::Visible)
  1991. style.set_property(CSS::PropertyID::OverflowY, IdentifierStyleValue::create(CSS::ValueID::Auto), nullptr);
  1992. if (overflow_y == CSS::Overflow::Clip)
  1993. style.set_property(CSS::PropertyID::OverflowY, IdentifierStyleValue::create(CSS::ValueID::Hidden), nullptr);
  1994. }
  1995. }
  1996. enum class BoxTypeTransformation {
  1997. None,
  1998. Blockify,
  1999. Inlinify,
  2000. };
  2001. static BoxTypeTransformation required_box_type_transformation(StyleProperties const& style, DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> const& pseudo_element)
  2002. {
  2003. // NOTE: We never blockify <br> elements. They are always inline.
  2004. // There is currently no way to express in CSS how a <br> element really behaves.
  2005. // Spec issue: https://github.com/whatwg/html/issues/2291
  2006. if (is<HTML::HTMLBRElement>(element))
  2007. return BoxTypeTransformation::None;
  2008. // Absolute positioning or floating an element blockifies the box’s display type. [CSS2]
  2009. if (style.position() == CSS::Positioning::Absolute || style.position() == CSS::Positioning::Fixed || style.float_() != CSS::Float::None)
  2010. return BoxTypeTransformation::Blockify;
  2011. // FIXME: Containment in a ruby container inlinifies the box’s display type, as described in [CSS-RUBY-1].
  2012. // NOTE: If we're computing style for a pseudo-element, the effective parent will be the originating element itself, not its parent.
  2013. auto const* parent = pseudo_element.has_value() ? &element : element.parent_element();
  2014. // A parent with a grid or flex display value blockifies the box’s display type. [CSS-GRID-1] [CSS-FLEXBOX-1]
  2015. if (parent && parent->computed_css_values()) {
  2016. auto const& parent_display = parent->computed_css_values()->display();
  2017. if (parent_display.is_grid_inside() || parent_display.is_flex_inside())
  2018. return BoxTypeTransformation::Blockify;
  2019. }
  2020. return BoxTypeTransformation::None;
  2021. }
  2022. // https://drafts.csswg.org/css-display/#transformations
  2023. void StyleComputer::transform_box_type_if_needed(StyleProperties& style, DOM::Element const& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  2024. {
  2025. // 2.7. Automatic Box Type Transformations
  2026. // Some layout effects require blockification or inlinification of the box type,
  2027. // which sets the box’s computed outer display type to block or inline (respectively).
  2028. // (This has no effect on display types that generate no box at all, such as none or contents.)
  2029. auto display = style.display();
  2030. if (display.is_none() || display.is_contents())
  2031. return;
  2032. auto new_display = display;
  2033. if (display.is_math_inside()) {
  2034. // https://w3c.github.io/mathml-core/#new-display-math-value
  2035. // For elements that are not MathML elements, if the specified value of display is inline math or block math
  2036. // then the computed value is block flow and inline flow respectively.
  2037. if (element.namespace_uri() != Namespace::MathML)
  2038. new_display = CSS::Display { display.outside(), CSS::DisplayInside::Flow };
  2039. // For the mtable element the computed value is block table and inline table respectively.
  2040. else if (element.tag_name().equals_ignoring_ascii_case("mtable"sv))
  2041. new_display = CSS::Display { display.outside(), CSS::DisplayInside::Table };
  2042. // For the mtr element, the computed value is table-row.
  2043. else if (element.tag_name().equals_ignoring_ascii_case("mtr"sv))
  2044. new_display = CSS::Display { CSS::DisplayInternal::TableRow };
  2045. // For the mtd element, the computed value is table-cell.
  2046. else if (element.tag_name().equals_ignoring_ascii_case("mtd"sv))
  2047. new_display = CSS::Display { CSS::DisplayInternal::TableCell };
  2048. }
  2049. switch (required_box_type_transformation(style, element, pseudo_element)) {
  2050. case BoxTypeTransformation::None:
  2051. break;
  2052. case BoxTypeTransformation::Blockify:
  2053. if (display.is_block_outside())
  2054. return;
  2055. // If a layout-internal box is blockified, its inner display type converts to flow so that it becomes a block container.
  2056. if (display.is_internal()) {
  2057. new_display = CSS::Display::from_short(CSS::Display::Short::Block);
  2058. } else {
  2059. VERIFY(display.is_outside_and_inside());
  2060. // For legacy reasons, if an inline block box (inline flow-root) is blockified, it becomes a block box (losing its flow-root nature).
  2061. // For consistency, a run-in flow-root box also blockifies to a block box.
  2062. if (display.is_inline_block()) {
  2063. new_display = CSS::Display { CSS::DisplayOutside::Block, CSS::DisplayInside::Flow, display.list_item() };
  2064. } else {
  2065. new_display = CSS::Display { CSS::DisplayOutside::Block, display.inside(), display.list_item() };
  2066. }
  2067. }
  2068. break;
  2069. case BoxTypeTransformation::Inlinify:
  2070. if (display.is_inline_outside()) {
  2071. // FIXME: If an inline box (inline flow) is inlinified, it recursively inlinifies all of its in-flow children,
  2072. // so that no block-level descendants break up the inline formatting context in which it participates.
  2073. if (display.is_flow_inside()) {
  2074. dbgln("FIXME: Inlinify inline box children recursively");
  2075. }
  2076. break;
  2077. }
  2078. if (display.is_internal()) {
  2079. // Inlinification has no effect on layout-internal boxes. (However, placement in such an inline context will typically cause them
  2080. // to be wrapped in an appropriately-typed anonymous inline-level box.)
  2081. } else {
  2082. VERIFY(display.is_outside_and_inside());
  2083. // If a block box (block flow) is inlinified, its inner display type is set to flow-root so that it remains a block container.
  2084. if (display.is_block_outside() && display.is_flow_inside()) {
  2085. new_display = CSS::Display { CSS::DisplayOutside::Inline, CSS::DisplayInside::FlowRoot, display.list_item() };
  2086. }
  2087. new_display = CSS::Display { CSS::DisplayOutside::Inline, display.inside(), display.list_item() };
  2088. }
  2089. break;
  2090. }
  2091. if (new_display != display)
  2092. style.set_property(CSS::PropertyID::Display, DisplayStyleValue::create(new_display), style.property_source_declaration(CSS::PropertyID::Display));
  2093. }
  2094. NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const
  2095. {
  2096. auto style = StyleProperties::create();
  2097. compute_math_depth(style, nullptr, {});
  2098. compute_font(style, nullptr, {});
  2099. compute_defaulted_values(style, nullptr, {});
  2100. absolutize_values(style);
  2101. style->set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().width())), nullptr);
  2102. style->set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length::make_px(viewport_rect().height())), nullptr);
  2103. style->set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::Block)), nullptr);
  2104. return style;
  2105. }
  2106. NonnullRefPtr<StyleProperties> StyleComputer::compute_style(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  2107. {
  2108. return compute_style_impl(element, move(pseudo_element), ComputeStyleMode::Normal).release_nonnull();
  2109. }
  2110. RefPtr<StyleProperties> StyleComputer::compute_pseudo_element_style_if_needed(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  2111. {
  2112. return compute_style_impl(element, move(pseudo_element), ComputeStyleMode::CreatePseudoElementStyleIfNeeded);
  2113. }
  2114. RefPtr<StyleProperties> StyleComputer::compute_style_impl(DOM::Element& element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element, ComputeStyleMode mode) const
  2115. {
  2116. build_rule_cache_if_needed();
  2117. // Special path for elements that use pseudo element as style selector
  2118. if (element.use_pseudo_element().has_value()) {
  2119. auto& parent_element = verify_cast<HTML::HTMLElement>(*element.root().parent_or_shadow_host());
  2120. auto style = compute_style(parent_element, *element.use_pseudo_element());
  2121. // Merge back inline styles
  2122. if (element.has_attribute(HTML::AttributeNames::style)) {
  2123. auto* inline_style = parse_css_style_attribute(CSS::Parser::ParsingContext(document()), *element.get_attribute(HTML::AttributeNames::style), element);
  2124. for (auto const& property : inline_style->properties())
  2125. style->set_property(property.property_id, property.value);
  2126. }
  2127. return style;
  2128. }
  2129. auto style = StyleProperties::create();
  2130. // 1. Perform the cascade. This produces the "specified style"
  2131. bool did_match_any_pseudo_element_rules = false;
  2132. compute_cascaded_values(style, element, pseudo_element, did_match_any_pseudo_element_rules, mode);
  2133. if (mode == ComputeStyleMode::CreatePseudoElementStyleIfNeeded && !did_match_any_pseudo_element_rules)
  2134. return nullptr;
  2135. // 2. Compute the math-depth property, since that might affect the font-size
  2136. compute_math_depth(style, &element, pseudo_element);
  2137. // 3. Compute the font, since that may be needed for font-relative CSS units
  2138. compute_font(style, &element, pseudo_element);
  2139. // 4. Absolutize values, turning font/viewport relative lengths into absolute lengths
  2140. absolutize_values(style);
  2141. // 5. Default the values, applying inheritance and 'initial' as needed
  2142. compute_defaulted_values(style, &element, pseudo_element);
  2143. // 6. Run automatic box type transformations
  2144. transform_box_type_if_needed(style, element, pseudo_element);
  2145. // 7. Resolve effective overflow values
  2146. resolve_effective_overflow_values(style);
  2147. // 8. Let the element adjust computed style
  2148. element.adjust_computed_style(style);
  2149. return style;
  2150. }
  2151. void StyleComputer::build_rule_cache_if_needed() const
  2152. {
  2153. if (m_author_rule_cache && m_user_rule_cache && m_user_agent_rule_cache)
  2154. return;
  2155. const_cast<StyleComputer&>(*this).build_rule_cache();
  2156. }
  2157. NonnullOwnPtr<StyleComputer::RuleCache> StyleComputer::make_rule_cache_for_cascade_origin(CascadeOrigin cascade_origin)
  2158. {
  2159. auto rule_cache = make<RuleCache>();
  2160. size_t num_class_rules = 0;
  2161. size_t num_id_rules = 0;
  2162. size_t num_tag_name_rules = 0;
  2163. size_t num_pseudo_element_rules = 0;
  2164. size_t num_root_rules = 0;
  2165. size_t num_attribute_rules = 0;
  2166. Vector<MatchingRule> matching_rules;
  2167. size_t style_sheet_index = 0;
  2168. for_each_stylesheet(cascade_origin, [&](auto& sheet, JS::GCPtr<DOM::ShadowRoot> shadow_root) {
  2169. size_t rule_index = 0;
  2170. sheet.for_each_effective_style_rule([&](auto const& rule) {
  2171. size_t selector_index = 0;
  2172. for (CSS::Selector const& selector : rule.selectors()) {
  2173. MatchingRule matching_rule {
  2174. shadow_root,
  2175. &rule,
  2176. sheet,
  2177. style_sheet_index,
  2178. rule_index,
  2179. selector_index,
  2180. selector.specificity(),
  2181. cascade_origin,
  2182. false,
  2183. false,
  2184. SelectorEngine::can_use_fast_matches(selector),
  2185. };
  2186. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  2187. if (!matching_rule.contains_pseudo_element) {
  2188. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::PseudoElement) {
  2189. matching_rule.contains_pseudo_element = true;
  2190. ++num_pseudo_element_rules;
  2191. }
  2192. }
  2193. if (!matching_rule.contains_root_pseudo_class) {
  2194. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::PseudoClass
  2195. && simple_selector.pseudo_class().type == CSS::PseudoClass::Root) {
  2196. matching_rule.contains_root_pseudo_class = true;
  2197. ++num_root_rules;
  2198. }
  2199. }
  2200. }
  2201. bool added_to_bucket = false;
  2202. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  2203. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Id) {
  2204. rule_cache->rules_by_id.ensure(simple_selector.name()).append(move(matching_rule));
  2205. ++num_id_rules;
  2206. added_to_bucket = true;
  2207. break;
  2208. }
  2209. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Class) {
  2210. rule_cache->rules_by_class.ensure(simple_selector.name()).append(move(matching_rule));
  2211. ++num_class_rules;
  2212. added_to_bucket = true;
  2213. break;
  2214. }
  2215. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::TagName) {
  2216. rule_cache->rules_by_tag_name.ensure(simple_selector.qualified_name().name.lowercase_name).append(move(matching_rule));
  2217. ++num_tag_name_rules;
  2218. added_to_bucket = true;
  2219. break;
  2220. }
  2221. }
  2222. if (!added_to_bucket) {
  2223. if (matching_rule.contains_pseudo_element) {
  2224. rule_cache->pseudo_element_rules.append(move(matching_rule));
  2225. } else if (matching_rule.contains_root_pseudo_class) {
  2226. rule_cache->root_rules.append(move(matching_rule));
  2227. } else {
  2228. for (auto const& simple_selector : selector.compound_selectors().last().simple_selectors) {
  2229. if (simple_selector.type == CSS::Selector::SimpleSelector::Type::Attribute) {
  2230. rule_cache->rules_by_attribute_name.ensure(simple_selector.attribute().qualified_name.name.lowercase_name).append(move(matching_rule));
  2231. ++num_attribute_rules;
  2232. added_to_bucket = true;
  2233. break;
  2234. }
  2235. }
  2236. if (!added_to_bucket) {
  2237. rule_cache->other_rules.append(move(matching_rule));
  2238. }
  2239. }
  2240. }
  2241. ++selector_index;
  2242. }
  2243. ++rule_index;
  2244. });
  2245. // Loosely based on https://drafts.csswg.org/css-animations-2/#keyframe-processing
  2246. sheet.for_each_effective_keyframes_at_rule([&](CSSKeyframesRule const& rule) {
  2247. auto keyframe_set = adopt_ref(*new Animations::KeyframeEffect::KeyFrameSet);
  2248. HashTable<PropertyID> animated_properties;
  2249. // Forwards pass, resolve all the user-specified keyframe properties.
  2250. for (auto const& keyframe_rule : *rule.css_rules()) {
  2251. auto const& keyframe = verify_cast<CSSKeyframeRule>(*keyframe_rule);
  2252. Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame resolved_keyframe;
  2253. auto key = static_cast<u64>(keyframe.key().value() * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor);
  2254. auto const& keyframe_style = *keyframe.style_as_property_owning_style_declaration();
  2255. for (auto const& it : keyframe_style.properties()) {
  2256. // Unresolved properties will be resolved in collect_animation_into()
  2257. for_each_property_expanding_shorthands(it.property_id, it.value, AllowUnresolved::Yes, [&](PropertyID shorthand_id, StyleValue const& shorthand_value) {
  2258. animated_properties.set(shorthand_id);
  2259. resolved_keyframe.properties.set(shorthand_id, NonnullRefPtr<StyleValue const> { shorthand_value });
  2260. });
  2261. }
  2262. keyframe_set->keyframes_by_key.insert(key, resolved_keyframe);
  2263. }
  2264. Animations::KeyframeEffect::generate_initial_and_final_frames(keyframe_set, animated_properties);
  2265. if constexpr (LIBWEB_CSS_DEBUG) {
  2266. dbgln("Resolved keyframe set '{}' into {} keyframes:", rule.name(), keyframe_set->keyframes_by_key.size());
  2267. for (auto it = keyframe_set->keyframes_by_key.begin(); it != keyframe_set->keyframes_by_key.end(); ++it)
  2268. dbgln(" - keyframe {}: {} properties", it.key(), it->properties.size());
  2269. }
  2270. rule_cache->rules_by_animation_keyframes.set(rule.name(), move(keyframe_set));
  2271. });
  2272. ++style_sheet_index;
  2273. });
  2274. size_t total_rules = num_class_rules + num_id_rules + num_tag_name_rules + num_pseudo_element_rules + num_root_rules + num_attribute_rules + rule_cache->other_rules.size();
  2275. if constexpr (LIBWEB_CSS_DEBUG) {
  2276. dbgln("Built rule cache!");
  2277. dbgln(" ID: {}", num_id_rules);
  2278. dbgln(" Class: {}", num_class_rules);
  2279. dbgln(" TagName: {}", num_tag_name_rules);
  2280. dbgln("PseudoElement: {}", num_pseudo_element_rules);
  2281. dbgln(" Root: {}", num_root_rules);
  2282. dbgln(" Attribute: {}", num_attribute_rules);
  2283. dbgln(" Other: {}", rule_cache->other_rules.size());
  2284. dbgln(" Total: {}", total_rules);
  2285. }
  2286. return rule_cache;
  2287. }
  2288. void StyleComputer::build_rule_cache()
  2289. {
  2290. if (auto user_style_source = document().page().user_style(); user_style_source.has_value()) {
  2291. m_user_style_sheet = JS::make_handle(parse_css_stylesheet(CSS::Parser::ParsingContext(document()), user_style_source.value()));
  2292. }
  2293. m_author_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::Author);
  2294. m_user_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::User);
  2295. m_user_agent_rule_cache = make_rule_cache_for_cascade_origin(CascadeOrigin::UserAgent);
  2296. }
  2297. void StyleComputer::invalidate_rule_cache()
  2298. {
  2299. m_author_rule_cache = nullptr;
  2300. // NOTE: We could be smarter about keeping the user rule cache, and style sheet.
  2301. // Currently we are re-parsing the user style sheet every time we build the caches,
  2302. // as it may have changed.
  2303. m_user_rule_cache = nullptr;
  2304. m_user_style_sheet = nullptr;
  2305. // NOTE: It might not be necessary to throw away the UA rule cache.
  2306. // If we are sure that it's safe, we could keep it as an optimization.
  2307. m_user_agent_rule_cache = nullptr;
  2308. }
  2309. void StyleComputer::did_load_font(FlyString const&)
  2310. {
  2311. document().invalidate_style();
  2312. }
  2313. Optional<FontLoader&> StyleComputer::load_font_face(ParsedFontFace const& font_face, Function<void(FontLoader const&)> on_load, Function<void()> on_fail)
  2314. {
  2315. if (font_face.sources().is_empty()) {
  2316. if (on_fail)
  2317. on_fail();
  2318. return {};
  2319. }
  2320. FontFaceKey key {
  2321. .family_name = font_face.font_family(),
  2322. .weight = font_face.weight().value_or(0),
  2323. .slope = font_face.slope().value_or(0),
  2324. };
  2325. Vector<URL::URL> urls;
  2326. for (auto const& source : font_face.sources()) {
  2327. // FIXME: These should be loaded relative to the stylesheet URL instead of the document URL.
  2328. if (source.local_or_url.has<URL::URL>())
  2329. urls.append(m_document->parse_url(MUST(source.local_or_url.get<URL::URL>().to_string())));
  2330. // FIXME: Handle local()
  2331. }
  2332. if (urls.is_empty()) {
  2333. if (on_fail)
  2334. on_fail();
  2335. return {};
  2336. }
  2337. auto loader = make<FontLoader>(const_cast<StyleComputer&>(*this), font_face.font_family(), font_face.unicode_ranges(), move(urls), move(on_load), move(on_fail));
  2338. auto& loader_ref = *loader;
  2339. auto maybe_font_loaders_list = const_cast<StyleComputer&>(*this).m_loaded_fonts.get(key);
  2340. if (maybe_font_loaders_list.has_value()) {
  2341. maybe_font_loaders_list->append(move(loader));
  2342. } else {
  2343. FontLoaderList loaders;
  2344. loaders.append(move(loader));
  2345. const_cast<StyleComputer&>(*this).m_loaded_fonts.set(key, move(loaders));
  2346. }
  2347. // Actual object owned by font loader list inside m_loaded_fonts, this isn't use-after-move/free
  2348. return loader_ref;
  2349. }
  2350. void StyleComputer::load_fonts_from_sheet(CSSStyleSheet const& sheet)
  2351. {
  2352. for (auto const& rule : sheet.rules()) {
  2353. if (!is<CSSFontFaceRule>(*rule))
  2354. continue;
  2355. (void)load_font_face(static_cast<CSSFontFaceRule const&>(*rule).font_face());
  2356. }
  2357. }
  2358. void StyleComputer::compute_math_depth(StyleProperties& style, DOM::Element const* element, Optional<CSS::Selector::PseudoElement::Type> pseudo_element) const
  2359. {
  2360. // https://w3c.github.io/mathml-core/#propdef-math-depth
  2361. // First, ensure that the relevant CSS properties have been defaulted.
  2362. // FIXME: This should be more sophisticated.
  2363. compute_defaulted_property_value(style, element, CSS::PropertyID::MathDepth, pseudo_element);
  2364. compute_defaulted_property_value(style, element, CSS::PropertyID::MathStyle, pseudo_element);
  2365. auto inherited_math_depth = [&]() {
  2366. if (!element || !element->parent_element())
  2367. return InitialValues::math_depth();
  2368. return element->parent_element()->computed_css_values()->math_depth();
  2369. };
  2370. auto value = style.property(CSS::PropertyID::MathDepth);
  2371. if (!value->is_math_depth()) {
  2372. style.set_math_depth(inherited_math_depth());
  2373. return;
  2374. }
  2375. auto& math_depth = value->as_math_depth();
  2376. auto resolve_integer = [&](StyleValue const& integer_value) {
  2377. if (integer_value.is_integer())
  2378. return integer_value.as_integer().integer();
  2379. if (integer_value.is_calculated())
  2380. return integer_value.as_calculated().resolve_integer().value();
  2381. VERIFY_NOT_REACHED();
  2382. };
  2383. // The computed value of the math-depth value is determined as follows:
  2384. // - If the specified value of math-depth is auto-add and the inherited value of math-style is compact
  2385. // then the computed value of math-depth of the element is its inherited value plus one.
  2386. if (math_depth.is_auto_add() && style.property(CSS::PropertyID::MathStyle)->to_identifier() == CSS::ValueID::Compact) {
  2387. style.set_math_depth(inherited_math_depth() + 1);
  2388. return;
  2389. }
  2390. // - If the specified value of math-depth is of the form add(<integer>) then the computed value of
  2391. // math-depth of the element is its inherited value plus the specified integer.
  2392. if (math_depth.is_add()) {
  2393. style.set_math_depth(inherited_math_depth() + resolve_integer(*math_depth.integer_value()));
  2394. return;
  2395. }
  2396. // - If the specified value of math-depth is of the form <integer> then the computed value of math-depth
  2397. // of the element is the specified integer.
  2398. if (math_depth.is_integer()) {
  2399. style.set_math_depth(resolve_integer(*math_depth.integer_value()));
  2400. return;
  2401. }
  2402. // - Otherwise, the computed value of math-depth of the element is the inherited one.
  2403. style.set_math_depth(inherited_math_depth());
  2404. }
  2405. static void for_each_element_hash(DOM::Element const& element, auto callback)
  2406. {
  2407. callback(element.local_name().hash());
  2408. if (element.id().has_value())
  2409. callback(element.id().value().hash());
  2410. for (auto const& class_ : element.class_names())
  2411. callback(class_.hash());
  2412. element.for_each_attribute([&](auto& attribute) {
  2413. callback(attribute.local_name().hash());
  2414. });
  2415. }
  2416. void StyleComputer::reset_ancestor_filter()
  2417. {
  2418. m_ancestor_filter.clear();
  2419. }
  2420. void StyleComputer::push_ancestor(DOM::Element const& element)
  2421. {
  2422. for_each_element_hash(element, [&](u32 hash) {
  2423. m_ancestor_filter.increment(hash);
  2424. });
  2425. }
  2426. void StyleComputer::pop_ancestor(DOM::Element const& element)
  2427. {
  2428. for_each_element_hash(element, [&](u32 hash) {
  2429. m_ancestor_filter.decrement(hash);
  2430. });
  2431. }
  2432. }