TreeBuilder.cpp 21 KB

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