BlockFormattingContext.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/TemporaryChange.h>
  7. #include <LibWeb/CSS/Length.h>
  8. #include <LibWeb/DOM/Node.h>
  9. #include <LibWeb/Dump.h>
  10. #include <LibWeb/HTML/BrowsingContext.h>
  11. #include <LibWeb/Layout/BlockContainer.h>
  12. #include <LibWeb/Layout/BlockFormattingContext.h>
  13. #include <LibWeb/Layout/Box.h>
  14. #include <LibWeb/Layout/InlineFormattingContext.h>
  15. #include <LibWeb/Layout/LineBuilder.h>
  16. #include <LibWeb/Layout/ListItemBox.h>
  17. #include <LibWeb/Layout/ListItemMarkerBox.h>
  18. #include <LibWeb/Layout/ReplacedBox.h>
  19. #include <LibWeb/Layout/TableBox.h>
  20. #include <LibWeb/Layout/TableWrapper.h>
  21. #include <LibWeb/Layout/Viewport.h>
  22. namespace Web::Layout {
  23. BlockFormattingContext::BlockFormattingContext(LayoutState& state, BlockContainer const& root, FormattingContext* parent)
  24. : FormattingContext(Type::Block, state, root, parent)
  25. {
  26. }
  27. BlockFormattingContext::~BlockFormattingContext()
  28. {
  29. if (!m_was_notified_after_parent_dimensioned_my_root_box) {
  30. // HACK: The parent formatting context never notified us after assigning dimensions to our root box.
  31. // Pretend that it did anyway, to make sure absolutely positioned children get laid out.
  32. // FIXME: Get rid of this hack once parent contexts behave properly.
  33. parent_context_did_dimension_child_root_box();
  34. }
  35. }
  36. CSSPixels BlockFormattingContext::automatic_content_width() const
  37. {
  38. return greatest_child_width(root());
  39. }
  40. CSSPixels BlockFormattingContext::automatic_content_height() const
  41. {
  42. return compute_auto_height_for_block_formatting_context_root(root());
  43. }
  44. static bool margins_collapse_through(Box const& box, LayoutState& state)
  45. {
  46. // FIXME: A box's own margins collapse if the 'min-height' property is zero, and it has neither top or bottom borders
  47. // nor top or bottom padding, and it has a 'height' of either 0 or 'auto', and it does not contain a line box, and
  48. // all of its in-flow children's margins (if any) collapse.
  49. // https://www.w3.org/TR/CSS22/box.html#collapsing-margins
  50. return state.get(box).border_box_height() == 0;
  51. }
  52. void BlockFormattingContext::run(Box const&, LayoutMode layout_mode, AvailableSpace const& available_space)
  53. {
  54. if (is<Viewport>(root())) {
  55. layout_viewport(layout_mode, available_space);
  56. return;
  57. }
  58. if (root().children_are_inline())
  59. layout_inline_children(root(), layout_mode, available_space);
  60. else
  61. layout_block_level_children(root(), layout_mode, available_space);
  62. // Assign collapsed margin left after children layout of formatting context to the last child box
  63. if (m_margin_state.current_collapsed_margin() != 0) {
  64. for (auto* child_box = root().last_child_of_type<Box>(); child_box; child_box = child_box->previous_sibling_of_type<Box>()) {
  65. if (child_box->is_absolutely_positioned() || child_box->is_floating())
  66. continue;
  67. if (margins_collapse_through(*child_box, m_state))
  68. continue;
  69. m_state.get_mutable(*child_box).margin_bottom = m_margin_state.current_collapsed_margin().value();
  70. break;
  71. }
  72. }
  73. }
  74. void BlockFormattingContext::parent_context_did_dimension_child_root_box()
  75. {
  76. m_was_notified_after_parent_dimensioned_my_root_box = true;
  77. // Left-side floats: offset_from_edge is from left edge (0) to left content edge of floating_box.
  78. for (auto& floating_box : m_left_floats.all_boxes) {
  79. auto& box_state = m_state.get_mutable(floating_box->box);
  80. box_state.set_content_x(floating_box->offset_from_edge.value());
  81. }
  82. // Right-side floats: offset_from_edge is from right edge (float_containing_block_width) to the left content edge of floating_box.
  83. for (auto& floating_box : m_right_floats.all_boxes) {
  84. auto float_containing_block_width = containing_block_width_for(floating_box->box);
  85. auto& box_state = m_state.get_mutable(floating_box->box);
  86. box_state.set_content_x((float_containing_block_width - floating_box->offset_from_edge).value());
  87. }
  88. // We can also layout absolutely positioned boxes within this BFC.
  89. for (auto& box : m_absolutely_positioned_boxes) {
  90. auto& cb_state = m_state.get(*box->containing_block());
  91. auto available_width = AvailableSize::make_definite(cb_state.content_width() + cb_state.padding_left + cb_state.padding_right);
  92. auto available_height = AvailableSize::make_definite(cb_state.content_height() + cb_state.padding_top + cb_state.padding_bottom);
  93. layout_absolutely_positioned_element(box, AvailableSpace(available_width, available_height));
  94. }
  95. }
  96. void BlockFormattingContext::compute_width(Box const& box, AvailableSpace const& available_space, LayoutMode)
  97. {
  98. if (box.is_absolutely_positioned()) {
  99. compute_width_for_absolutely_positioned_element(box, available_space);
  100. return;
  101. }
  102. if (is<ReplacedBox>(box)) {
  103. // FIXME: This should not be done *by* ReplacedBox
  104. auto& replaced = verify_cast<ReplacedBox>(box);
  105. // FIXME: This const_cast is gross.
  106. const_cast<ReplacedBox&>(replaced).prepare_for_replaced_layout();
  107. compute_width_for_block_level_replaced_element_in_normal_flow(replaced, available_space);
  108. // NOTE: We don't return here.
  109. }
  110. if (box.is_floating()) {
  111. compute_width_for_floating_box(box, available_space);
  112. return;
  113. }
  114. auto const& computed_values = box.computed_values();
  115. auto width_of_containing_block = available_space.width.to_px();
  116. auto width_of_containing_block_as_length_for_resolve = available_space.width.is_definite() ? CSS::Length::make_px(width_of_containing_block) : CSS::Length::make_px(0);
  117. auto zero_value = CSS::Length::make_px(0);
  118. auto margin_left = CSS::Length::make_auto();
  119. auto margin_right = CSS::Length::make_auto();
  120. auto const padding_left = computed_values.padding().left().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  121. auto const padding_right = computed_values.padding().right().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  122. auto& box_state = m_state.get_mutable(box);
  123. box_state.border_left = computed_values.border_left().width;
  124. box_state.border_right = computed_values.border_right().width;
  125. box_state.padding_left = padding_left.to_px(box);
  126. box_state.padding_right = padding_right.to_px(box);
  127. // NOTE: If we are calculating the min-content or max-content width of this box,
  128. // and the width should be treated as auto, then we can simply return here,
  129. // as the preferred width and min/max constraints are irrelevant for intrinsic sizing.
  130. if (box_state.width_constraint != SizeConstraint::None)
  131. return;
  132. auto try_compute_width = [&](auto const& a_width) {
  133. CSS::Length width = a_width;
  134. margin_left = computed_values.margin().left().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  135. margin_right = computed_values.margin().right().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  136. CSSPixels total_px = computed_values.border_left().width + computed_values.border_right().width;
  137. for (auto& value : { margin_left, padding_left, width, padding_right, margin_right }) {
  138. total_px += value.to_px(box);
  139. }
  140. if (!box.is_inline()) {
  141. // 10.3.3 Block-level, non-replaced elements in normal flow
  142. // If 'width' is not 'auto' and 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' (plus any of 'margin-left' or 'margin-right' that are not 'auto') is larger than the width of the containing block, then any 'auto' values for 'margin-left' or 'margin-right' are, for the following rules, treated as zero.
  143. if (width.is_auto() && total_px > width_of_containing_block) {
  144. if (margin_left.is_auto())
  145. margin_left = zero_value;
  146. if (margin_right.is_auto())
  147. margin_right = zero_value;
  148. }
  149. // 10.3.3 cont'd.
  150. auto underflow_px = width_of_containing_block - total_px;
  151. if (!isfinite(underflow_px.value()))
  152. underflow_px = 0;
  153. if (width.is_auto()) {
  154. if (margin_left.is_auto())
  155. margin_left = zero_value;
  156. if (margin_right.is_auto())
  157. margin_right = zero_value;
  158. if (available_space.width.is_definite()) {
  159. if (underflow_px >= 0) {
  160. width = CSS::Length::make_px(underflow_px);
  161. } else {
  162. width = zero_value;
  163. margin_right = CSS::Length::make_px(margin_right.to_px(box) + underflow_px.value());
  164. }
  165. }
  166. } else {
  167. if (!margin_left.is_auto() && !margin_right.is_auto()) {
  168. margin_right = CSS::Length::make_px(margin_right.to_px(box) + underflow_px.value());
  169. } else if (!margin_left.is_auto() && margin_right.is_auto()) {
  170. margin_right = CSS::Length::make_px(underflow_px);
  171. } else if (margin_left.is_auto() && !margin_right.is_auto()) {
  172. margin_left = CSS::Length::make_px(underflow_px);
  173. } else { // margin_left.is_auto() && margin_right.is_auto()
  174. auto half_of_the_underflow = CSS::Length::make_px(underflow_px / 2);
  175. margin_left = half_of_the_underflow;
  176. margin_right = half_of_the_underflow;
  177. }
  178. }
  179. }
  180. return width;
  181. };
  182. auto input_width = [&] {
  183. if (is<TableWrapper>(box))
  184. return CSS::Length::make_px(compute_width_for_table_wrapper(box, available_space));
  185. if (should_treat_width_as_auto(box, available_space))
  186. return CSS::Length::make_auto();
  187. return calculate_inner_width(box, available_space.width, computed_values.width());
  188. }();
  189. // 1. The tentative used width is calculated (without 'min-width' and 'max-width')
  190. auto used_width = try_compute_width(input_width);
  191. // 2. The tentative used width is greater than 'max-width', the rules above are applied again,
  192. // but this time using the computed value of 'max-width' as the computed value for 'width'.
  193. if (!computed_values.max_width().is_none()) {
  194. auto max_width = calculate_inner_width(box, available_space.width, computed_values.max_width());
  195. if (used_width.to_px(box) > max_width.to_px(box)) {
  196. used_width = try_compute_width(max_width);
  197. }
  198. }
  199. // 3. If the resulting width is smaller than 'min-width', the rules above are applied again,
  200. // but this time using the value of 'min-width' as the computed value for 'width'.
  201. if (!computed_values.min_width().is_auto()) {
  202. auto min_width = calculate_inner_width(box, available_space.width, computed_values.min_width());
  203. if (used_width.to_px(box) < min_width.to_px(box)) {
  204. used_width = try_compute_width(min_width);
  205. }
  206. }
  207. if (!is<ReplacedBox>(box) && !used_width.is_auto())
  208. box_state.set_content_width(used_width.to_px(box));
  209. box_state.margin_left = margin_left.to_px(box);
  210. box_state.margin_right = margin_right.to_px(box);
  211. resolve_vertical_box_model_metrics(box, m_state);
  212. }
  213. void BlockFormattingContext::compute_width_for_floating_box(Box const& box, AvailableSpace const& available_space)
  214. {
  215. // 10.3.5 Floating, non-replaced elements
  216. auto& computed_values = box.computed_values();
  217. auto zero_value = CSS::Length::make_px(0);
  218. auto width_of_containing_block = available_space.width.to_px();
  219. auto width_of_containing_block_as_length_for_resolve = CSS::Length::make_px(width_of_containing_block);
  220. if (!available_space.width.is_definite())
  221. width_of_containing_block_as_length_for_resolve = CSS::Length::make_px(0);
  222. auto margin_left = computed_values.margin().left().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  223. auto margin_right = computed_values.margin().right().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  224. auto const padding_left = computed_values.padding().left().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  225. auto const padding_right = computed_values.padding().right().resolved(box, width_of_containing_block_as_length_for_resolve).resolved(box);
  226. // If 'margin-left', or 'margin-right' are computed as 'auto', their used value is '0'.
  227. if (margin_left.is_auto())
  228. margin_left = zero_value;
  229. if (margin_right.is_auto())
  230. margin_right = zero_value;
  231. auto compute_width = [&](auto width) {
  232. // If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.
  233. if (width.is_auto()) {
  234. // Find the available width: in this case, this is the width of the containing
  235. // block minus the used values of 'margin-left', 'border-left-width', 'padding-left',
  236. // 'padding-right', 'border-right-width', 'margin-right', and the widths of any relevant scroll bars.
  237. auto available_width = width_of_containing_block
  238. - margin_left.to_px(box) - computed_values.border_left().width - padding_left.to_px(box)
  239. - padding_right.to_px(box) - computed_values.border_right().width - margin_right.to_px(box);
  240. auto result = calculate_shrink_to_fit_widths(box);
  241. // Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width).
  242. width = CSS::Length::make_px(min(max(result.preferred_minimum_width, available_width), result.preferred_width));
  243. }
  244. return width;
  245. };
  246. auto input_width = [&] {
  247. if (should_treat_width_as_auto(box, available_space))
  248. return CSS::Length::make_auto();
  249. return calculate_inner_width(box, available_space.width, computed_values.width());
  250. }();
  251. // 1. The tentative used width is calculated (without 'min-width' and 'max-width')
  252. auto width = compute_width(input_width);
  253. // 2. The tentative used width is greater than 'max-width', the rules above are applied again,
  254. // but this time using the computed value of 'max-width' as the computed value for 'width'.
  255. if (!computed_values.max_width().is_none()) {
  256. auto max_width = calculate_inner_width(box, available_space.width, computed_values.max_width());
  257. if (width.to_px(box) > max_width.to_px(box))
  258. width = compute_width(max_width);
  259. }
  260. // 3. If the resulting width is smaller than 'min-width', the rules above are applied again,
  261. // but this time using the value of 'min-width' as the computed value for 'width'.
  262. if (!computed_values.min_width().is_auto()) {
  263. auto min_width = calculate_inner_width(box, available_space.width, computed_values.min_width());
  264. if (width.to_px(box) < min_width.to_px(box))
  265. width = compute_width(min_width);
  266. }
  267. auto& box_state = m_state.get_mutable(box);
  268. box_state.set_content_width(width.to_px(box));
  269. box_state.margin_left = margin_left.to_px(box);
  270. box_state.margin_right = margin_right.to_px(box);
  271. box_state.border_left = computed_values.border_left().width;
  272. box_state.border_right = computed_values.border_right().width;
  273. box_state.padding_left = padding_left.to_px(box);
  274. box_state.padding_right = padding_right.to_px(box);
  275. resolve_vertical_box_model_metrics(box, m_state);
  276. }
  277. void BlockFormattingContext::compute_width_for_block_level_replaced_element_in_normal_flow(ReplacedBox const& box, AvailableSpace const& available_space)
  278. {
  279. m_state.get_mutable(box).set_content_width(compute_width_for_replaced_element(m_state, box, available_space));
  280. }
  281. CSSPixels BlockFormattingContext::compute_width_for_table_wrapper(Box const& box, AvailableSpace const& available_space)
  282. {
  283. // 17.5.2
  284. // Table wrapper width should be equal to width of table box it contains
  285. LayoutState throwaway_state(&m_state);
  286. auto context = create_independent_formatting_context_if_needed(throwaway_state, box);
  287. VERIFY(context);
  288. context->run(box, LayoutMode::IntrinsicSizing, m_state.get(box).available_inner_space_or_constraints_from(available_space));
  289. auto const* table_box = box.first_child_of_type<TableBox>();
  290. return throwaway_state.get(*table_box).content_width();
  291. }
  292. void BlockFormattingContext::compute_height(Box const& box, AvailableSpace const& available_space)
  293. {
  294. auto const& computed_values = box.computed_values();
  295. auto containing_block_height = CSS::Length::make_px(available_space.height.to_px());
  296. // Then work out what the height is, based on box type and CSS properties.
  297. CSSPixels height = 0;
  298. if (is<ReplacedBox>(box)) {
  299. height = compute_height_for_replaced_element(m_state, verify_cast<ReplacedBox>(box), available_space);
  300. } else {
  301. if (should_treat_height_as_auto(box, available_space)) {
  302. height = compute_auto_height_for_block_level_element(box, m_state.get(box).available_inner_space_or_constraints_from(available_space));
  303. } else {
  304. height = calculate_inner_height(box, available_space.height, computed_values.height()).to_px(box);
  305. }
  306. }
  307. if (!computed_values.max_height().is_none()) {
  308. auto max_height = calculate_inner_height(box, available_space.height, computed_values.max_height());
  309. if (!max_height.is_auto())
  310. height = min(height, max_height.to_px(box));
  311. }
  312. if (!computed_values.min_height().is_auto()) {
  313. height = max(height, calculate_inner_height(box, available_space.height, computed_values.min_height()).to_px(box));
  314. }
  315. m_state.get_mutable(box).set_content_height(height);
  316. }
  317. void BlockFormattingContext::layout_inline_children(BlockContainer const& block_container, LayoutMode layout_mode, AvailableSpace const& available_space)
  318. {
  319. VERIFY(block_container.children_are_inline());
  320. auto& block_container_state = m_state.get_mutable(block_container);
  321. InlineFormattingContext context(m_state, block_container, *this);
  322. context.run(
  323. block_container,
  324. layout_mode,
  325. available_space);
  326. if (!block_container_state.has_definite_width())
  327. block_container_state.set_content_width(context.automatic_content_width());
  328. if (!block_container_state.has_definite_height())
  329. block_container_state.set_content_height(context.automatic_content_height());
  330. }
  331. CSSPixels BlockFormattingContext::compute_auto_height_for_block_level_element(Box const& box, AvailableSpace const& available_space)
  332. {
  333. if (creates_block_formatting_context(box)) {
  334. return compute_auto_height_for_block_formatting_context_root(box);
  335. }
  336. auto const& box_state = m_state.get(box);
  337. auto display = box.display();
  338. if (display.is_flex_inside()) {
  339. // https://drafts.csswg.org/css-flexbox-1/#algo-main-container
  340. // NOTE: The automatic block size of a block-level flex container is its max-content size.
  341. return calculate_max_content_height(box, available_space.width);
  342. }
  343. if (display.is_grid_inside()) {
  344. // https://www.w3.org/TR/css-grid-2/#intrinsic-sizes
  345. // In both inline and block formatting contexts, the grid container’s auto block size is its
  346. // max-content size.
  347. return calculate_max_content_height(box, available_space.width);
  348. }
  349. if (display.is_table_inside()) {
  350. return calculate_max_content_height(box, available_space.height);
  351. }
  352. // https://www.w3.org/TR/CSS22/visudet.html#normal-block
  353. // 10.6.3 Block-level non-replaced elements in normal flow when 'overflow' computes to 'visible'
  354. // The element's height is the distance from its top content edge to the first applicable of the following:
  355. // 1. the bottom edge of the last line box, if the box establishes a inline formatting context with one or more lines
  356. if (box.children_are_inline() && !box_state.line_boxes.is_empty())
  357. return box_state.line_boxes.last().bottom().value();
  358. // 2. the bottom edge of the bottom (possibly collapsed) margin of its last in-flow child, if the child's bottom margin does not collapse with the element's bottom margin
  359. // 3. the bottom border edge of the last in-flow child whose top margin doesn't collapse with the element's bottom margin
  360. if (!box.children_are_inline()) {
  361. for (auto* child_box = box.last_child_of_type<Box>(); child_box; child_box = child_box->previous_sibling_of_type<Box>()) {
  362. if (child_box->is_absolutely_positioned() || child_box->is_floating())
  363. continue;
  364. // FIXME: This is hack. If the last child is a list-item marker box, we ignore it for purposes of height calculation.
  365. // Perhaps markers should not be considered in-flow(?) Perhaps they should always be the first child of the list-item
  366. // box instead of the last child.
  367. if (child_box->is_list_item_marker_box())
  368. continue;
  369. auto const& child_box_state = m_state.get(*child_box);
  370. // Ignore anonymous block containers with no lines. These don't count as in-flow block boxes.
  371. if (!child_box->is_table_wrapper() && child_box->is_anonymous() && child_box->is_block_container() && child_box_state.line_boxes.is_empty())
  372. continue;
  373. auto margin_bottom = m_margin_state.current_collapsed_margin();
  374. if (box_state.padding_bottom == 0 && box_state.border_bottom == 0) {
  375. m_margin_state.box_last_in_flow_child_margin_bottom_collapsed = true;
  376. margin_bottom = 0;
  377. }
  378. return max(0.0f, (child_box_state.offset.y() + child_box_state.content_height() + child_box_state.border_box_bottom() + margin_bottom).value());
  379. }
  380. }
  381. // 4. zero, otherwise
  382. return 0;
  383. }
  384. void BlockFormattingContext::layout_block_level_box(Box const& box, BlockContainer const& block_container, LayoutMode layout_mode, CSSPixels& bottom_of_lowest_margin_box, AvailableSpace const& available_space)
  385. {
  386. auto& box_state = m_state.get_mutable(box);
  387. if (box.is_absolutely_positioned()) {
  388. m_absolutely_positioned_boxes.append(box);
  389. return;
  390. }
  391. // NOTE: ListItemMarkerBoxes are placed by their corresponding ListItemBox.
  392. if (is<ListItemMarkerBox>(box))
  393. return;
  394. auto const y = m_y_offset_of_current_block_container.value();
  395. if (box.is_floating()) {
  396. auto margin_top = !m_margin_state.has_block_container_waiting_for_final_y_position() ? m_margin_state.current_collapsed_margin() : 0;
  397. layout_floating_box(box, block_container, layout_mode, available_space, margin_top + y);
  398. bottom_of_lowest_margin_box = max(bottom_of_lowest_margin_box, box_state.offset.y() + box_state.content_height() + box_state.margin_box_bottom());
  399. return;
  400. }
  401. compute_width(box, available_space, layout_mode);
  402. if (box_state.has_definite_height()) {
  403. compute_height(box, available_space);
  404. }
  405. if (box.computed_values().clear() != CSS::Clear::None) {
  406. m_margin_state.reset();
  407. }
  408. m_margin_state.add_margin(box_state.margin_top);
  409. m_margin_state.update_block_waiting_for_final_y_position();
  410. auto margin_top = m_margin_state.current_collapsed_margin();
  411. if (m_margin_state.has_block_container_waiting_for_final_y_position()) {
  412. // If first child margin top will collapse with margin-top of containing block then margin-top of child is 0
  413. margin_top = 0;
  414. }
  415. place_block_level_element_in_normal_flow_vertically(box, y + margin_top);
  416. place_block_level_element_in_normal_flow_horizontally(box, available_space);
  417. OwnPtr<FormattingContext> independent_formatting_context;
  418. if (!box.is_replaced_box() && box.has_children()) {
  419. independent_formatting_context = create_independent_formatting_context_if_needed(m_state, box);
  420. if (independent_formatting_context) {
  421. // Margins of elements that establish new formatting contexts do not collapse with their in-flow children
  422. m_margin_state.reset();
  423. independent_formatting_context->run(box, layout_mode, box_state.available_inner_space_or_constraints_from(available_space));
  424. } else {
  425. if (box.children_are_inline()) {
  426. layout_inline_children(verify_cast<BlockContainer>(box), layout_mode, box_state.available_inner_space_or_constraints_from(available_space));
  427. } else {
  428. if (box_state.border_top > 0 || box_state.padding_top > 0) {
  429. // margin-top of block container can't collapse with it's children if it has non zero border or padding
  430. m_margin_state.reset();
  431. } else if (!m_margin_state.has_block_container_waiting_for_final_y_position()) {
  432. // margin-top of block container can be updated during children layout hence it's final y position yet to be determined
  433. m_margin_state.register_block_container_y_position_update_callback([&](CSSPixels margin_top) {
  434. place_block_level_element_in_normal_flow_vertically(box, margin_top + y + box_state.border_box_top());
  435. });
  436. }
  437. layout_block_level_children(verify_cast<BlockContainer>(box), layout_mode, box_state.available_inner_space_or_constraints_from(available_space));
  438. }
  439. }
  440. }
  441. compute_height(box, available_space);
  442. if (!margins_collapse_through(box, m_state)) {
  443. if (!m_margin_state.box_last_in_flow_child_margin_bottom_collapsed) {
  444. m_margin_state.reset();
  445. }
  446. m_y_offset_of_current_block_container = box_state.offset.y() + box_state.content_height() + box_state.border_box_bottom();
  447. }
  448. m_margin_state.box_last_in_flow_child_margin_bottom_collapsed = false;
  449. m_margin_state.add_margin(box_state.margin_bottom);
  450. m_margin_state.update_block_waiting_for_final_y_position();
  451. compute_inset(box);
  452. if (is<ListItemBox>(box)) {
  453. layout_list_item_marker(static_cast<ListItemBox const&>(box));
  454. }
  455. bottom_of_lowest_margin_box = max(bottom_of_lowest_margin_box, box_state.offset.y() + box_state.content_height() + box_state.margin_box_bottom());
  456. if (independent_formatting_context)
  457. independent_formatting_context->parent_context_did_dimension_child_root_box();
  458. }
  459. void BlockFormattingContext::layout_block_level_children(BlockContainer const& block_container, LayoutMode layout_mode, AvailableSpace const& available_space)
  460. {
  461. VERIFY(!block_container.children_are_inline());
  462. CSSPixels bottom_of_lowest_margin_box = 0;
  463. TemporaryChange<Optional<CSSPixels>> change { m_y_offset_of_current_block_container, CSSPixels(0) };
  464. block_container.for_each_child_of_type<Box>([&](Box& box) {
  465. layout_block_level_box(box, block_container, layout_mode, bottom_of_lowest_margin_box, available_space);
  466. return IterationDecision::Continue;
  467. });
  468. m_margin_state.block_container_y_position_update_callback = {};
  469. if (layout_mode == LayoutMode::IntrinsicSizing) {
  470. auto& block_container_state = m_state.get_mutable(block_container);
  471. if (!block_container_state.has_definite_width())
  472. block_container_state.set_content_width(greatest_child_width(block_container));
  473. if (!block_container_state.has_definite_height())
  474. block_container_state.set_content_height(bottom_of_lowest_margin_box);
  475. }
  476. }
  477. void BlockFormattingContext::resolve_vertical_box_model_metrics(Box const& box, LayoutState& state)
  478. {
  479. auto& box_state = state.get_mutable(box);
  480. auto const& computed_values = box.computed_values();
  481. auto width_of_containing_block = CSS::Length::make_px(containing_block_width_for(box, state));
  482. box_state.margin_top = computed_values.margin().top().resolved(box, width_of_containing_block).to_px(box);
  483. box_state.margin_bottom = computed_values.margin().bottom().resolved(box, width_of_containing_block).to_px(box);
  484. box_state.border_top = computed_values.border_top().width;
  485. box_state.border_bottom = computed_values.border_bottom().width;
  486. box_state.padding_top = computed_values.padding().top().resolved(box, width_of_containing_block).to_px(box);
  487. box_state.padding_bottom = computed_values.padding().bottom().resolved(box, width_of_containing_block).to_px(box);
  488. }
  489. CSSPixels BlockFormattingContext::BlockMarginState::current_collapsed_margin() const
  490. {
  491. CSSPixels smallest_margin = 0;
  492. CSSPixels largest_margin = 0;
  493. size_t negative_margin_count = 0;
  494. for (auto margin : current_collapsible_margins) {
  495. if (margin < 0)
  496. ++negative_margin_count;
  497. largest_margin = max(largest_margin, margin);
  498. smallest_margin = min(smallest_margin, margin);
  499. }
  500. CSSPixels collapsed_margin = 0;
  501. if (negative_margin_count == current_collapsible_margins.size()) {
  502. // When all margins are negative, the size of the collapsed margin is the smallest (most negative) margin.
  503. collapsed_margin = smallest_margin;
  504. } else if (negative_margin_count > 0) {
  505. // When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.
  506. collapsed_margin = largest_margin + smallest_margin;
  507. } else {
  508. // Otherwise, collapse all the adjacent margins by using only the largest one.
  509. collapsed_margin = largest_margin;
  510. }
  511. return collapsed_margin;
  512. }
  513. void BlockFormattingContext::place_block_level_element_in_normal_flow_vertically(Box const& child_box, CSSPixels y)
  514. {
  515. auto& box_state = m_state.get_mutable(child_box);
  516. auto const& computed_values = child_box.computed_values();
  517. auto clear_floating_boxes = [&](FloatSideData& float_side) {
  518. if (!float_side.current_boxes.is_empty()) {
  519. // NOTE: Floating boxes are globally relevant within this BFC, *but* their offset coordinates
  520. // are relative to their containing block.
  521. // This means that we have to first convert to a root-space Y coordinate before clearing,
  522. // and then convert back to a local Y coordinate when assigning the cleared offset to
  523. // the `child_box` layout state.
  524. // First, find the lowest margin box edge on this float side and calculate the Y offset just below it.
  525. CSSPixels clearance_y_in_root = 0;
  526. for (auto const& floating_box : float_side.current_boxes) {
  527. auto floating_box_rect_in_root = margin_box_rect_in_ancestor_coordinate_space(floating_box.box, root(), m_state);
  528. clearance_y_in_root = max(clearance_y_in_root, floating_box_rect_in_root.bottom() + 1);
  529. }
  530. // Then, convert the clearance Y to a coordinate relative to the containing block of `child_box`.
  531. CSSPixels clearance_y_in_containing_block = clearance_y_in_root;
  532. for (auto* containing_block = child_box.containing_block(); containing_block && containing_block != &root(); containing_block = containing_block->containing_block())
  533. clearance_y_in_containing_block -= m_state.get(*containing_block).offset.y();
  534. if (clearance_y_in_containing_block > y)
  535. m_y_offset_of_current_block_container = clearance_y_in_containing_block;
  536. y = max(y, clearance_y_in_containing_block);
  537. float_side.clear();
  538. }
  539. };
  540. // Flex-items don't float and also don't clear.
  541. if ((computed_values.clear() == CSS::Clear::Left || computed_values.clear() == CSS::Clear::Both) && !child_box.is_flex_item())
  542. clear_floating_boxes(m_left_floats);
  543. if ((computed_values.clear() == CSS::Clear::Right || computed_values.clear() == CSS::Clear::Both) && !child_box.is_flex_item())
  544. clear_floating_boxes(m_right_floats);
  545. y += box_state.border_box_top();
  546. box_state.set_content_offset(CSSPixelPoint { box_state.offset.x(), y.value() });
  547. }
  548. void BlockFormattingContext::place_block_level_element_in_normal_flow_horizontally(Box const& child_box, AvailableSpace const& available_space)
  549. {
  550. auto& box_state = m_state.get_mutable(child_box);
  551. CSSPixels x = 0;
  552. CSSPixels available_width_within_containing_block = available_space.width.to_px();
  553. if ((!m_left_floats.current_boxes.is_empty() || !m_right_floats.current_boxes.is_empty())
  554. && creates_block_formatting_context(child_box)) {
  555. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(child_box, root(), m_state);
  556. auto space = space_used_by_floats(box_in_root_rect.y());
  557. available_width_within_containing_block -= space.left + space.right;
  558. x += space.left;
  559. }
  560. if (child_box.containing_block()->computed_values().text_align() == CSS::TextAlign::LibwebCenter) {
  561. x += (available_width_within_containing_block / 2) - box_state.content_width() / 2;
  562. } else {
  563. x += box_state.margin_box_left();
  564. }
  565. box_state.set_content_offset({ x.value(), box_state.offset.y() });
  566. }
  567. static void measure_scrollable_overflow(LayoutState const& state, Box const& box, CSSPixels& bottom_edge, CSSPixels& right_edge)
  568. {
  569. auto const& child_state = state.get(box);
  570. auto child_rect = absolute_content_rect(box, state);
  571. child_rect.inflate(child_state.border_box_top(), child_state.border_box_right(), child_state.border_box_bottom(), child_state.border_box_left());
  572. bottom_edge = max(bottom_edge, child_rect.bottom());
  573. right_edge = max(right_edge, child_rect.right());
  574. if (box.computed_values().overflow_x() == CSS::Overflow::Hidden && box.computed_values().overflow_y() == CSS::Overflow::Hidden)
  575. return;
  576. if (box.children_are_inline()) {
  577. if (!child_state.line_boxes.is_empty()) {
  578. bottom_edge = max(bottom_edge, child_rect.y() + child_state.line_boxes.last().bottom());
  579. for (auto& line_box : child_state.line_boxes) {
  580. if (line_box.fragments().is_empty())
  581. continue;
  582. right_edge = max(right_edge, child_rect.x() + line_box.fragments().last().width());
  583. }
  584. }
  585. } else {
  586. box.for_each_child_of_type<Box>([&](Box const& child) {
  587. measure_scrollable_overflow(state, child, bottom_edge, right_edge);
  588. return IterationDecision::Continue;
  589. });
  590. }
  591. }
  592. void BlockFormattingContext::layout_viewport(LayoutMode layout_mode, AvailableSpace const& available_space)
  593. {
  594. auto viewport_rect = root().browsing_context().viewport_rect();
  595. auto& viewport = verify_cast<Layout::Viewport>(root());
  596. auto& viewport_state = m_state.get_mutable(viewport);
  597. if (root().children_are_inline())
  598. layout_inline_children(root(), layout_mode, available_space);
  599. else
  600. layout_block_level_children(root(), layout_mode, available_space);
  601. CSSPixels bottom_edge = 0;
  602. CSSPixels right_edge = 0;
  603. measure_scrollable_overflow(m_state, viewport, bottom_edge, right_edge);
  604. if (bottom_edge >= viewport_rect.height() || right_edge >= viewport_rect.width()) {
  605. // FIXME: Move overflow data to LayoutState!
  606. auto& overflow_data = viewport_state.ensure_overflow_data();
  607. overflow_data.scrollable_overflow_rect = viewport_rect;
  608. // NOTE: The edges are *within* the rectangle, so we add 1 to get the width and height.
  609. overflow_data.scrollable_overflow_rect.set_size(right_edge + 1, bottom_edge + 1);
  610. }
  611. }
  612. void BlockFormattingContext::layout_floating_box(Box const& box, BlockContainer const&, LayoutMode layout_mode, AvailableSpace const& available_space, CSSPixels y, LineBuilder* line_builder)
  613. {
  614. VERIFY(box.is_floating());
  615. auto& box_state = m_state.get_mutable(box);
  616. CSSPixels width_of_containing_block = available_space.width.to_px();
  617. compute_width(box, available_space, layout_mode);
  618. auto independent_formatting_context = layout_inside(box, layout_mode, box_state.available_inner_space_or_constraints_from(available_space));
  619. compute_height(box, available_space);
  620. // First we place the box normally (to get the right y coordinate.)
  621. // If we have a LineBuilder, we're in the middle of inline layout, otherwise this is block layout.
  622. if (line_builder) {
  623. auto y = line_builder->y_for_float_to_be_inserted_here(box);
  624. box_state.set_content_y(y + box_state.margin_box_top());
  625. } else {
  626. place_block_level_element_in_normal_flow_vertically(box, y + box_state.margin_top);
  627. place_block_level_element_in_normal_flow_horizontally(box, available_space);
  628. }
  629. // Then we float it to the left or right.
  630. auto float_box = [&](FloatSide side, FloatSideData& side_data, FloatSideData& other_side_data) {
  631. CSSPixels offset_from_edge = 0;
  632. auto float_to_edge = [&] {
  633. if (side == FloatSide::Left)
  634. offset_from_edge = box_state.margin_box_left();
  635. else
  636. offset_from_edge = box_state.content_width() + box_state.margin_box_right();
  637. };
  638. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(box, root(), m_state);
  639. CSSPixels y_in_root = box_in_root_rect.y();
  640. CSSPixels y = box_state.offset.y();
  641. if (side_data.current_boxes.is_empty()) {
  642. // This is the first floating box on this side. Go all the way to the edge.
  643. float_to_edge();
  644. side_data.y_offset = 0;
  645. } else {
  646. // NOTE: If we're in inline layout, the LineBuilder has already provided the right Y offset.
  647. // In block layout, we adjust by the side's current Y offset here.
  648. if (!line_builder)
  649. y_in_root += side_data.y_offset;
  650. bool did_touch_preceding_float = false;
  651. bool did_place_next_to_preceding_float = false;
  652. // Walk all currently tracked floats on the side we're floating towards.
  653. // We're looking for the innermost preceding float that intersects vertically with `box`.
  654. for (auto& preceding_float : side_data.current_boxes.in_reverse()) {
  655. auto const preceding_float_rect = margin_box_rect_in_ancestor_coordinate_space(preceding_float.box, root(), m_state);
  656. if (!preceding_float_rect.contains_vertically(y_in_root))
  657. continue;
  658. // We found a preceding float that intersects vertically with the current float.
  659. // Now we need to find out if there's enough inline-axis space to stack them next to each other.
  660. auto const& preceding_float_state = m_state.get(preceding_float.box);
  661. CSSPixels tentative_offset_from_edge = 0;
  662. bool fits_next_to_preceding_float = false;
  663. if (side == FloatSide::Left) {
  664. tentative_offset_from_edge = preceding_float.offset_from_edge + preceding_float_state.content_width() + preceding_float_state.margin_box_right() + box_state.margin_box_left();
  665. fits_next_to_preceding_float = (tentative_offset_from_edge + box_state.content_width() + box_state.margin_box_right()) <= width_of_containing_block;
  666. } else {
  667. tentative_offset_from_edge = preceding_float.offset_from_edge + preceding_float_state.margin_box_left() + box_state.margin_box_right() + box_state.content_width();
  668. fits_next_to_preceding_float = tentative_offset_from_edge >= 0;
  669. }
  670. did_touch_preceding_float = true;
  671. if (!fits_next_to_preceding_float)
  672. break;
  673. offset_from_edge = tentative_offset_from_edge;
  674. did_place_next_to_preceding_float = true;
  675. break;
  676. }
  677. if (!did_touch_preceding_float || !did_place_next_to_preceding_float) {
  678. // One of two things happened:
  679. // - This box does not touch another floating box.
  680. // - We ran out of horizontal space on this "float line", and need to break.
  681. // Either way, we float this box all the way to the edge.
  682. float_to_edge();
  683. CSSPixels lowest_margin_edge = 0;
  684. for (auto const& box : side_data.current_boxes) {
  685. auto const& box_state = m_state.get(box.box);
  686. lowest_margin_edge = max(lowest_margin_edge, box_state.margin_box_height());
  687. }
  688. side_data.y_offset += lowest_margin_edge;
  689. // Also, forget all previous boxes floated to this side while since they're no longer relevant.
  690. side_data.clear();
  691. }
  692. }
  693. // NOTE: If we're in inline layout, the LineBuilder has already provided the right Y offset.
  694. // In block layout, we adjust by the side's current Y offset here.
  695. // FIXME: It's annoying that we have different behavior for inline vs block here.
  696. // Find a way to unify the behavior so we don't need to branch here.
  697. if (!line_builder)
  698. y += side_data.y_offset;
  699. side_data.all_boxes.append(adopt_own(*new FloatingBox {
  700. .box = box,
  701. .offset_from_edge = offset_from_edge,
  702. .top_margin_edge = y - box_state.margin_box_top(),
  703. .bottom_margin_edge = y + box_state.content_height() + box_state.margin_box_bottom(),
  704. }));
  705. side_data.current_boxes.append(*side_data.all_boxes.last());
  706. if (side == FloatSide::Left) {
  707. side_data.current_width = offset_from_edge + box_state.content_width() + box_state.margin_box_right();
  708. } else {
  709. side_data.current_width = offset_from_edge + box_state.margin_box_left();
  710. }
  711. side_data.max_width = max(side_data.current_width, side_data.max_width);
  712. // NOTE: We don't set the X position here, that happens later, once we know the root block width.
  713. // See parent_context_did_dimension_child_root_box() for that logic.
  714. box_state.set_content_y(y.value());
  715. // If the new box was inserted below the bottom of the opposite side,
  716. // we reset the other side back to its edge.
  717. if (y > other_side_data.y_offset)
  718. other_side_data.clear();
  719. };
  720. // Next, float to the left and/or right
  721. if (box.computed_values().float_() == CSS::Float::Left) {
  722. float_box(FloatSide::Left, m_left_floats, m_right_floats);
  723. } else if (box.computed_values().float_() == CSS::Float::Right) {
  724. float_box(FloatSide::Right, m_right_floats, m_left_floats);
  725. }
  726. m_state.get_mutable(root()).add_floating_descendant(box);
  727. if (line_builder)
  728. line_builder->recalculate_available_space();
  729. if (independent_formatting_context)
  730. independent_formatting_context->parent_context_did_dimension_child_root_box();
  731. }
  732. void BlockFormattingContext::layout_list_item_marker(ListItemBox const& list_item_box)
  733. {
  734. if (!list_item_box.marker())
  735. return;
  736. auto& marker = *list_item_box.marker();
  737. auto& marker_state = m_state.get_mutable(marker);
  738. auto& list_item_state = m_state.get_mutable(list_item_box);
  739. CSSPixels image_width = 0;
  740. CSSPixels image_height = 0;
  741. if (auto const* list_style_image = marker.list_style_image()) {
  742. image_width = list_style_image->natural_width().value_or(0);
  743. image_height = list_style_image->natural_height().value_or(0);
  744. }
  745. CSSPixels default_marker_width = max(4, marker.font().pixel_size_rounded_up() - 4);
  746. if (marker.text().is_empty()) {
  747. marker_state.set_content_width((image_width + default_marker_width).value());
  748. } else {
  749. auto text_width = marker.font().width(marker.text());
  750. marker_state.set_content_width((image_width + text_width).value());
  751. }
  752. marker_state.set_content_height(max(image_height, marker.font().pixel_size_rounded_up() + 1).value());
  753. marker_state.set_content_offset({ -(marker_state.content_width() + default_marker_width),
  754. max(CSSPixels(0.f), (CSSPixels(marker.line_height()) - marker_state.content_height()) / 2.f) });
  755. if (marker_state.content_height() > list_item_state.content_height())
  756. list_item_state.set_content_height(marker_state.content_height());
  757. }
  758. BlockFormattingContext::SpaceUsedByFloats BlockFormattingContext::space_used_by_floats(CSSPixels y) const
  759. {
  760. SpaceUsedByFloats space_used_by_floats;
  761. for (auto const& floating_box_ptr : m_left_floats.all_boxes.in_reverse()) {
  762. auto const& floating_box = *floating_box_ptr;
  763. auto const& floating_box_state = m_state.get(floating_box.box);
  764. // NOTE: The floating box is *not* in the final horizontal position yet, but the size and vertical position is valid.
  765. auto rect = margin_box_rect_in_ancestor_coordinate_space(floating_box.box, root(), m_state);
  766. if (rect.contains_vertically(y.value())) {
  767. space_used_by_floats.left = floating_box.offset_from_edge
  768. + floating_box_state.content_width()
  769. + floating_box_state.margin_box_right();
  770. break;
  771. }
  772. }
  773. for (auto const& floating_box_ptr : m_right_floats.all_boxes.in_reverse()) {
  774. auto const& floating_box = *floating_box_ptr;
  775. auto const& floating_box_state = m_state.get(floating_box.box);
  776. // NOTE: The floating box is *not* in the final horizontal position yet, but the size and vertical position is valid.
  777. auto rect = margin_box_rect_in_ancestor_coordinate_space(floating_box.box, root(), m_state);
  778. if (rect.contains_vertically(y.value())) {
  779. space_used_by_floats.right = floating_box.offset_from_edge
  780. + floating_box_state.margin_box_left();
  781. break;
  782. }
  783. }
  784. return space_used_by_floats;
  785. }
  786. CSSPixels BlockFormattingContext::greatest_child_width(Box const& box) const
  787. {
  788. // Similar to FormattingContext::greatest_child_width()
  789. // but this one takes floats into account!
  790. CSSPixels max_width = m_left_floats.max_width + m_right_floats.max_width;
  791. if (box.children_are_inline()) {
  792. for (auto const& line_box : m_state.get(verify_cast<BlockContainer>(box)).line_boxes) {
  793. CSSPixels width_here = line_box.width();
  794. CSSPixels extra_width_from_left_floats = 0;
  795. for (auto& left_float : m_left_floats.all_boxes) {
  796. if (line_box.baseline() >= left_float->top_margin_edge.value() || line_box.baseline() <= left_float->bottom_margin_edge.value()) {
  797. auto const& left_float_state = m_state.get(left_float->box);
  798. extra_width_from_left_floats = max(extra_width_from_left_floats, left_float->offset_from_edge + left_float_state.content_width() + left_float_state.margin_box_right());
  799. }
  800. }
  801. CSSPixels extra_width_from_right_floats = 0;
  802. for (auto& right_float : m_right_floats.all_boxes) {
  803. if (line_box.baseline() >= right_float->top_margin_edge.value() || line_box.baseline() <= right_float->bottom_margin_edge.value()) {
  804. auto const& right_float_state = m_state.get(right_float->box);
  805. extra_width_from_right_floats = max(extra_width_from_right_floats, right_float->offset_from_edge + right_float_state.margin_box_left());
  806. }
  807. }
  808. width_here += extra_width_from_left_floats + extra_width_from_right_floats;
  809. max_width = max(max_width, width_here);
  810. }
  811. } else {
  812. box.for_each_child_of_type<Box>([&](Box const& child) {
  813. if (!child.is_absolutely_positioned())
  814. max_width = max(max_width, m_state.get(child).margin_box_width());
  815. });
  816. }
  817. return max_width;
  818. }
  819. void BlockFormattingContext::determine_width_of_child(Box const& box, AvailableSpace const& available_space)
  820. {
  821. compute_width(box, available_space);
  822. }
  823. void BlockFormattingContext::determine_height_of_child(Box const& box, AvailableSpace const& available_space)
  824. {
  825. compute_height(box, available_space);
  826. }
  827. }