TreeBuilder.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <andreas@ladybird.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/CSSKeywordValue.h>
  13. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.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/HTMLLIElement.h>
  23. #include <LibWeb/HTML/HTMLOListElement.h>
  24. #include <LibWeb/HTML/HTMLSlotElement.h>
  25. #include <LibWeb/Layout/FieldSetBox.h>
  26. #include <LibWeb/Layout/ListItemBox.h>
  27. #include <LibWeb/Layout/ListItemMarkerBox.h>
  28. #include <LibWeb/Layout/Node.h>
  29. #include <LibWeb/Layout/SVGClipBox.h>
  30. #include <LibWeb/Layout/SVGMaskBox.h>
  31. #include <LibWeb/Layout/TableGrid.h>
  32. #include <LibWeb/Layout/TableWrapper.h>
  33. #include <LibWeb/Layout/TextNode.h>
  34. #include <LibWeb/Layout/TreeBuilder.h>
  35. #include <LibWeb/Layout/Viewport.h>
  36. #include <LibWeb/SVG/SVGForeignObjectElement.h>
  37. namespace Web::Layout {
  38. TreeBuilder::TreeBuilder() = default;
  39. static bool has_inline_or_in_flow_block_children(Layout::Node const& layout_node)
  40. {
  41. for (auto child = layout_node.first_child(); child; child = child->next_sibling()) {
  42. if (child->is_inline() || child->is_in_flow())
  43. return true;
  44. }
  45. return false;
  46. }
  47. static bool has_in_flow_block_children(Layout::Node const& layout_node)
  48. {
  49. if (layout_node.children_are_inline())
  50. return false;
  51. for (auto child = layout_node.first_child(); child; child = child->next_sibling()) {
  52. if (child->is_inline())
  53. continue;
  54. if (child->is_in_flow())
  55. return true;
  56. }
  57. return false;
  58. }
  59. // The insertion_parent_for_*() functions maintain the invariant that the in-flow children of
  60. // block-level boxes must be either all block-level or all inline-level.
  61. static Layout::Node& insertion_parent_for_inline_node(Layout::NodeWithStyle& layout_parent)
  62. {
  63. auto last_child_creating_anonymous_wrapper_if_needed = [](auto& layout_parent) -> Layout::Node& {
  64. if (!layout_parent.last_child()
  65. || !layout_parent.last_child()->is_anonymous()
  66. || !layout_parent.last_child()->children_are_inline()
  67. || layout_parent.last_child()->is_generated()) {
  68. layout_parent.append_child(layout_parent.create_anonymous_wrapper());
  69. }
  70. return *layout_parent.last_child();
  71. };
  72. if (is<FieldSetBox>(layout_parent))
  73. return last_child_creating_anonymous_wrapper_if_needed(layout_parent);
  74. if (layout_parent.display().is_inline_outside() && layout_parent.display().is_flow_inside())
  75. return layout_parent;
  76. if (layout_parent.display().is_flex_inside() || layout_parent.display().is_grid_inside())
  77. return last_child_creating_anonymous_wrapper_if_needed(layout_parent);
  78. if (!has_in_flow_block_children(layout_parent) || layout_parent.children_are_inline())
  79. return layout_parent;
  80. // Parent has block-level children, insert into an anonymous wrapper block (and create it first if needed)
  81. return last_child_creating_anonymous_wrapper_if_needed(layout_parent);
  82. }
  83. static Layout::Node& insertion_parent_for_block_node(Layout::NodeWithStyle& layout_parent, Layout::Node& layout_node)
  84. {
  85. if (!has_inline_or_in_flow_block_children(layout_parent)) {
  86. // Parent block has no children, insert this block into parent.
  87. return layout_parent;
  88. }
  89. if (layout_node.is_out_of_flow()
  90. && !layout_parent.display().is_flex_inside()
  91. && !layout_parent.display().is_grid_inside()
  92. && !layout_parent.last_child()->is_generated()
  93. && layout_parent.last_child()->is_anonymous()
  94. && layout_parent.last_child()->children_are_inline()) {
  95. // Block is out-of-flow & previous sibling was wrapped in an anonymous block.
  96. // Join the previous sibling inside the anonymous block.
  97. return *layout_parent.last_child();
  98. }
  99. if (!layout_parent.children_are_inline()) {
  100. // Parent block has block-level children, insert this block into parent.
  101. return layout_parent;
  102. }
  103. if (layout_node.is_out_of_flow()) {
  104. // Block is out-of-flow, it can have inline siblings if necessary.
  105. return layout_parent;
  106. }
  107. // Parent block has inline-level children (our siblings).
  108. // First move these siblings into an anonymous wrapper block.
  109. Vector<GC::Root<Layout::Node>> children;
  110. {
  111. GC::Ptr<Layout::Node> next;
  112. for (GC::Ptr<Layout::Node> child = layout_parent.first_child(); child; child = next) {
  113. next = child->next_sibling();
  114. // NOTE: We let out-of-flow children stay in the parent, to preserve tree structure.
  115. if (child->is_out_of_flow())
  116. continue;
  117. layout_parent.remove_child(*child);
  118. children.append(*child);
  119. }
  120. }
  121. layout_parent.append_child(layout_parent.create_anonymous_wrapper());
  122. layout_parent.set_children_are_inline(false);
  123. for (auto& child : children) {
  124. layout_parent.last_child()->append_child(*child);
  125. }
  126. layout_parent.last_child()->set_children_are_inline(true);
  127. // Then it's safe to insert this block into parent.
  128. return layout_parent;
  129. }
  130. void TreeBuilder::insert_node_into_inline_or_block_ancestor(Layout::Node& node, CSS::Display display, AppendOrPrepend mode)
  131. {
  132. if (node.display().is_contents())
  133. return;
  134. if (display.is_inline_outside()) {
  135. // Inlines can be inserted into the nearest ancestor without "display: contents".
  136. auto& nearest_ancestor_without_display_contents = [&]() -> Layout::NodeWithStyle& {
  137. for (auto& ancestor : m_ancestor_stack.in_reverse()) {
  138. if (!ancestor->display().is_contents())
  139. return ancestor;
  140. }
  141. VERIFY_NOT_REACHED();
  142. }();
  143. auto& insertion_point = insertion_parent_for_inline_node(nearest_ancestor_without_display_contents);
  144. if (mode == AppendOrPrepend::Prepend)
  145. insertion_point.prepend_child(node);
  146. else
  147. insertion_point.append_child(node);
  148. insertion_point.set_children_are_inline(true);
  149. } else {
  150. // Non-inlines can't be inserted into an inline parent, so find the nearest non-inline ancestor.
  151. auto& nearest_non_inline_ancestor = [&]() -> Layout::NodeWithStyle& {
  152. for (auto& ancestor : m_ancestor_stack.in_reverse()) {
  153. if (ancestor->display().is_contents())
  154. continue;
  155. if (!ancestor->display().is_inline_outside())
  156. return ancestor;
  157. if (!ancestor->display().is_flow_inside())
  158. return ancestor;
  159. if (ancestor->dom_node() && is<SVG::SVGForeignObjectElement>(*ancestor->dom_node()))
  160. return ancestor;
  161. }
  162. VERIFY_NOT_REACHED();
  163. }();
  164. auto& insertion_point = insertion_parent_for_block_node(nearest_non_inline_ancestor, node);
  165. if (mode == AppendOrPrepend::Prepend)
  166. insertion_point.prepend_child(node);
  167. else
  168. insertion_point.append_child(node);
  169. // After inserting an in-flow block-level box into a parent, mark the parent as having non-inline children.
  170. if (!node.is_floating() && !node.is_absolutely_positioned())
  171. insertion_point.set_children_are_inline(false);
  172. }
  173. }
  174. void TreeBuilder::create_pseudo_element_if_needed(DOM::Element& element, CSS::Selector::PseudoElement::Type pseudo_element, AppendOrPrepend mode)
  175. {
  176. auto& document = element.document();
  177. auto pseudo_element_style = element.pseudo_element_computed_properties(pseudo_element);
  178. if (!pseudo_element_style)
  179. return;
  180. auto initial_quote_nesting_level = m_quote_nesting_level;
  181. auto [pseudo_element_content, final_quote_nesting_level] = pseudo_element_style->content(element, initial_quote_nesting_level);
  182. m_quote_nesting_level = final_quote_nesting_level;
  183. auto pseudo_element_display = pseudo_element_style->display();
  184. // ::before and ::after only exist if they have content. `content: normal` computes to `none` for them.
  185. // We also don't create them if they are `display: none`.
  186. if (pseudo_element_display.is_none()
  187. || pseudo_element_content.type == CSS::ContentData::Type::Normal
  188. || pseudo_element_content.type == CSS::ContentData::Type::None)
  189. return;
  190. auto pseudo_element_node = DOM::Element::create_layout_node_for_display_type(document, pseudo_element_display, *pseudo_element_style, nullptr);
  191. if (!pseudo_element_node)
  192. return;
  193. auto& style_computer = document.style_computer();
  194. // FIXME: This code actually computes style for element::marker, and shouldn't for element::pseudo::marker
  195. if (is<ListItemBox>(*pseudo_element_node)) {
  196. auto marker_style = style_computer.compute_style(element, CSS::Selector::PseudoElement::Type::Marker);
  197. auto list_item_marker = document.heap().allocate<ListItemMarkerBox>(
  198. document,
  199. pseudo_element_node->computed_values().list_style_type(),
  200. pseudo_element_node->computed_values().list_style_position(),
  201. 0,
  202. marker_style);
  203. static_cast<ListItemBox&>(*pseudo_element_node).set_marker(list_item_marker);
  204. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::Type::Marker, list_item_marker);
  205. pseudo_element_node->append_child(*list_item_marker);
  206. }
  207. auto generated_for = Node::GeneratedFor::NotGenerated;
  208. if (pseudo_element == CSS::Selector::PseudoElement::Type::Before) {
  209. generated_for = Node::GeneratedFor::PseudoBefore;
  210. } else if (pseudo_element == CSS::Selector::PseudoElement::Type::After) {
  211. generated_for = Node::GeneratedFor::PseudoAfter;
  212. } else {
  213. VERIFY_NOT_REACHED();
  214. }
  215. pseudo_element_node->set_generated_for(generated_for, element);
  216. pseudo_element_node->set_initial_quote_nesting_level(initial_quote_nesting_level);
  217. // FIXME: Handle images, and multiple values
  218. if (pseudo_element_content.type == CSS::ContentData::Type::String) {
  219. auto text = document.realm().create<DOM::Text>(document, pseudo_element_content.data);
  220. auto text_node = document.heap().allocate<Layout::TextNode>(document, *text);
  221. text_node->set_generated_for(generated_for, element);
  222. push_parent(*pseudo_element_node);
  223. insert_node_into_inline_or_block_ancestor(*text_node, text_node->display(), AppendOrPrepend::Append);
  224. pop_parent();
  225. } else {
  226. TODO();
  227. }
  228. element.set_pseudo_element_node({}, pseudo_element, pseudo_element_node);
  229. insert_node_into_inline_or_block_ancestor(*pseudo_element_node, pseudo_element_display, mode);
  230. pseudo_element_node->mutable_computed_values().set_content(pseudo_element_content);
  231. }
  232. static bool is_ignorable_whitespace(Layout::Node const& node)
  233. {
  234. if (node.is_text_node() && static_cast<TextNode const&>(node).text_for_rendering().bytes_as_string_view().is_whitespace())
  235. return true;
  236. if (node.is_anonymous() && node.is_block_container() && static_cast<BlockContainer const&>(node).children_are_inline()) {
  237. bool contains_only_white_space = true;
  238. node.for_each_in_inclusive_subtree_of_type<TextNode>([&contains_only_white_space](auto& text_node) {
  239. if (!text_node.text_for_rendering().bytes_as_string_view().is_whitespace()) {
  240. contains_only_white_space = false;
  241. return TraversalDecision::Break;
  242. }
  243. return TraversalDecision::Continue;
  244. });
  245. if (contains_only_white_space)
  246. return true;
  247. }
  248. return false;
  249. }
  250. i32 TreeBuilder::calculate_list_item_index(DOM::Node& dom_node)
  251. {
  252. if (is<HTML::HTMLLIElement>(dom_node)) {
  253. auto& li = static_cast<HTML::HTMLLIElement&>(dom_node);
  254. if (li.value() != 0)
  255. return li.value();
  256. }
  257. if (dom_node.previous_sibling() != nullptr) {
  258. DOM::Node* current = dom_node.previous_sibling();
  259. while (current != nullptr) {
  260. if (is<HTML::HTMLLIElement>(*current))
  261. return calculate_list_item_index(*current) + 1;
  262. current = current->previous_sibling();
  263. }
  264. }
  265. if (is<HTML::HTMLOListElement>(*dom_node.parent())) {
  266. auto& ol = static_cast<HTML::HTMLOListElement&>(*dom_node.parent());
  267. return ol.start();
  268. }
  269. return 1;
  270. }
  271. void TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder::Context& context)
  272. {
  273. if (dom_node.is_element()) {
  274. auto& element = static_cast<DOM::Element&>(dom_node);
  275. if (element.in_top_layer() && !context.layout_top_layer)
  276. return;
  277. }
  278. if (dom_node.is_element())
  279. dom_node.document().style_computer().push_ancestor(static_cast<DOM::Element const&>(dom_node));
  280. ScopeGuard pop_ancestor_guard = [&] {
  281. if (dom_node.is_element())
  282. dom_node.document().style_computer().pop_ancestor(static_cast<DOM::Element const&>(dom_node));
  283. };
  284. GC::Ptr<Layout::Node> layout_node;
  285. Optional<TemporaryChange<bool>> has_svg_root_change;
  286. ScopeGuard remove_stale_layout_node_guard = [&] {
  287. // If we didn't create a layout node for this DOM node,
  288. // go through the DOM tree and remove any old layout & paint nodes since they are now all stale.
  289. if (!layout_node) {
  290. dom_node.for_each_in_inclusive_subtree([&](auto& node) {
  291. node.detach_layout_node({});
  292. node.clear_paintable();
  293. if (is<DOM::Element>(node))
  294. static_cast<DOM::Element&>(node).clear_pseudo_element_nodes({});
  295. return TraversalDecision::Continue;
  296. });
  297. }
  298. };
  299. if (dom_node.is_svg_container()) {
  300. has_svg_root_change.emplace(context.has_svg_root, true);
  301. } else if (dom_node.requires_svg_container() && !context.has_svg_root) {
  302. return;
  303. }
  304. auto& document = dom_node.document();
  305. auto& style_computer = document.style_computer();
  306. GC::Ptr<CSS::ComputedProperties> style;
  307. CSS::Display display;
  308. if (is<DOM::Element>(dom_node)) {
  309. auto& element = static_cast<DOM::Element&>(dom_node);
  310. element.clear_pseudo_element_nodes({});
  311. VERIFY(!element.needs_style_update());
  312. style = element.computed_properties();
  313. element.resolve_counters(*style);
  314. display = style->display();
  315. if (display.is_none())
  316. return;
  317. // TODO: Implement changing element contents with the `content` property.
  318. if (context.layout_svg_mask_or_clip_path) {
  319. if (is<SVG::SVGMaskElement>(dom_node))
  320. layout_node = document.heap().allocate<Layout::SVGMaskBox>(document, static_cast<SVG::SVGMaskElement&>(dom_node), *style);
  321. else if (is<SVG::SVGClipPathElement>(dom_node))
  322. layout_node = document.heap().allocate<Layout::SVGClipBox>(document, static_cast<SVG::SVGClipPathElement&>(dom_node), *style);
  323. else
  324. VERIFY_NOT_REACHED();
  325. // Only layout direct uses of SVG masks/clipPaths.
  326. context.layout_svg_mask_or_clip_path = false;
  327. } else {
  328. layout_node = element.create_layout_node(*style);
  329. }
  330. } else if (is<DOM::Document>(dom_node)) {
  331. style = style_computer.create_document_style();
  332. display = style->display();
  333. layout_node = document.heap().allocate<Layout::Viewport>(static_cast<DOM::Document&>(dom_node), *style);
  334. } else if (is<DOM::Text>(dom_node)) {
  335. layout_node = document.heap().allocate<Layout::TextNode>(document, static_cast<DOM::Text&>(dom_node));
  336. display = CSS::Display(CSS::DisplayOutside::Inline, CSS::DisplayInside::Flow);
  337. }
  338. if (!layout_node)
  339. return;
  340. if (!dom_node.parent_or_shadow_host()) {
  341. m_layout_root = layout_node;
  342. } else if (layout_node->is_svg_box()) {
  343. m_ancestor_stack.last()->append_child(*layout_node);
  344. } else {
  345. insert_node_into_inline_or_block_ancestor(*layout_node, display, AppendOrPrepend::Append);
  346. }
  347. auto shadow_root = is<DOM::Element>(dom_node) ? verify_cast<DOM::Element>(dom_node).shadow_root() : nullptr;
  348. auto element_has_content_visibility_hidden = [&dom_node]() {
  349. if (is<DOM::Element>(dom_node)) {
  350. auto& element = static_cast<DOM::Element&>(dom_node);
  351. return element.computed_properties()->content_visibility() == CSS::ContentVisibility::Hidden;
  352. }
  353. return false;
  354. }();
  355. // Add node for the ::before pseudo-element.
  356. if (is<DOM::Element>(dom_node) && layout_node->can_have_children() && !element_has_content_visibility_hidden) {
  357. auto& element = static_cast<DOM::Element&>(dom_node);
  358. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  359. create_pseudo_element_if_needed(element, CSS::Selector::PseudoElement::Type::Before, AppendOrPrepend::Prepend);
  360. pop_parent();
  361. }
  362. if ((dom_node.has_children() || shadow_root) && layout_node->can_have_children() && !element_has_content_visibility_hidden) {
  363. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  364. if (shadow_root) {
  365. for (auto* node = shadow_root->first_child(); node; node = node->next_sibling()) {
  366. create_layout_tree(*node, context);
  367. }
  368. } else {
  369. // This is the same as verify_cast<DOM::ParentNode>(dom_node).for_each_child
  370. for (auto* node = verify_cast<DOM::ParentNode>(dom_node).first_child(); node; node = node->next_sibling())
  371. create_layout_tree(*node, context);
  372. }
  373. if (dom_node.is_document()) {
  374. // Elements in the top layer do not lay out normally based on their position in the document; instead they
  375. // generate boxes as if they were siblings of the root element.
  376. TemporaryChange<bool> layout_mask(context.layout_top_layer, true);
  377. for (auto const& top_layer_element : document.top_layer_elements())
  378. create_layout_tree(top_layer_element, context);
  379. }
  380. pop_parent();
  381. }
  382. if (is<ListItemBox>(*layout_node)) {
  383. auto& element = static_cast<DOM::Element&>(dom_node);
  384. auto marker_style = style_computer.compute_style(element, CSS::Selector::PseudoElement::Type::Marker);
  385. auto list_item_marker = document.heap().allocate<ListItemMarkerBox>(document, layout_node->computed_values().list_style_type(), layout_node->computed_values().list_style_position(), calculate_list_item_index(dom_node), marker_style);
  386. static_cast<ListItemBox&>(*layout_node).set_marker(list_item_marker);
  387. element.set_pseudo_element_node({}, CSS::Selector::PseudoElement::Type::Marker, list_item_marker);
  388. layout_node->append_child(*list_item_marker);
  389. }
  390. if (is<HTML::HTMLSlotElement>(dom_node)) {
  391. auto& slot_element = static_cast<HTML::HTMLSlotElement&>(dom_node);
  392. if (slot_element.computed_properties()->content_visibility() == CSS::ContentVisibility::Hidden)
  393. return;
  394. auto slottables = slot_element.assigned_nodes_internal();
  395. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  396. for (auto const& slottable : slottables)
  397. slottable.visit([&](auto& node) { create_layout_tree(node, context); });
  398. pop_parent();
  399. }
  400. if (is<SVG::SVGGraphicsElement>(dom_node)) {
  401. auto& graphics_element = static_cast<SVG::SVGGraphicsElement&>(dom_node);
  402. // Create the layout tree for the SVG mask/clip paths as a child of the masked element.
  403. // Note: This will create a new subtree for each use of the mask (so there's not a 1-to-1 mapping
  404. // from DOM node to mask layout node). Each use of a mask may be laid out differently so this
  405. // duplication is necessary.
  406. auto layout_mask_or_clip_path = [&](GC::Ptr<SVG::SVGElement const> mask_or_clip_path) {
  407. TemporaryChange<bool> layout_mask(context.layout_svg_mask_or_clip_path, true);
  408. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  409. create_layout_tree(const_cast<SVG::SVGElement&>(*mask_or_clip_path), context);
  410. pop_parent();
  411. };
  412. if (auto mask = graphics_element.mask())
  413. layout_mask_or_clip_path(mask);
  414. if (auto clip_path = graphics_element.clip_path())
  415. layout_mask_or_clip_path(clip_path);
  416. }
  417. auto is_button_layout = [&] {
  418. if (dom_node.is_html_button_element())
  419. return true;
  420. if (!dom_node.is_html_input_element())
  421. return false;
  422. // https://html.spec.whatwg.org/multipage/rendering.html#the-input-element-as-a-button
  423. // An input element whose type attribute is in the Submit Button, Reset Button, or Button state, when it generates a CSS box, is expected to depict a button and use button layout
  424. auto const& input_element = static_cast<HTML::HTMLInputElement const&>(dom_node);
  425. if (input_element.is_button())
  426. return true;
  427. return false;
  428. }();
  429. // https://html.spec.whatwg.org/multipage/rendering.html#button-layout
  430. // If the computed value of 'inline-size' is 'auto', then the used value is the fit-content inline size.
  431. if (is_button_layout && dom_node.layout_node()->computed_values().width().is_auto()) {
  432. auto& computed_values = verify_cast<NodeWithStyle>(*dom_node.layout_node()).mutable_computed_values();
  433. computed_values.set_width(CSS::Size::make_fit_content());
  434. }
  435. // https://html.spec.whatwg.org/multipage/rendering.html#button-layout
  436. // If the element is an input element, or if it is a button element and its computed value for
  437. // 'display' is not 'inline-grid', 'grid', 'inline-flex', or 'flex', then the element's box has
  438. // a child anonymous button content box with the following behaviors:
  439. if (is_button_layout && !display.is_grid_inside() && !display.is_flex_inside()) {
  440. auto& parent = *dom_node.layout_node();
  441. // If the box does not overflow in the vertical axis, then it is centered vertically.
  442. // FIXME: Only apply alignment when box overflows
  443. auto flex_computed_values = parent.computed_values().clone_inherited_values();
  444. auto& mutable_flex_computed_values = static_cast<CSS::MutableComputedValues&>(*flex_computed_values);
  445. mutable_flex_computed_values.set_display(CSS::Display { CSS::DisplayOutside::Block, CSS::DisplayInside::Flex });
  446. mutable_flex_computed_values.set_justify_content(CSS::JustifyContent::Center);
  447. mutable_flex_computed_values.set_flex_direction(CSS::FlexDirection::Column);
  448. mutable_flex_computed_values.set_height(CSS::Size::make_percentage(CSS::Percentage(100)));
  449. mutable_flex_computed_values.set_min_height(parent.computed_values().min_height());
  450. auto flex_wrapper = parent.heap().template allocate<BlockContainer>(parent.document(), nullptr, move(flex_computed_values));
  451. auto content_box_computed_values = parent.computed_values().clone_inherited_values();
  452. auto content_box_wrapper = parent.heap().template allocate<BlockContainer>(parent.document(), nullptr, move(content_box_computed_values));
  453. content_box_wrapper->set_children_are_inline(parent.children_are_inline());
  454. Vector<GC::Root<Node>> sequence;
  455. for (auto child = parent.first_child(); child; child = child->next_sibling()) {
  456. if (child->is_generated_for_before_pseudo_element())
  457. continue;
  458. sequence.append(*child);
  459. }
  460. for (auto& node : sequence) {
  461. parent.remove_child(*node);
  462. content_box_wrapper->append_child(*node);
  463. }
  464. flex_wrapper->append_child(*content_box_wrapper);
  465. parent.append_child(*flex_wrapper);
  466. parent.set_children_are_inline(false);
  467. }
  468. // Add nodes for the ::after pseudo-element.
  469. if (is<DOM::Element>(dom_node) && layout_node->can_have_children() && !element_has_content_visibility_hidden) {
  470. auto& element = static_cast<DOM::Element&>(dom_node);
  471. push_parent(verify_cast<NodeWithStyle>(*layout_node));
  472. create_pseudo_element_if_needed(element, CSS::Selector::PseudoElement::Type::After, AppendOrPrepend::Append);
  473. pop_parent();
  474. }
  475. }
  476. GC::Ptr<Layout::Node> TreeBuilder::build(DOM::Node& dom_node)
  477. {
  478. VERIFY(dom_node.is_document());
  479. dom_node.document().style_computer().reset_ancestor_filter();
  480. Context context;
  481. m_quote_nesting_level = 0;
  482. create_layout_tree(dom_node, context);
  483. if (auto* root = dom_node.document().layout_node())
  484. fixup_tables(*root);
  485. return move(m_layout_root);
  486. }
  487. template<CSS::DisplayInternal internal, typename Callback>
  488. void TreeBuilder::for_each_in_tree_with_internal_display(NodeWithStyle& root, Callback callback)
  489. {
  490. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& box) {
  491. auto const display = box.display();
  492. if (display.is_internal() && display.internal() == internal)
  493. callback(box);
  494. return TraversalDecision::Continue;
  495. });
  496. }
  497. template<CSS::DisplayInside inside, typename Callback>
  498. void TreeBuilder::for_each_in_tree_with_inside_display(NodeWithStyle& root, Callback callback)
  499. {
  500. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& box) {
  501. auto const display = box.display();
  502. if (display.is_outside_and_inside() && display.inside() == inside)
  503. callback(box);
  504. return TraversalDecision::Continue;
  505. });
  506. }
  507. void TreeBuilder::fixup_tables(NodeWithStyle& root)
  508. {
  509. remove_irrelevant_boxes(root);
  510. generate_missing_child_wrappers(root);
  511. auto table_root_boxes = generate_missing_parents(root);
  512. missing_cells_fixup(table_root_boxes);
  513. }
  514. void TreeBuilder::remove_irrelevant_boxes(NodeWithStyle& root)
  515. {
  516. // The following boxes are discarded as if they were display:none:
  517. Vector<GC::Root<Node>> to_remove;
  518. // Children of a table-column.
  519. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableColumn>(root, [&](Box& table_column) {
  520. table_column.for_each_child([&](auto& child) {
  521. to_remove.append(child);
  522. return IterationDecision::Continue;
  523. });
  524. });
  525. // Children of a table-column-group which are not a table-column.
  526. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableColumnGroup>(root, [&](Box& table_column_group) {
  527. table_column_group.for_each_child([&](auto& child) {
  528. if (!child.display().is_table_column())
  529. to_remove.append(child);
  530. return IterationDecision::Continue;
  531. });
  532. });
  533. // FIXME:
  534. // Anonymous inline boxes which contain only white space and are between two immediate siblings each of which is a table-non-root box.
  535. // Anonymous inline boxes which meet all of the following criteria:
  536. // - they contain only white space
  537. // - they are the first and/or last child of a tabular container
  538. // - whose immediate sibling, if any, is a table-non-root box
  539. for (auto& box : to_remove)
  540. box->parent()->remove_child(*box);
  541. }
  542. static bool is_table_track(CSS::Display display)
  543. {
  544. return display.is_table_row() || display.is_table_column();
  545. }
  546. static bool is_table_track_group(CSS::Display display)
  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. return display.is_table_row_group()
  551. || display.is_table_header_group()
  552. || display.is_table_footer_group()
  553. || display.is_table_column_group();
  554. }
  555. static bool is_proper_table_child(Node const& node)
  556. {
  557. auto const display = node.display();
  558. return is_table_track_group(display) || is_table_track(display) || display.is_table_caption();
  559. }
  560. static bool is_not_proper_table_child(Node const& node)
  561. {
  562. if (!node.has_style())
  563. return true;
  564. return !is_proper_table_child(node);
  565. }
  566. static bool is_table_row(Node const& node)
  567. {
  568. return node.display().is_table_row();
  569. }
  570. static bool is_not_table_row(Node const& node)
  571. {
  572. if (!node.has_style())
  573. return true;
  574. return !is_table_row(node);
  575. }
  576. static bool is_table_cell(Node const& node)
  577. {
  578. return node.display().is_table_cell();
  579. }
  580. static bool is_not_table_cell(Node const& node)
  581. {
  582. if (!node.has_style())
  583. return true;
  584. return !is_table_cell(node);
  585. }
  586. template<typename Matcher, typename Callback>
  587. static void for_each_sequence_of_consecutive_children_matching(NodeWithStyle& parent, Matcher matcher, Callback callback)
  588. {
  589. Vector<GC::Root<Node>> sequence;
  590. auto sequence_is_all_ignorable_whitespace = [&]() -> bool {
  591. for (auto& node : sequence) {
  592. if (!is_ignorable_whitespace(*node))
  593. return false;
  594. }
  595. return true;
  596. };
  597. for (auto child = parent.first_child(); child; child = child->next_sibling()) {
  598. if (matcher(*child) || (!sequence.is_empty() && is_ignorable_whitespace(*child))) {
  599. sequence.append(*child);
  600. } else {
  601. if (!sequence.is_empty()) {
  602. if (!sequence_is_all_ignorable_whitespace())
  603. callback(sequence, child);
  604. sequence.clear();
  605. }
  606. }
  607. }
  608. if (!sequence.is_empty() && !sequence_is_all_ignorable_whitespace())
  609. callback(sequence, nullptr);
  610. }
  611. template<typename WrapperBoxType>
  612. static void wrap_in_anonymous(Vector<GC::Root<Node>>& sequence, Node* nearest_sibling, CSS::Display display)
  613. {
  614. VERIFY(!sequence.is_empty());
  615. auto& parent = *sequence.first()->parent();
  616. auto computed_values = parent.computed_values().clone_inherited_values();
  617. static_cast<CSS::MutableComputedValues&>(*computed_values).set_display(display);
  618. auto wrapper = parent.heap().template allocate<WrapperBoxType>(parent.document(), nullptr, move(computed_values));
  619. for (auto& child : sequence) {
  620. parent.remove_child(*child);
  621. wrapper->append_child(*child);
  622. }
  623. wrapper->set_children_are_inline(parent.children_are_inline());
  624. if (nearest_sibling)
  625. parent.insert_before(*wrapper, *nearest_sibling);
  626. else
  627. parent.append_child(*wrapper);
  628. }
  629. void TreeBuilder::generate_missing_child_wrappers(NodeWithStyle& root)
  630. {
  631. // 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.
  632. for_each_in_tree_with_inside_display<CSS::DisplayInside::Table>(root, [&](auto& parent) {
  633. for_each_sequence_of_consecutive_children_matching(parent, is_not_proper_table_child, [&](auto sequence, auto nearest_sibling) {
  634. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  635. });
  636. });
  637. // 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.
  638. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableRowGroup>(root, [&](auto& parent) {
  639. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  640. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  641. });
  642. });
  643. // Unless explicitly mentioned otherwise, mentions of table-row-groups in this spec also encompass the specialized
  644. // table-header-groups and table-footer-groups.
  645. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableHeaderGroup>(root, [&](auto& parent) {
  646. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  647. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  648. });
  649. });
  650. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableFooterGroup>(root, [&](auto& parent) {
  651. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_row, [&](auto& sequence, auto nearest_sibling) {
  652. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  653. });
  654. });
  655. // 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
  656. for_each_in_tree_with_internal_display<CSS::DisplayInternal::TableRow>(root, [&](auto& parent) {
  657. for_each_sequence_of_consecutive_children_matching(parent, is_not_table_cell, [&](auto& sequence, auto nearest_sibling) {
  658. wrap_in_anonymous<BlockContainer>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableCell });
  659. });
  660. });
  661. }
  662. Vector<GC::Root<Box>> TreeBuilder::generate_missing_parents(NodeWithStyle& root)
  663. {
  664. Vector<GC::Root<Box>> table_roots_to_wrap;
  665. root.for_each_in_inclusive_subtree_of_type<Box>([&](auto& parent) {
  666. // An anonymous table-row box must be generated around each sequence of consecutive table-cell boxes whose parent is not a table-row.
  667. if (is_not_table_row(parent)) {
  668. for_each_sequence_of_consecutive_children_matching(parent, is_table_cell, [&](auto& sequence, auto nearest_sibling) {
  669. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display { CSS::DisplayInternal::TableRow });
  670. });
  671. }
  672. // A table-row is misparented if its parent is neither a table-row-group nor a table-root box.
  673. if (!parent.display().is_table_inside() && !is_proper_table_child(parent)) {
  674. for_each_sequence_of_consecutive_children_matching(parent, is_table_row, [&](auto& sequence, auto nearest_sibling) {
  675. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display::from_short(parent.display().is_inline_outside() ? CSS::Display::Short::InlineTable : CSS::Display::Short::Table));
  676. });
  677. }
  678. // A table-row-group, table-column-group, or table-caption box is misparented if its parent is not a table-root box.
  679. if (!parent.display().is_table_inside() && !is_proper_table_child(parent)) {
  680. for_each_sequence_of_consecutive_children_matching(parent, is_proper_table_child, [&](auto& sequence, auto nearest_sibling) {
  681. wrap_in_anonymous<Box>(sequence, nearest_sibling, CSS::Display::from_short(parent.display().is_inline_outside() ? CSS::Display::Short::InlineTable : CSS::Display::Short::Table));
  682. });
  683. }
  684. // An anonymous table-wrapper box must be generated around each table-root.
  685. if (parent.display().is_table_inside()) {
  686. table_roots_to_wrap.append(parent);
  687. }
  688. return TraversalDecision::Continue;
  689. });
  690. for (auto& table_box : table_roots_to_wrap) {
  691. auto* nearest_sibling = table_box->next_sibling();
  692. auto& parent = *table_box->parent();
  693. auto wrapper_computed_values = table_box->computed_values().clone_inherited_values();
  694. table_box->transfer_table_box_computed_values_to_wrapper_computed_values(*wrapper_computed_values);
  695. auto wrapper = parent.heap().allocate<TableWrapper>(parent.document(), nullptr, move(wrapper_computed_values));
  696. parent.remove_child(*table_box);
  697. wrapper->append_child(*table_box);
  698. if (nearest_sibling)
  699. parent.insert_before(*wrapper, *nearest_sibling);
  700. else
  701. parent.append_child(*wrapper);
  702. }
  703. return table_roots_to_wrap;
  704. }
  705. template<typename Matcher, typename Callback>
  706. static void for_each_child_box_matching(Box& parent, Matcher matcher, Callback callback)
  707. {
  708. parent.for_each_child_of_type<Box>([&](Box& child_box) {
  709. if (matcher(child_box))
  710. callback(child_box);
  711. return IterationDecision::Continue;
  712. });
  713. }
  714. static void fixup_row(Box& row_box, TableGrid const& table_grid, size_t row_index)
  715. {
  716. for (size_t column_index = 0; column_index < table_grid.column_count(); ++column_index) {
  717. if (table_grid.occupancy_grid().contains({ column_index, row_index }))
  718. continue;
  719. auto computed_values = row_box.computed_values().clone_inherited_values();
  720. auto& mutable_computed_values = static_cast<CSS::MutableComputedValues&>(*computed_values);
  721. mutable_computed_values.set_display(Web::CSS::Display { CSS::DisplayInternal::TableCell });
  722. // Ensure that the cell (with zero content height) will have the same height as the row by setting vertical-align to middle.
  723. mutable_computed_values.set_vertical_align(CSS::VerticalAlign::Middle);
  724. auto cell_box = row_box.heap().template allocate<BlockContainer>(row_box.document(), nullptr, move(computed_values));
  725. row_box.append_child(cell_box);
  726. }
  727. }
  728. void TreeBuilder::missing_cells_fixup(Vector<GC::Root<Box>> const& table_root_boxes)
  729. {
  730. // Implements https://www.w3.org/TR/css-tables-3/#missing-cells-fixup.
  731. for (auto& table_box : table_root_boxes) {
  732. auto table_grid = TableGrid::calculate_row_column_grid(*table_box);
  733. size_t row_index = 0;
  734. for_each_child_box_matching(*table_box, TableGrid::is_table_row_group, [&](auto& row_group_box) {
  735. for_each_child_box_matching(row_group_box, is_table_row, [&](auto& row_box) {
  736. fixup_row(row_box, table_grid, row_index);
  737. ++row_index;
  738. return IterationDecision::Continue;
  739. });
  740. });
  741. for_each_child_box_matching(*table_box, is_table_row, [&](auto& row_box) {
  742. fixup_row(row_box, table_grid, row_index);
  743. ++row_index;
  744. return IterationDecision::Continue;
  745. });
  746. }
  747. }
  748. }