TreeBuilder.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Optional.h>
  8. #include <AK/TemporaryChange.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/DOM/Element.h>
  11. #include <LibWeb/DOM/ParentNode.h>
  12. #include <LibWeb/DOM/ShadowRoot.h>
  13. #include <LibWeb/Dump.h>
  14. #include <LibWeb/Layout/InitialContainingBlock.h>
  15. #include <LibWeb/Layout/ListItemBox.h>
  16. #include <LibWeb/Layout/ListItemMarkerBox.h>
  17. #include <LibWeb/Layout/Node.h>
  18. #include <LibWeb/Layout/TableBox.h>
  19. #include <LibWeb/Layout/TableCellBox.h>
  20. #include <LibWeb/Layout/TableRowBox.h>
  21. #include <LibWeb/Layout/TextNode.h>
  22. #include <LibWeb/Layout/TreeBuilder.h>
  23. namespace Web::Layout {
  24. TreeBuilder::TreeBuilder() = default;
  25. static bool has_inline_or_in_flow_block_children(Layout::Node const& layout_node)
  26. {
  27. for (auto const* child = layout_node.first_child(); child; child = child->next_sibling()) {
  28. if (child->is_inline())
  29. return true;
  30. if (!child->is_floating() && !child->is_absolutely_positioned())
  31. return true;
  32. }
  33. return false;
  34. }
  35. static bool has_in_flow_block_children(Layout::Node const& layout_node)
  36. {
  37. if (layout_node.children_are_inline())
  38. return false;
  39. for (auto const* child = layout_node.first_child(); child; child = child->next_sibling()) {
  40. if (child->is_inline())
  41. continue;
  42. if (!child->is_floating() && !child->is_absolutely_positioned())
  43. return true;
  44. }
  45. return false;
  46. }
  47. // The insertion_parent_for_*() functions maintain the invariant that the in-flow children of
  48. // block-level boxes must be either all block-level or all inline-level.
  49. static Layout::Node& insertion_parent_for_inline_node(Layout::NodeWithStyle& layout_parent)
  50. {
  51. if (layout_parent.is_inline() && !layout_parent.is_inline_block())
  52. return layout_parent;
  53. if (layout_parent.computed_values().display().is_flex_inside()) {
  54. layout_parent.append_child(layout_parent.create_anonymous_wrapper());
  55. }
  56. if (!has_in_flow_block_children(layout_parent) || layout_parent.children_are_inline())
  57. return layout_parent;
  58. // Parent has block-level children, insert into an anonymous wrapper block (and create it first if needed)
  59. if (!layout_parent.last_child()->is_anonymous() || !layout_parent.last_child()->children_are_inline()) {
  60. layout_parent.append_child(layout_parent.create_anonymous_wrapper());
  61. }
  62. return *layout_parent.last_child();
  63. }
  64. static Layout::Node& insertion_parent_for_block_node(Layout::Node& layout_parent, Layout::Node& layout_node)
  65. {
  66. if (!has_inline_or_in_flow_block_children(layout_parent)) {
  67. // Parent block has no children, insert this block into parent.
  68. return layout_parent;
  69. }
  70. if (!layout_parent.children_are_inline()) {
  71. // Parent block has block-level children, insert this block into parent.
  72. return layout_parent;
  73. }
  74. if (layout_node.is_floating() || layout_node.is_absolutely_positioned()) {
  75. // Block is out-of-flow, it can have inline siblings if necessary.
  76. return layout_parent;
  77. }
  78. // Parent block has inline-level children (our siblings).
  79. // First move these siblings into an anonymous wrapper block.
  80. NonnullRefPtrVector<Layout::Node> children;
  81. while (RefPtr<Layout::Node> child = layout_parent.first_child()) {
  82. layout_parent.remove_child(*child);
  83. children.append(child.release_nonnull());
  84. }
  85. layout_parent.append_child(adopt_ref(*new BlockContainer(layout_node.document(), nullptr, layout_parent.computed_values().clone_inherited_values())));
  86. layout_parent.set_children_are_inline(false);
  87. for (auto& child : children) {
  88. layout_parent.last_child()->append_child(child);
  89. }
  90. layout_parent.last_child()->set_children_are_inline(true);
  91. // Then it's safe to insert this block into parent.
  92. return layout_parent;
  93. }
  94. void TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder::Context& context)
  95. {
  96. // If the parent doesn't have a layout node, we don't need one either.
  97. if (dom_node.parent_or_shadow_host() && !dom_node.parent_or_shadow_host()->layout_node())
  98. return;
  99. Optional<TemporaryChange<bool>> has_svg_root_change;
  100. if (dom_node.is_svg_container()) {
  101. has_svg_root_change.emplace(context.has_svg_root, true);
  102. } else if (dom_node.requires_svg_container() && !context.has_svg_root) {
  103. return;
  104. }
  105. auto& document = dom_node.document();
  106. auto& style_computer = document.style_computer();
  107. RefPtr<Layout::Node> layout_node;
  108. RefPtr<CSS::StyleProperties> style;
  109. if (is<DOM::Element>(dom_node)) {
  110. auto& element = static_cast<DOM::Element&>(dom_node);
  111. element.clear_pseudo_element_nodes({});
  112. VERIFY(!element.needs_style_update());
  113. style = element.computed_css_values();
  114. if (style->display().is_none())
  115. return;
  116. layout_node = element.create_layout_node(*style);
  117. } else if (is<DOM::Document>(dom_node)) {
  118. style = style_computer.create_document_style();
  119. layout_node = adopt_ref(*new Layout::InitialContainingBlock(static_cast<DOM::Document&>(dom_node), *style));
  120. } else if (is<DOM::Text>(dom_node)) {
  121. layout_node = adopt_ref(*new Layout::TextNode(document, static_cast<DOM::Text&>(dom_node)));
  122. } else if (is<DOM::ShadowRoot>(dom_node)) {
  123. layout_node = adopt_ref(*new Layout::BlockContainer(document, &static_cast<DOM::ShadowRoot&>(dom_node), CSS::ComputedValues {}));
  124. }
  125. if (!layout_node)
  126. return;
  127. auto insert_node_into_inline_or_block_ancestor = [this](auto& node, bool prepend = false) {
  128. if (node->is_inline() && !(node->is_inline_block() && m_parent_stack.last()->computed_values().display().is_flex_inside())) {
  129. // Inlines can be inserted into the nearest ancestor.
  130. auto& insertion_point = insertion_parent_for_inline_node(*m_parent_stack.last());
  131. if (prepend)
  132. insertion_point.prepend_child(*node);
  133. else
  134. insertion_point.append_child(*node);
  135. insertion_point.set_children_are_inline(true);
  136. } else {
  137. // Non-inlines can't be inserted into an inline parent, so find the nearest non-inline ancestor.
  138. auto& nearest_non_inline_ancestor = [&]() -> Layout::Node& {
  139. for (ssize_t i = m_parent_stack.size() - 1; i >= 0; --i) {
  140. if (!m_parent_stack[i]->is_inline() || m_parent_stack[i]->is_inline_block())
  141. return *m_parent_stack[i];
  142. }
  143. VERIFY_NOT_REACHED();
  144. }();
  145. auto& insertion_point = insertion_parent_for_block_node(nearest_non_inline_ancestor, *node);
  146. if (prepend)
  147. insertion_point.prepend_child(*node);
  148. else
  149. insertion_point.append_child(*node);
  150. insertion_point.set_children_are_inline(false);
  151. }
  152. };
  153. if (!dom_node.parent_or_shadow_host()) {
  154. m_layout_root = layout_node;
  155. } else if (layout_node->is_svg_box()) {
  156. m_parent_stack.last()->append_child(*layout_node);
  157. } else {
  158. insert_node_into_inline_or_block_ancestor(layout_node);
  159. }
  160. if (layout_node->has_style() && style)
  161. static_cast<Layout::NodeWithStyle&>(*layout_node).did_insert_into_layout_tree(*style);
  162. auto* shadow_root = is<DOM::Element>(dom_node) ? verify_cast<DOM::Element>(dom_node).shadow_root() : nullptr;
  163. if ((dom_node.has_children() || shadow_root) && layout_node->can_have_children()) {
  164. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  165. if (shadow_root)
  166. create_layout_tree(*shadow_root, context);
  167. verify_cast<DOM::ParentNode>(dom_node).for_each_child([&](auto& dom_child) {
  168. create_layout_tree(dom_child, context);
  169. });
  170. pop_parent();
  171. }
  172. // Add nodes for the ::before and ::after pseudo-elements.
  173. if (is<DOM::Element>(dom_node)) {
  174. auto& element = static_cast<DOM::Element&>(dom_node);
  175. auto create_pseudo_element_if_needed = [&](CSS::Selector::PseudoElement pseudo_element) -> RefPtr<Node> {
  176. auto pseudo_element_style = style_computer.compute_style(element, pseudo_element);
  177. auto pseudo_element_content = pseudo_element_style->content();
  178. auto pseudo_element_display = pseudo_element_style->display();
  179. // ::before and ::after only exist if they have content. `content: normal` computes to `none` for them.
  180. // We also don't create them if they are `display: none`.
  181. if (pseudo_element_display.is_none()
  182. || pseudo_element_content.type == CSS::ContentData::Type::Normal
  183. || pseudo_element_content.type == CSS::ContentData::Type::None)
  184. return nullptr;
  185. if (auto pseudo_element_node = DOM::Element::create_layout_node_for_display_type(document, pseudo_element_display, move(pseudo_element_style), nullptr)) {
  186. // FIXME: Handle images, and multiple values
  187. if (pseudo_element_content.type == CSS::ContentData::Type::String) {
  188. auto text = adopt_ref(*new DOM::Text(document, pseudo_element_content.data));
  189. auto text_node = adopt_ref(*new TextNode(document, text));
  190. push_parent(verify_cast<NodeWithStyle>(*pseudo_element_node));
  191. insert_node_into_inline_or_block_ancestor(text_node);
  192. pop_parent();
  193. } else {
  194. TODO();
  195. }
  196. return pseudo_element_node;
  197. }
  198. return nullptr;
  199. };
  200. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  201. if (auto before_node = create_pseudo_element_if_needed(CSS::Selector::PseudoElement::Before)) {
  202. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::Before, before_node);
  203. insert_node_into_inline_or_block_ancestor(before_node, true);
  204. }
  205. if (auto after_node = create_pseudo_element_if_needed(CSS::Selector::PseudoElement::After)) {
  206. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::After, after_node);
  207. insert_node_into_inline_or_block_ancestor(after_node);
  208. }
  209. pop_parent();
  210. }
  211. if (is<ListItemBox>(*layout_node)) {
  212. auto& element = static_cast<DOM::Element&>(dom_node);
  213. int child_index = layout_node->parent()->index_of_child<ListItemBox>(*layout_node).value();
  214. auto marker_style = style_computer.compute_style(element, CSS::Selector::PseudoElement::Marker);
  215. auto list_item_marker = adopt_ref(*new ListItemMarkerBox(document, layout_node->computed_values().list_style_type(), child_index + 1, *marker_style));
  216. if (layout_node->first_child())
  217. list_item_marker->set_inline(layout_node->first_child()->is_inline());
  218. static_cast<ListItemBox&>(*layout_node).set_marker(list_item_marker);
  219. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::Marker, list_item_marker);
  220. layout_node->append_child(move(list_item_marker));
  221. }
  222. }
  223. RefPtr<Node> TreeBuilder::build(DOM::Node& dom_node)
  224. {
  225. VERIFY(dom_node.is_document());
  226. Context context;
  227. create_layout_tree(dom_node, context);
  228. if (auto* root = dom_node.document().layout_node())
  229. fixup_tables(*root);
  230. return move(m_layout_root);
  231. }
  232. template<CSS::Display::Internal internal, typename Callback>
  233. void TreeBuilder::for_each_in_tree_with_internal_display(NodeWithStyle& root, Callback callback)
  234. {
  235. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& box) {
  236. auto const& display = box.computed_values().display();
  237. if (display.is_internal() && display.internal() == internal)
  238. callback(box);
  239. return IterationDecision::Continue;
  240. });
  241. }
  242. template<CSS::Display::Inside inside, typename Callback>
  243. void TreeBuilder::for_each_in_tree_with_inside_display(NodeWithStyle& root, Callback callback)
  244. {
  245. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& box) {
  246. auto const& display = box.computed_values().display();
  247. if (display.it_outside_and_inside() && display.inside() == inside)
  248. callback(box);
  249. return IterationDecision::Continue;
  250. });
  251. }
  252. void TreeBuilder::fixup_tables(NodeWithStyle& root)
  253. {
  254. remove_irrelevant_boxes(root);
  255. generate_missing_child_wrappers(root);
  256. generate_missing_parents(root);
  257. }
  258. void TreeBuilder::remove_irrelevant_boxes(NodeWithStyle& root)
  259. {
  260. // The following boxes are discarded as if they were display:none:
  261. NonnullRefPtrVector<Node> to_remove;
  262. // Children of a table-column.
  263. for_each_in_tree_with_internal_display<CSS::Display::Internal::TableColumn>(root, [&](Box& table_column) {
  264. table_column.for_each_child([&](auto& child) {
  265. to_remove.append(child);
  266. });
  267. });
  268. // Children of a table-column-group which are not a table-column.
  269. for_each_in_tree_with_internal_display<CSS::Display::Internal::TableColumnGroup>(root, [&](Box& table_column_group) {
  270. table_column_group.for_each_child([&](auto& child) {
  271. if (child.computed_values().display().is_table_column())
  272. to_remove.append(child);
  273. });
  274. });
  275. // FIXME:
  276. // Anonymous inline boxes which contain only white space and are between two immediate siblings each of which is a table-non-root box.
  277. // Anonymous inline boxes which meet all of the following criteria:
  278. // - they contain only white space
  279. // - they are the first and/or last child of a tabular container
  280. // - whose immediate sibling, if any, is a table-non-root box
  281. for (auto& box : to_remove)
  282. box.parent()->remove_child(box);
  283. }
  284. static bool is_table_track(CSS::Display display)
  285. {
  286. return display.is_table_row() || display.is_table_column();
  287. }
  288. static bool is_table_track_group(CSS::Display display)
  289. {
  290. // Unless explicitly mentioned otherwise, mentions of table-row-groups in this spec also encompass the specialized
  291. // table-header-groups and table-footer-groups.
  292. return display.is_table_row_group()
  293. || display.is_table_header_group()
  294. || display.is_table_footer_group()
  295. || display.is_table_column_group();
  296. }
  297. static bool is_not_proper_table_child(const Node& node)
  298. {
  299. if (!node.has_style())
  300. return true;
  301. auto display = node.computed_values().display();
  302. return !is_table_track_group(display) && !is_table_track(display) && !display.is_table_caption();
  303. }
  304. static bool is_not_table_row(const Node& node)
  305. {
  306. if (!node.has_style())
  307. return true;
  308. auto display = node.computed_values().display();
  309. return !display.is_table_row();
  310. }
  311. static bool is_not_table_cell(const Node& node)
  312. {
  313. if (!node.has_style())
  314. return true;
  315. auto display = node.computed_values().display();
  316. return !display.is_table_cell();
  317. }
  318. static bool is_ignorable_whitespace(Layout::Node const& node)
  319. {
  320. if (node.is_text_node() && static_cast<TextNode const&>(node).text_for_rendering().is_whitespace())
  321. return true;
  322. if (node.is_anonymous() && node.is_block_container() && static_cast<BlockContainer const&>(node).children_are_inline()) {
  323. bool contains_only_white_space = true;
  324. node.for_each_in_inclusive_subtree_of_type<TextNode>([&contains_only_white_space](auto& text_node) {
  325. if (!text_node.text_for_rendering().is_whitespace()) {
  326. contains_only_white_space = false;
  327. return IterationDecision::Break;
  328. }
  329. return IterationDecision::Continue;
  330. });
  331. if (contains_only_white_space)
  332. return true;
  333. }
  334. return false;
  335. }
  336. template<typename Matcher, typename Callback>
  337. static void for_each_sequence_of_consecutive_children_matching(NodeWithStyle& parent, Matcher matcher, Callback callback)
  338. {
  339. NonnullRefPtrVector<Node> sequence;
  340. auto sequence_is_all_ignorable_whitespace = [&]() -> bool {
  341. for (auto& node : sequence) {
  342. if (!is_ignorable_whitespace(node))
  343. return false;
  344. }
  345. return true;
  346. };
  347. Node* next_sibling = nullptr;
  348. for (auto* child = parent.first_child(); child; child = next_sibling) {
  349. next_sibling = child->next_sibling();
  350. if (matcher(*child)) {
  351. sequence.append(*child);
  352. } else {
  353. if (!sequence.is_empty()) {
  354. if (!sequence_is_all_ignorable_whitespace())
  355. callback(sequence, next_sibling);
  356. sequence.clear();
  357. }
  358. }
  359. }
  360. if (sequence.is_empty() && !sequence_is_all_ignorable_whitespace())
  361. callback(sequence, nullptr);
  362. }
  363. template<typename WrapperBoxType>
  364. static void wrap_in_anonymous(NonnullRefPtrVector<Node>& sequence, Node* nearest_sibling)
  365. {
  366. VERIFY(!sequence.is_empty());
  367. auto& parent = *sequence.first().parent();
  368. auto computed_values = parent.computed_values().clone_inherited_values();
  369. static_cast<CSS::MutableComputedValues&>(computed_values).set_display(WrapperBoxType::static_display());
  370. auto wrapper = adopt_ref(*new WrapperBoxType(parent.document(), nullptr, move(computed_values)));
  371. for (auto& child : sequence) {
  372. parent.remove_child(child);
  373. wrapper->append_child(child);
  374. }
  375. if (nearest_sibling)
  376. parent.insert_before(move(wrapper), *nearest_sibling);
  377. else
  378. parent.append_child(move(wrapper));
  379. }
  380. void TreeBuilder::generate_missing_child_wrappers(NodeWithStyle& root)
  381. {
  382. // 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.
  383. for_each_in_tree_with_inside_display<CSS::Display::Inside::Table>(root, [&](auto& parent) {
  384. for_each_sequence_of_consecutive_children_matching(parent, is_not_proper_table_child, [&](auto sequence, auto nearest_sibling) {
  385. wrap_in_anonymous<TableRowBox>(sequence, nearest_sibling);
  386. });
  387. });
  388. // 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.
  389. for_each_in_tree_with_internal_display<CSS::Display::Internal::TableRowGroup>(root, [&](auto& parent) {
  390. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  391. wrap_in_anonymous<TableRowBox>(sequence, nearest_sibling);
  392. });
  393. });
  394. // Unless explicitly mentioned otherwise, mentions of table-row-groups in this spec also encompass the specialized
  395. // table-header-groups and table-footer-groups.
  396. for_each_in_tree_with_internal_display<CSS::Display::Internal::TableHeaderGroup>(root, [&](auto& parent) {
  397. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  398. wrap_in_anonymous<TableRowBox>(sequence, nearest_sibling);
  399. });
  400. });
  401. for_each_in_tree_with_internal_display<CSS::Display::Internal::TableFooterGroup>(root, [&](auto& parent) {
  402. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  403. wrap_in_anonymous<TableRowBox>(sequence, nearest_sibling);
  404. });
  405. });
  406. // 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
  407. for_each_in_tree_with_internal_display<CSS::Display::Internal::TableRow>(root, [&](auto& parent) {
  408. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_cell, [&](auto& sequence, auto nearest_sibling) {
  409. wrap_in_anonymous<TableCellBox>(sequence, nearest_sibling);
  410. });
  411. });
  412. }
  413. void TreeBuilder::generate_missing_parents(NodeWithStyle&)
  414. {
  415. // FIXME: Implement.
  416. }
  417. }