TreeBuilder.cpp 34 KB

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