TreeBuilder.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Error.h>
  9. #include <AK/Optional.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <LibWeb/CSS/StyleComputer.h>
  12. #include <LibWeb/CSS/StyleValues/CSSKeywordValue.h>
  13. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  14. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  15. #include <LibWeb/DOM/Document.h>
  16. #include <LibWeb/DOM/Element.h>
  17. #include <LibWeb/DOM/ParentNode.h>
  18. #include <LibWeb/DOM/ShadowRoot.h>
  19. #include <LibWeb/Dump.h>
  20. #include <LibWeb/HTML/HTMLButtonElement.h>
  21. #include <LibWeb/HTML/HTMLInputElement.h>
  22. #include <LibWeb/HTML/HTMLLIElement.h>
  23. #include <LibWeb/HTML/HTMLOListElement.h>
  24. #include <LibWeb/HTML/HTMLSlotElement.h>
  25. #include <LibWeb/Layout/ListItemBox.h>
  26. #include <LibWeb/Layout/ListItemMarkerBox.h>
  27. #include <LibWeb/Layout/Node.h>
  28. #include <LibWeb/Layout/SVGClipBox.h>
  29. #include <LibWeb/Layout/SVGMaskBox.h>
  30. #include <LibWeb/Layout/TableGrid.h>
  31. #include <LibWeb/Layout/TableWrapper.h>
  32. #include <LibWeb/Layout/TextNode.h>
  33. #include <LibWeb/Layout/TreeBuilder.h>
  34. #include <LibWeb/Layout/Viewport.h>
  35. #include <LibWeb/SVG/SVGForeignObjectElement.h>
  36. namespace Web::Layout {
  37. TreeBuilder::TreeBuilder() = default;
  38. static bool has_inline_or_in_flow_block_children(Layout::Node const& layout_node)
  39. {
  40. for (auto child = layout_node.first_child(); child; child = child->next_sibling()) {
  41. if (child->is_inline() || child->is_in_flow())
  42. return true;
  43. }
  44. return false;
  45. }
  46. static bool has_in_flow_block_children(Layout::Node const& layout_node)
  47. {
  48. if (layout_node.children_are_inline())
  49. return false;
  50. for (auto child = layout_node.first_child(); child; child = child->next_sibling()) {
  51. if (child->is_inline())
  52. continue;
  53. if (child->is_in_flow())
  54. return true;
  55. }
  56. return false;
  57. }
  58. // The insertion_parent_for_*() functions maintain the invariant that the in-flow children of
  59. // block-level boxes must be either all block-level or all inline-level.
  60. static Layout::Node& insertion_parent_for_inline_node(Layout::NodeWithStyle& layout_parent)
  61. {
  62. auto last_child_creating_anonymous_wrapper_if_needed = [](auto& layout_parent) -> Layout::Node& {
  63. if (!layout_parent.last_child()
  64. || !layout_parent.last_child()->is_anonymous()
  65. || !layout_parent.last_child()->children_are_inline()
  66. || layout_parent.last_child()->is_generated()) {
  67. layout_parent.append_child(layout_parent.create_anonymous_wrapper());
  68. }
  69. return *layout_parent.last_child();
  70. };
  71. if (layout_parent.display().is_inline_outside() && layout_parent.display().is_flow_inside())
  72. return layout_parent;
  73. if (layout_parent.display().is_flex_inside() || layout_parent.display().is_grid_inside())
  74. return last_child_creating_anonymous_wrapper_if_needed(layout_parent);
  75. if (!has_in_flow_block_children(layout_parent) || layout_parent.children_are_inline())
  76. return layout_parent;
  77. // Parent has block-level children, insert into an anonymous wrapper block (and create it first if needed)
  78. return last_child_creating_anonymous_wrapper_if_needed(layout_parent);
  79. }
  80. static Layout::Node& insertion_parent_for_block_node(Layout::NodeWithStyle& layout_parent, Layout::Node& layout_node)
  81. {
  82. if (!has_inline_or_in_flow_block_children(layout_parent)) {
  83. // Parent block has no children, insert this block into parent.
  84. return layout_parent;
  85. }
  86. if (layout_node.is_out_of_flow()
  87. && !layout_parent.display().is_flex_inside()
  88. && !layout_parent.display().is_grid_inside()
  89. && !layout_parent.last_child()->is_generated()
  90. && layout_parent.last_child()->is_anonymous()
  91. && layout_parent.last_child()->children_are_inline()) {
  92. // Block is out-of-flow & previous sibling was wrapped in an anonymous block.
  93. // Join the previous sibling inside the anonymous block.
  94. return *layout_parent.last_child();
  95. }
  96. if (!layout_parent.children_are_inline()) {
  97. // Parent block has block-level children, insert this block into parent.
  98. return layout_parent;
  99. }
  100. if (layout_node.is_out_of_flow()) {
  101. // Block is out-of-flow, it can have inline siblings if necessary.
  102. return layout_parent;
  103. }
  104. // Parent block has inline-level children (our siblings).
  105. // First move these siblings into an anonymous wrapper block.
  106. Vector<JS::Handle<Layout::Node>> children;
  107. {
  108. JS::GCPtr<Layout::Node> next;
  109. for (JS::GCPtr<Layout::Node> child = layout_parent.first_child(); child; child = next) {
  110. next = child->next_sibling();
  111. // NOTE: We let out-of-flow children stay in the parent, to preserve tree structure.
  112. if (child->is_out_of_flow())
  113. continue;
  114. layout_parent.remove_child(*child);
  115. children.append(*child);
  116. }
  117. }
  118. layout_parent.append_child(layout_parent.create_anonymous_wrapper());
  119. layout_parent.set_children_are_inline(false);
  120. for (auto& child : children) {
  121. layout_parent.last_child()->append_child(*child);
  122. }
  123. layout_parent.last_child()->set_children_are_inline(true);
  124. // Then it's safe to insert this block into parent.
  125. return layout_parent;
  126. }
  127. void TreeBuilder::insert_node_into_inline_or_block_ancestor(Layout::Node& node, CSS::Display display, AppendOrPrepend mode)
  128. {
  129. if (node.display().is_contents())
  130. return;
  131. if (display.is_inline_outside()) {
  132. // Inlines can be inserted into the nearest ancestor without "display: contents".
  133. auto& nearest_ancestor_without_display_contents = [&]() -> Layout::NodeWithStyle& {
  134. for (auto& ancestor : m_ancestor_stack.in_reverse()) {
  135. if (!ancestor->display().is_contents())
  136. return ancestor;
  137. }
  138. VERIFY_NOT_REACHED();
  139. }();
  140. auto& insertion_point = insertion_parent_for_inline_node(nearest_ancestor_without_display_contents);
  141. if (mode == AppendOrPrepend::Prepend)
  142. insertion_point.prepend_child(node);
  143. else
  144. insertion_point.append_child(node);
  145. insertion_point.set_children_are_inline(true);
  146. } else {
  147. // Non-inlines can't be inserted into an inline parent, so find the nearest non-inline ancestor.
  148. auto& nearest_non_inline_ancestor = [&]() -> Layout::NodeWithStyle& {
  149. for (auto& ancestor : m_ancestor_stack.in_reverse()) {
  150. if (ancestor->display().is_contents())
  151. continue;
  152. if (!ancestor->display().is_inline_outside())
  153. return ancestor;
  154. if (!ancestor->display().is_flow_inside())
  155. return ancestor;
  156. if (ancestor->dom_node() && is<SVG::SVGForeignObjectElement>(*ancestor->dom_node()))
  157. return ancestor;
  158. }
  159. VERIFY_NOT_REACHED();
  160. }();
  161. auto& insertion_point = insertion_parent_for_block_node(nearest_non_inline_ancestor, node);
  162. if (mode == AppendOrPrepend::Prepend)
  163. insertion_point.prepend_child(node);
  164. else
  165. insertion_point.append_child(node);
  166. // After inserting an in-flow block-level box into a parent, mark the parent as having non-inline children.
  167. if (!node.is_floating() && !node.is_absolutely_positioned())
  168. insertion_point.set_children_are_inline(false);
  169. }
  170. }
  171. void TreeBuilder::create_pseudo_element_if_needed(DOM::Element& element, CSS::Selector::PseudoElement::Type pseudo_element, AppendOrPrepend mode)
  172. {
  173. auto& document = element.document();
  174. auto pseudo_element_style = element.pseudo_element_computed_css_values(pseudo_element);
  175. if (!pseudo_element_style.has_value())
  176. return;
  177. auto initial_quote_nesting_level = m_quote_nesting_level;
  178. auto [pseudo_element_content, final_quote_nesting_level] = pseudo_element_style->content(element, initial_quote_nesting_level);
  179. m_quote_nesting_level = final_quote_nesting_level;
  180. auto pseudo_element_display = pseudo_element_style->display();
  181. // ::before and ::after only exist if they have content. `content: normal` computes to `none` for them.
  182. // We also don't create them if they are `display: none`.
  183. if (pseudo_element_display.is_none()
  184. || pseudo_element_content.type == CSS::ContentData::Type::Normal
  185. || pseudo_element_content.type == CSS::ContentData::Type::None)
  186. return;
  187. auto pseudo_element_node = DOM::Element::create_layout_node_for_display_type(document, pseudo_element_display, *pseudo_element_style, nullptr);
  188. if (!pseudo_element_node)
  189. return;
  190. auto& style_computer = document.style_computer();
  191. // FIXME: This code actually computes style for element::marker, and shouldn't for element::pseudo::marker
  192. if (is<ListItemBox>(*pseudo_element_node)) {
  193. auto marker_style = style_computer.compute_style(element, CSS::Selector::PseudoElement::Type::Marker);
  194. auto list_item_marker = document.heap().allocate_without_realm<ListItemMarkerBox>(
  195. document,
  196. pseudo_element_node->computed_values().list_style_type(),
  197. pseudo_element_node->computed_values().list_style_position(),
  198. 0,
  199. marker_style);
  200. static_cast<ListItemBox&>(*pseudo_element_node).set_marker(list_item_marker);
  201. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::Type::Marker, list_item_marker);
  202. pseudo_element_node->append_child(*list_item_marker);
  203. }
  204. auto generated_for = Node::GeneratedFor::NotGenerated;
  205. if (pseudo_element == CSS::Selector::PseudoElement::Type::Before) {
  206. generated_for = Node::GeneratedFor::PseudoBefore;
  207. } else if (pseudo_element == CSS::Selector::PseudoElement::Type::After) {
  208. generated_for = Node::GeneratedFor::PseudoAfter;
  209. } else {
  210. VERIFY_NOT_REACHED();
  211. }
  212. pseudo_element_node->set_generated_for(generated_for, element);
  213. pseudo_element_node->set_initial_quote_nesting_level(initial_quote_nesting_level);
  214. // FIXME: Handle images, and multiple values
  215. if (pseudo_element_content.type == CSS::ContentData::Type::String) {
  216. auto text = document.heap().allocate<DOM::Text>(document.realm(), document, pseudo_element_content.data);
  217. auto text_node = document.heap().allocate_without_realm<Layout::TextNode>(document, *text);
  218. text_node->set_generated_for(generated_for, element);
  219. push_parent(*pseudo_element_node);
  220. insert_node_into_inline_or_block_ancestor(*text_node, text_node->display(), AppendOrPrepend::Append);
  221. pop_parent();
  222. } else {
  223. TODO();
  224. }
  225. element.set_pseudo_element_node({}, pseudo_element, pseudo_element_node);
  226. insert_node_into_inline_or_block_ancestor(*pseudo_element_node, pseudo_element_display, mode);
  227. }
  228. static bool is_ignorable_whitespace(Layout::Node const& node)
  229. {
  230. if (node.is_text_node() && static_cast<TextNode const&>(node).text_for_rendering().bytes_as_string_view().is_whitespace())
  231. return true;
  232. if (node.is_anonymous() && node.is_block_container() && static_cast<BlockContainer const&>(node).children_are_inline()) {
  233. bool contains_only_white_space = true;
  234. node.for_each_in_inclusive_subtree_of_type<TextNode>([&contains_only_white_space](auto& text_node) {
  235. if (!text_node.text_for_rendering().bytes_as_string_view().is_whitespace()) {
  236. contains_only_white_space = false;
  237. return TraversalDecision::Break;
  238. }
  239. return TraversalDecision::Continue;
  240. });
  241. if (contains_only_white_space)
  242. return true;
  243. }
  244. return false;
  245. }
  246. i32 TreeBuilder::calculate_list_item_index(DOM::Node& dom_node)
  247. {
  248. if (is<HTML::HTMLLIElement>(dom_node)) {
  249. auto& li = static_cast<HTML::HTMLLIElement&>(dom_node);
  250. if (li.value() != 0)
  251. return li.value();
  252. }
  253. if (dom_node.previous_sibling() != nullptr) {
  254. DOM::Node* current = dom_node.previous_sibling();
  255. while (current != nullptr) {
  256. if (is<HTML::HTMLLIElement>(*current))
  257. return calculate_list_item_index(*current) + 1;
  258. current = current->previous_sibling();
  259. }
  260. }
  261. if (is<HTML::HTMLOListElement>(*dom_node.parent())) {
  262. auto& ol = static_cast<HTML::HTMLOListElement&>(*dom_node.parent());
  263. return ol.start();
  264. }
  265. return 1;
  266. }
  267. void TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder::Context& context)
  268. {
  269. if (dom_node.is_element()) {
  270. auto& element = static_cast<DOM::Element&>(dom_node);
  271. if (element.in_top_layer() && !context.layout_top_layer)
  272. return;
  273. }
  274. if (dom_node.is_element())
  275. dom_node.document().style_computer().push_ancestor(static_cast<DOM::Element const&>(dom_node));
  276. ScopeGuard pop_ancestor_guard = [&] {
  277. if (dom_node.is_element())
  278. dom_node.document().style_computer().pop_ancestor(static_cast<DOM::Element const&>(dom_node));
  279. };
  280. JS::GCPtr<Layout::Node> layout_node;
  281. Optional<TemporaryChange<bool>> has_svg_root_change;
  282. ScopeGuard remove_stale_layout_node_guard = [&] {
  283. // If we didn't create a layout node for this DOM node,
  284. // go through the DOM tree and remove any old layout & paint nodes since they are now all stale.
  285. if (!layout_node) {
  286. dom_node.for_each_in_inclusive_subtree([&](auto& node) {
  287. node.detach_layout_node({});
  288. node.clear_paintable();
  289. if (is<DOM::Element>(node))
  290. static_cast<DOM::Element&>(node).clear_pseudo_element_nodes({});
  291. return TraversalDecision::Continue;
  292. });
  293. }
  294. };
  295. if (dom_node.is_svg_container()) {
  296. has_svg_root_change.emplace(context.has_svg_root, true);
  297. } else if (dom_node.requires_svg_container() && !context.has_svg_root) {
  298. return;
  299. }
  300. auto& document = dom_node.document();
  301. auto& style_computer = document.style_computer();
  302. Optional<CSS::StyleProperties> style;
  303. CSS::Display display;
  304. if (is<DOM::Element>(dom_node)) {
  305. auto& element = static_cast<DOM::Element&>(dom_node);
  306. element.clear_pseudo_element_nodes({});
  307. VERIFY(!element.needs_style_update());
  308. style = element.computed_css_values();
  309. element.resolve_counters(*style);
  310. display = style->display();
  311. if (display.is_none())
  312. return;
  313. // TODO: Implement changing element contents with the `content` property.
  314. if (context.layout_svg_mask_or_clip_path) {
  315. if (is<SVG::SVGMaskElement>(dom_node))
  316. layout_node = document.heap().allocate_without_realm<Layout::SVGMaskBox>(document, static_cast<SVG::SVGMaskElement&>(dom_node), *style);
  317. else if (is<SVG::SVGClipPathElement>(dom_node))
  318. layout_node = document.heap().allocate_without_realm<Layout::SVGClipBox>(document, static_cast<SVG::SVGClipPathElement&>(dom_node), *style);
  319. else
  320. VERIFY_NOT_REACHED();
  321. // Only layout direct uses of SVG masks/clipPaths.
  322. context.layout_svg_mask_or_clip_path = false;
  323. } else {
  324. layout_node = element.create_layout_node(*style);
  325. }
  326. } else if (is<DOM::Document>(dom_node)) {
  327. style = style_computer.create_document_style();
  328. display = style->display();
  329. layout_node = document.heap().allocate_without_realm<Layout::Viewport>(static_cast<DOM::Document&>(dom_node), *style);
  330. } else if (is<DOM::Text>(dom_node)) {
  331. layout_node = document.heap().allocate_without_realm<Layout::TextNode>(document, static_cast<DOM::Text&>(dom_node));
  332. display = CSS::Display(CSS::DisplayOutside::Inline, CSS::DisplayInside::Flow);
  333. }
  334. if (!layout_node)
  335. return;
  336. if (!dom_node.parent_or_shadow_host()) {
  337. m_layout_root = layout_node;
  338. } else if (layout_node->is_svg_box()) {
  339. m_ancestor_stack.last()->append_child(*layout_node);
  340. } else {
  341. insert_node_into_inline_or_block_ancestor(*layout_node, display, AppendOrPrepend::Append);
  342. }
  343. auto shadow_root = is<DOM::Element>(dom_node) ? verify_cast<DOM::Element>(dom_node).shadow_root() : nullptr;
  344. auto element_has_content_visibility_hidden = [&dom_node]() {
  345. if (is<DOM::Element>(dom_node)) {
  346. auto& element = static_cast<DOM::Element&>(dom_node);
  347. return element.computed_css_values()->content_visibility() == CSS::ContentVisibility::Hidden;
  348. }
  349. return false;
  350. }();
  351. // Add node for the ::before pseudo-element.
  352. if (is<DOM::Element>(dom_node) && layout_node->can_have_children() && !element_has_content_visibility_hidden) {
  353. auto& element = static_cast<DOM::Element&>(dom_node);
  354. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  355. create_pseudo_element_if_needed(element, CSS::Selector::PseudoElement::Type::Before, AppendOrPrepend::Prepend);
  356. pop_parent();
  357. }
  358. if ((dom_node.has_children() || shadow_root) && layout_node->can_have_children() && !element_has_content_visibility_hidden) {
  359. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  360. if (shadow_root) {
  361. for (auto* node = shadow_root->first_child(); node; node = node->next_sibling()) {
  362. create_layout_tree(*node, context);
  363. }
  364. } else {
  365. // This is the same as verify_cast<DOM::ParentNode>(dom_node).for_each_child
  366. for (auto* node = verify_cast<DOM::ParentNode>(dom_node).first_child(); node; node = node->next_sibling())
  367. create_layout_tree(*node, context);
  368. }
  369. if (dom_node.is_document()) {
  370. // Elements in the top layer do not lay out normally based on their position in the document; instead they
  371. // generate boxes as if they were siblings of the root element.
  372. TemporaryChange<bool> layout_mask(context.layout_top_layer, true);
  373. for (auto const& top_layer_element : document.top_layer_elements())
  374. create_layout_tree(top_layer_element, context);
  375. }
  376. pop_parent();
  377. }
  378. if (is<ListItemBox>(*layout_node)) {
  379. auto& element = static_cast<DOM::Element&>(dom_node);
  380. auto marker_style = style_computer.compute_style(element, CSS::Selector::PseudoElement::Type::Marker);
  381. auto list_item_marker = document.heap().allocate_without_realm<ListItemMarkerBox>(document, layout_node->computed_values().list_style_type(), layout_node->computed_values().list_style_position(), calculate_list_item_index(dom_node), marker_style);
  382. static_cast<ListItemBox&>(*layout_node).set_marker(list_item_marker);
  383. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::Type::Marker, list_item_marker);
  384. layout_node->append_child(*list_item_marker);
  385. }
  386. if (is<HTML::HTMLSlotElement>(dom_node)) {
  387. auto& slot_element = static_cast<HTML::HTMLSlotElement&>(dom_node);
  388. if (slot_element.computed_css_values()->content_visibility() == CSS::ContentVisibility::Hidden)
  389. return;
  390. auto slottables = slot_element.assigned_nodes_internal();
  391. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  392. for (auto const& slottable : slottables)
  393. slottable.visit([&](auto& node) { create_layout_tree(node, context); });
  394. pop_parent();
  395. }
  396. if (is<SVG::SVGGraphicsElement>(dom_node)) {
  397. auto& graphics_element = static_cast<SVG::SVGGraphicsElement&>(dom_node);
  398. // Create the layout tree for the SVG mask/clip paths as a child of the masked element.
  399. // Note: This will create a new subtree for each use of the mask (so there's not a 1-to-1 mapping
  400. // from DOM node to mask layout node). Each use of a mask may be laid out differently so this
  401. // duplication is necessary.
  402. auto layout_mask_or_clip_path = [&](JS::GCPtr<SVG::SVGElement const> mask_or_clip_path) {
  403. TemporaryChange<bool> layout_mask(context.layout_svg_mask_or_clip_path, true);
  404. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  405. create_layout_tree(const_cast<SVG::SVGElement&>(*mask_or_clip_path), context);
  406. pop_parent();
  407. };
  408. if (auto mask = graphics_element.mask())
  409. layout_mask_or_clip_path(mask);
  410. if (auto clip_path = graphics_element.clip_path())
  411. layout_mask_or_clip_path(clip_path);
  412. }
  413. auto is_button_layout = [&] {
  414. if (dom_node.is_html_button_element())
  415. return true;
  416. if (!dom_node.is_html_input_element())
  417. return false;
  418. // https://html.spec.whatwg.org/multipage/rendering.html#the-input-element-as-a-button
  419. // An input element whose type attribute is in the Submit Button, Reset Button, or Button state, when it generates a CSS box, is expected to depict a button and use button layout
  420. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(dom_node);
  421. if (input_element.is_button())
  422. return true;
  423. return false;
  424. }();
  425. // https://html.spec.whatwg.org/multipage/rendering.html#button-layout
  426. // If the computed value of 'inline-size' is 'auto', then the used value is the fit-content inline size.
  427. if (is_button_layout && dom_node.layout_node()->computed_values().width().is_auto()) {
  428. auto& computed_values = verify_cast<NodeWithStyle>(*dom_node.layout_node()).mutable_computed_values();
  429. computed_values.set_width(CSS::Size::make_fit_content());
  430. }
  431. // https://html.spec.whatwg.org/multipage/rendering.html#button-layout
  432. // If the element is an input element, or if it is a button element and its computed value for
  433. // 'display' is not 'inline-grid', 'grid', 'inline-flex', or 'flex', then the element's box has
  434. // a child anonymous button content box with the following behaviors:
  435. if (is_button_layout && !display.is_grid_inside() && !display.is_flex_inside()) {
  436. auto& parent = *dom_node.layout_node();
  437. // If the box does not overflow in the vertical axis, then it is centered vertically.
  438. // FIXME: Only apply alignment when box overflows
  439. auto flex_computed_values = parent.computed_values().clone_inherited_values();
  440. auto& mutable_flex_computed_values = static_cast<CSS::MutableComputedValues&>(*flex_computed_values);
  441. mutable_flex_computed_values.set_display(CSS::Display { CSS::DisplayOutside::Block, CSS::DisplayInside::Flex });
  442. mutable_flex_computed_values.set_justify_content(CSS::JustifyContent::Center);
  443. mutable_flex_computed_values.set_flex_direction(CSS::FlexDirection::Column);
  444. mutable_flex_computed_values.set_height(CSS::Size::make_percentage(CSS::Percentage(100)));
  445. mutable_flex_computed_values.set_min_height(parent.computed_values().min_height());
  446. auto flex_wrapper = parent.heap().template allocate_without_realm<BlockContainer>(parent.document(), nullptr, move(flex_computed_values));
  447. auto content_box_computed_values = parent.computed_values().clone_inherited_values();
  448. auto content_box_wrapper = parent.heap().template allocate_without_realm<BlockContainer>(parent.document(), nullptr, move(content_box_computed_values));
  449. content_box_wrapper->set_children_are_inline(parent.children_are_inline());
  450. Vector<JS::Handle<Node>> sequence;
  451. for (auto child = parent.first_child(); child; child = child->next_sibling()) {
  452. if (child->is_generated_for_before_pseudo_element())
  453. continue;
  454. sequence.append(*child);
  455. }
  456. for (auto& node : sequence) {
  457. parent.remove_child(*node);
  458. content_box_wrapper->append_child(*node);
  459. }
  460. flex_wrapper->append_child(*content_box_wrapper);
  461. parent.append_child(*flex_wrapper);
  462. parent.set_children_are_inline(false);
  463. }
  464. // Add nodes for the ::after pseudo-element.
  465. if (is<DOM::Element>(dom_node) && layout_node->can_have_children() && !element_has_content_visibility_hidden) {
  466. auto& element = static_cast<DOM::Element&>(dom_node);
  467. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  468. create_pseudo_element_if_needed(element, CSS::Selector::PseudoElement::Type::After, AppendOrPrepend::Append);
  469. pop_parent();
  470. }
  471. }
  472. JS::GCPtr<Layout::Node> TreeBuilder::build(DOM::Node& dom_node)
  473. {
  474. VERIFY(dom_node.is_document());
  475. dom_node.document().style_computer().reset_ancestor_filter();
  476. Context context;
  477. m_quote_nesting_level = 0;
  478. create_layout_tree(dom_node, context);
  479. if (auto* root = dom_node.document().layout_node())
  480. fixup_tables(*root);
  481. return move(m_layout_root);
  482. }
  483. template<CSS::DisplayInternal internal, typename Callback>
  484. void TreeBuilder::for_each_in_tree_with_internal_display(NodeWithStyle& root, Callback callback)
  485. {
  486. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& box) {
  487. auto const display = box.display();
  488. if (display.is_internal() && display.internal() == internal)
  489. callback(box);
  490. return TraversalDecision::Continue;
  491. });
  492. }
  493. template<CSS::DisplayInside inside, typename Callback>
  494. void TreeBuilder::for_each_in_tree_with_inside_display(NodeWithStyle& root, Callback callback)
  495. {
  496. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& box) {
  497. auto const display = box.display();
  498. if (display.is_outside_and_inside() && display.inside() == inside)
  499. callback(box);
  500. return TraversalDecision::Continue;
  501. });
  502. }
  503. void TreeBuilder::fixup_tables(NodeWithStyle& root)
  504. {
  505. remove_irrelevant_boxes(root);
  506. generate_missing_child_wrappers(root);
  507. auto table_root_boxes = generate_missing_parents(root);
  508. missing_cells_fixup(table_root_boxes);
  509. }
  510. void TreeBuilder::remove_irrelevant_boxes(NodeWithStyle& root)
  511. {
  512. // The following boxes are discarded as if they were display:none:
  513. Vector<JS::Handle<Node>> to_remove;
  514. // Children of a table-column.
  515. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableColumn>(root, [&](Box& table_column) {
  516. table_column.for_each_child([&](auto& child) {
  517. to_remove.append(child);
  518. return IterationDecision::Continue;
  519. });
  520. });
  521. // Children of a table-column-group which are not a table-column.
  522. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableColumnGroup>(root, [&](Box& table_column_group) {
  523. table_column_group.for_each_child([&](auto& child) {
  524. if (!child.display().is_table_column())
  525. to_remove.append(child);
  526. return IterationDecision::Continue;
  527. });
  528. });
  529. // FIXME:
  530. // Anonymous inline boxes which contain only white space and are between two immediate siblings each of which is a table-non-root box.
  531. // Anonymous inline boxes which meet all of the following criteria:
  532. // - they contain only white space
  533. // - they are the first and/or last child of a tabular container
  534. // - whose immediate sibling, if any, is a table-non-root box
  535. for (auto& box : to_remove)
  536. box->parent()->remove_child(*box);
  537. }
  538. static bool is_table_track(CSS::Display display)
  539. {
  540. return display.is_table_row() || display.is_table_column();
  541. }
  542. static bool is_table_track_group(CSS::Display display)
  543. {
  544. // Unless explicitly mentioned otherwise, mentions of table-row-groups in this spec also encompass the specialized
  545. // table-header-groups and table-footer-groups.
  546. return display.is_table_row_group()
  547. || display.is_table_header_group()
  548. || display.is_table_footer_group()
  549. || display.is_table_column_group();
  550. }
  551. static bool is_proper_table_child(Node const& node)
  552. {
  553. auto const display = node.display();
  554. return is_table_track_group(display) || is_table_track(display) || display.is_table_caption();
  555. }
  556. static bool is_not_proper_table_child(Node const& node)
  557. {
  558. if (!node.has_style())
  559. return true;
  560. return !is_proper_table_child(node);
  561. }
  562. static bool is_table_row(Node const& node)
  563. {
  564. return node.display().is_table_row();
  565. }
  566. static bool is_not_table_row(Node const& node)
  567. {
  568. if (!node.has_style())
  569. return true;
  570. return !is_table_row(node);
  571. }
  572. static bool is_table_cell(Node const& node)
  573. {
  574. return node.display().is_table_cell();
  575. }
  576. static bool is_not_table_cell(Node const& node)
  577. {
  578. if (!node.has_style())
  579. return true;
  580. return !is_table_cell(node);
  581. }
  582. template<typename Matcher, typename Callback>
  583. static void for_each_sequence_of_consecutive_children_matching(NodeWithStyle& parent, Matcher matcher, Callback callback)
  584. {
  585. Vector<JS::Handle<Node>> sequence;
  586. auto sequence_is_all_ignorable_whitespace = [&]() -> bool {
  587. for (auto& node : sequence) {
  588. if (!is_ignorable_whitespace(*node))
  589. return false;
  590. }
  591. return true;
  592. };
  593. for (auto child = parent.first_child(); child; child = child->next_sibling()) {
  594. if (matcher(*child) || (!sequence.is_empty() && is_ignorable_whitespace(*child))) {
  595. sequence.append(*child);
  596. } else {
  597. if (!sequence.is_empty()) {
  598. if (!sequence_is_all_ignorable_whitespace())
  599. callback(sequence, child);
  600. sequence.clear();
  601. }
  602. }
  603. }
  604. if (!sequence.is_empty() && !sequence_is_all_ignorable_whitespace())
  605. callback(sequence, nullptr);
  606. }
  607. template<typename WrapperBoxType>
  608. static void wrap_in_anonymous(Vector<JS::Handle<Node>>& sequence, Node* nearest_sibling, CSS::Display display)
  609. {
  610. VERIFY(!sequence.is_empty());
  611. auto& parent = *sequence.first()->parent();
  612. auto computed_values = parent.computed_values().clone_inherited_values();
  613. static_cast<CSS::MutableComputedValues&>(*computed_values).set_display(display);
  614. auto wrapper = parent.heap().template allocate_without_realm<WrapperBoxType>(parent.document(), nullptr, move(computed_values));
  615. for (auto& child : sequence) {
  616. parent.remove_child(*child);
  617. wrapper->append_child(*child);
  618. }
  619. wrapper->set_children_are_inline(parent.children_are_inline());
  620. if (nearest_sibling)
  621. parent.insert_before(*wrapper, *nearest_sibling);
  622. else
  623. parent.append_child(*wrapper);
  624. }
  625. void TreeBuilder::generate_missing_child_wrappers(NodeWithStyle& root)
  626. {
  627. // An anonymous table-row box must be generated around each sequence of consecutive children of a table-root box which are not proper table child boxes.
  628. for_each_in_tree_with_inside_display<CSS::DisplayInside::Table>(root, [&](auto& parent) {
  629. for_each_sequence_of_consecutive_children_matching(parent, is_not_proper_table_child, [&](auto sequence, auto nearest_sibling) {
  630. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  631. });
  632. });
  633. // An anonymous table-row box must be generated around each sequence of consecutive children of a table-row-group box which are not table-row boxes.
  634. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableRowGroup>(root, [&](auto& parent) {
  635. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  636. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  637. });
  638. });
  639. // Unless explicitly mentioned otherwise, mentions of table-row-groups in this spec also encompass the specialized
  640. // table-header-groups and table-footer-groups.
  641. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableHeaderGroup>(root, [&](auto& parent) {
  642. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  643. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  644. });
  645. });
  646. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableFooterGroup>(root, [&](auto& parent) {
  647. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  648. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  649. });
  650. });
  651. // An anonymous table-cell box must be generated around each sequence of consecutive children of a table-row box which are not table-cell boxes. !Testcase
  652. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableRow>(root, [&](auto& parent) {
  653. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_cell, [&](auto& sequence, auto nearest_sibling) {
  654. wrap_in_anonymous<BlockContainer>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableCell });
  655. });
  656. });
  657. }
  658. Vector<JS::Handle<Box>> TreeBuilder::generate_missing_parents(NodeWithStyle& root)
  659. {
  660. Vector<JS::Handle<Box>> table_roots_to_wrap;
  661. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& parent) {
  662. // An anonymous table-row box must be generated around each sequence of consecutive table-cell boxes whose parent is not a table-row.
  663. if (is_not_table_row(parent)) {
  664. for_each_sequence_of_consecutive_children_matching(parent, is_table_cell, [&](auto& sequence, auto nearest_sibling) {
  665. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  666. });
  667. }
  668. // A table-row is misparented if its parent is neither a table-row-group nor a table-root box.
  669. if (!parent.display().is_table_inside() && !is_proper_table_child(parent)) {
  670. for_each_sequence_of_consecutive_children_matching(parent, is_table_row, [&](auto& sequence, auto nearest_sibling) {
  671. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display::from_short(parent.display().is_inline_outside() ? CSS::Display::Short::InlineTable : CSS::Display::Short::Table));
  672. });
  673. }
  674. // A table-row-group, table-column-group, or table-caption box is misparented if its parent is not a table-root box.
  675. if (!parent.display().is_table_inside() && !is_proper_table_child(parent)) {
  676. for_each_sequence_of_consecutive_children_matching(parent, is_proper_table_child, [&](auto& sequence, auto nearest_sibling) {
  677. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display::from_short(parent.display().is_inline_outside() ? CSS::Display::Short::InlineTable : CSS::Display::Short::Table));
  678. });
  679. }
  680. // An anonymous table-wrapper box must be generated around each table-root.
  681. if (parent.display().is_table_inside()) {
  682. table_roots_to_wrap.append(parent);
  683. }
  684. return TraversalDecision::Continue;
  685. });
  686. for (auto& table_box : table_roots_to_wrap) {
  687. auto* nearest_sibling = table_box->next_sibling();
  688. auto& parent = *table_box->parent();
  689. auto wrapper_computed_values = table_box->computed_values().clone_inherited_values();
  690. table_box->transfer_table_box_computed_values_to_wrapper_computed_values(*wrapper_computed_values);
  691. auto wrapper = parent.heap().allocate_without_realm<TableWrapper>(parent.document(), nullptr, move(wrapper_computed_values));
  692. parent.remove_child(*table_box);
  693. wrapper->append_child(*table_box);
  694. if (nearest_sibling)
  695. parent.insert_before(*wrapper, *nearest_sibling);
  696. else
  697. parent.append_child(*wrapper);
  698. }
  699. return table_roots_to_wrap;
  700. }
  701. template<typename Matcher, typename Callback>
  702. static void for_each_child_box_matching(Box& parent, Matcher matcher, Callback callback)
  703. {
  704. parent.for_each_child_of_type<Box>([&](Box& child_box) {
  705. if (matcher(child_box))
  706. callback(child_box);
  707. return IterationDecision::Continue;
  708. });
  709. }
  710. static void fixup_row(Box& row_box, TableGrid const& table_grid, size_t row_index)
  711. {
  712. for (size_t column_index = 0; column_index < table_grid.column_count(); ++column_index) {
  713. if (table_grid.occupancy_grid().contains({ column_index, row_index }))
  714. continue;
  715. auto computed_values = row_box.computed_values().clone_inherited_values();
  716. auto& mutable_computed_values = static_cast<CSS::MutableComputedValues&>(*computed_values);
  717. mutable_computed_values.set_display(Web::CSS::Display { CSS::DisplayInternal::TableCell });
  718. // Ensure that the cell (with zero content height) will have the same height as the row by setting vertical-align to middle.
  719. mutable_computed_values.set_vertical_align(CSS::VerticalAlign::Middle);
  720. auto cell_box = row_box.heap().template allocate_without_realm<BlockContainer>(row_box.document(), nullptr, move(computed_values));
  721. row_box.append_child(cell_box);
  722. }
  723. }
  724. void TreeBuilder::missing_cells_fixup(Vector<JS::Handle<Box>> const& table_root_boxes)
  725. {
  726. // Implements https://www.w3.org/TR/css-tables-3/#missing-cells-fixup.
  727. for (auto& table_box : table_root_boxes) {
  728. auto table_grid = TableGrid::calculate_row_column_grid(*table_box);
  729. size_t row_index = 0;
  730. for_each_child_box_matching(*table_box, TableGrid::is_table_row_group, [&](auto& row_group_box) {
  731. for_each_child_box_matching(row_group_box, is_table_row, [&](auto& row_box) {
  732. fixup_row(row_box, table_grid, row_index);
  733. ++row_index;
  734. return IterationDecision::Continue;
  735. });
  736. });
  737. for_each_child_box_matching(*table_box, is_table_row, [&](auto& row_box) {
  738. fixup_row(row_box, table_grid, row_index);
  739. ++row_index;
  740. return IterationDecision::Continue;
  741. });
  742. }
  743. }
  744. }