TreeBuilder.cpp 19 KB

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