TreeBuilder.cpp 32 KB

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