TreeBuilder.cpp 34 KB

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