TreeBuilder.cpp 33 KB

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