TreeBuilder.cpp 30 KB

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