TreeBuilder.cpp 34 KB

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