BlockFormattingContext.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <andreas@ladybird.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/FieldSetBox.h>
  15. #include <LibWeb/Layout/InlineFormattingContext.h>
  16. #include <LibWeb/Layout/LegendBox.h>
  17. #include <LibWeb/Layout/LineBuilder.h>
  18. #include <LibWeb/Layout/ListItemBox.h>
  19. #include <LibWeb/Layout/ListItemMarkerBox.h>
  20. #include <LibWeb/Layout/ReplacedBox.h>
  21. #include <LibWeb/Layout/SVGSVGBox.h>
  22. #include <LibWeb/Layout/TableWrapper.h>
  23. #include <LibWeb/Layout/Viewport.h>
  24. namespace Web::Layout {
  25. BlockFormattingContext::BlockFormattingContext(LayoutState& state, LayoutMode layout_mode, BlockContainer const& root, FormattingContext* parent)
  26. : FormattingContext(Type::Block, layout_mode, state, root, parent)
  27. {
  28. }
  29. BlockFormattingContext::~BlockFormattingContext()
  30. {
  31. if (!m_was_notified_after_parent_dimensioned_my_root_box) {
  32. // HACK: The parent formatting context never notified us after assigning dimensions to our root box.
  33. // Pretend that it did anyway, to make sure absolutely positioned children get laid out.
  34. // FIXME: Get rid of this hack once parent contexts behave properly.
  35. parent_context_did_dimension_child_root_box();
  36. }
  37. }
  38. CSSPixels BlockFormattingContext::automatic_content_width() const
  39. {
  40. if (root().children_are_inline())
  41. return m_state.get(root()).content_width();
  42. return greatest_child_width(root());
  43. }
  44. CSSPixels BlockFormattingContext::automatic_content_height() const
  45. {
  46. return compute_auto_height_for_block_formatting_context_root(root());
  47. }
  48. static bool margins_collapse_through(Box const& box, LayoutState& state)
  49. {
  50. // FIXME: A box's own margins collapse if the 'min-height' property is zero, and it has neither top or bottom borders
  51. // nor top or bottom padding, and it has a 'height' of either 0 or 'auto', and it does not contain a line box, and
  52. // all of its in-flow children's margins (if any) collapse.
  53. // https://www.w3.org/TR/CSS22/box.html#collapsing-margins
  54. // FIXME: For the purpose of margin collapsing (CSS 2 §8.3.1 Collapsing margins), if the block axis is the
  55. // ratio-dependent axis, it is not considered to have a computed block-size of auto.
  56. // https://www.w3.org/TR/css-sizing-4/#aspect-ratio-margin-collapse
  57. if (box.computed_values().clear() != CSS::Clear::None)
  58. return false;
  59. return state.get(box).border_box_height() == 0;
  60. }
  61. void BlockFormattingContext::run(AvailableSpace const& available_space)
  62. {
  63. if (is<Viewport>(root())) {
  64. layout_viewport(available_space);
  65. return;
  66. }
  67. if (is<FieldSetBox>(root())) {
  68. if (root().children_are_inline())
  69. layout_inline_children(root(), available_space);
  70. else
  71. layout_block_level_children(root(), available_space);
  72. auto const& fieldset_box = verify_cast<FieldSetBox>(root());
  73. if (!(fieldset_box.has_rendered_legend())) {
  74. return;
  75. }
  76. auto const* legend = root().first_child_of_type<LegendBox>();
  77. auto& legend_state = m_state.get_mutable(*legend);
  78. auto& fieldset_state = m_state.get_mutable(root());
  79. // The element is expected to be positioned in the block-flow direction such that
  80. // its border box is centered over the border on the block-start side of the fieldset element.
  81. // FIXME: this should take writing modes into consideration.
  82. auto legend_height = legend_state.border_box_height();
  83. auto new_y = -((legend_height) / 2) - fieldset_state.padding_top;
  84. legend_state.set_content_offset({ legend_state.offset.x(), new_y });
  85. // If the computed value of 'inline-size' is 'auto',
  86. // then the used value is the fit-content inline size.
  87. if (legend->computed_values().width().is_auto()) {
  88. auto width = calculate_fit_content_width(*legend, available_space);
  89. legend_state.set_content_width(width);
  90. }
  91. return;
  92. }
  93. if (root().children_are_inline())
  94. layout_inline_children(root(), available_space);
  95. else
  96. layout_block_level_children(root(), available_space);
  97. // Assign collapsed margin left after children layout of formatting context to the last child box
  98. if (m_margin_state.current_collapsed_margin() != 0) {
  99. for (auto* child_box = root().last_child_of_type<Box>(); child_box; child_box = child_box->previous_sibling_of_type<Box>()) {
  100. if (child_box->is_absolutely_positioned() || child_box->is_floating())
  101. continue;
  102. if (margins_collapse_through(*child_box, m_state))
  103. continue;
  104. m_state.get_mutable(*child_box).margin_bottom = m_margin_state.current_collapsed_margin();
  105. break;
  106. }
  107. }
  108. }
  109. void BlockFormattingContext::parent_context_did_dimension_child_root_box()
  110. {
  111. m_was_notified_after_parent_dimensioned_my_root_box = true;
  112. // Left-side floats: offset_from_edge is from left edge (0) to left content edge of floating_box.
  113. for (auto& floating_box : m_left_floats.all_boxes) {
  114. auto& box_state = m_state.get_mutable(floating_box->box);
  115. box_state.set_content_x(floating_box->offset_from_edge);
  116. }
  117. // Right-side floats: offset_from_edge is from right edge (float_containing_block_width) to the left content edge of floating_box.
  118. for (auto& floating_box : m_right_floats.all_boxes) {
  119. auto float_containing_block_width = containing_block_width_for(floating_box->box);
  120. auto& box_state = m_state.get_mutable(floating_box->box);
  121. box_state.set_content_x(float_containing_block_width - floating_box->offset_from_edge);
  122. }
  123. if (m_layout_mode == LayoutMode::Normal) {
  124. // We can also layout absolutely positioned boxes within this BFC.
  125. for (auto& child : root().contained_abspos_children()) {
  126. auto& box = verify_cast<Box>(*child);
  127. auto& cb_state = m_state.get(*box.containing_block());
  128. auto available_width = AvailableSize::make_definite(cb_state.content_width() + cb_state.padding_left + cb_state.padding_right);
  129. auto available_height = AvailableSize::make_definite(cb_state.content_height() + cb_state.padding_top + cb_state.padding_bottom);
  130. layout_absolutely_positioned_element(box, AvailableSpace(available_width, available_height));
  131. }
  132. }
  133. }
  134. bool BlockFormattingContext::box_should_avoid_floats_because_it_establishes_fc(Box const& box)
  135. {
  136. if (auto formatting_context_type = formatting_context_type_created_by_box(box); formatting_context_type.has_value()) {
  137. if (formatting_context_type.value() == Type::Block)
  138. return true;
  139. if (formatting_context_type.value() == Type::Flex)
  140. return true;
  141. if (formatting_context_type.value() == Type::Grid)
  142. return true;
  143. }
  144. return false;
  145. }
  146. void BlockFormattingContext::compute_width(Box const& box, AvailableSpace const& available_space)
  147. {
  148. auto remaining_available_space = available_space;
  149. if (available_space.width.is_definite() && box_should_avoid_floats_because_it_establishes_fc(box)) {
  150. // NOTE: Although CSS 2.2 specification says that only block formatting contexts should avoid floats,
  151. // we also do this for flex and grid formatting contexts, because that how other engines behave.
  152. // 9.5 Floats
  153. // The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a
  154. // new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap the margin
  155. // box of any floats in the same block formatting context as the element itself. If necessary, implementations should
  156. // clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is
  157. // sufficient space. They may even make the border box of said element narrower than defined by section 10.3.3.
  158. // CSS2 does not define when a UA may put said element next to the float or by how much said element may
  159. // become narrower.
  160. auto intrusion = intrusion_by_floats_into_box(box, 0);
  161. auto remaining_width = available_space.width.to_px_or_zero() - intrusion.left - intrusion.right;
  162. remaining_available_space.width = AvailableSize::make_definite(remaining_width);
  163. }
  164. if (box_is_sized_as_replaced_element(box)) {
  165. // FIXME: This should not be done *by* ReplacedBox
  166. if (is<ReplacedBox>(box)) {
  167. auto& replaced = verify_cast<ReplacedBox>(box);
  168. // FIXME: This const_cast is gross.
  169. const_cast<ReplacedBox&>(replaced).prepare_for_replaced_layout();
  170. }
  171. compute_width_for_block_level_replaced_element_in_normal_flow(box, remaining_available_space);
  172. if (box.is_floating()) {
  173. // 10.3.6 Floating, replaced elements:
  174. // https://www.w3.org/TR/CSS22/visudet.html#float-replaced-width
  175. return;
  176. }
  177. }
  178. if (box.is_floating()) {
  179. // 10.3.5 Floating, non-replaced elements:
  180. // https://www.w3.org/TR/CSS22/visudet.html#float-width
  181. compute_width_for_floating_box(box, available_space);
  182. return;
  183. }
  184. auto const& computed_values = box.computed_values();
  185. auto width_of_containing_block = remaining_available_space.width.to_px_or_zero();
  186. auto zero_value = CSS::Length::make_px(0);
  187. auto margin_left = CSS::Length::make_auto();
  188. auto margin_right = CSS::Length::make_auto();
  189. auto const padding_left = computed_values.padding().left().resolved(box, width_of_containing_block).to_px(box);
  190. auto const padding_right = computed_values.padding().right().resolved(box, width_of_containing_block).to_px(box);
  191. auto& box_state = m_state.get_mutable(box);
  192. box_state.border_left = computed_values.border_left().width;
  193. box_state.border_right = computed_values.border_right().width;
  194. box_state.padding_left = padding_left;
  195. box_state.padding_right = padding_right;
  196. // NOTE: If we are calculating the min-content or max-content width of this box,
  197. // and the width should be treated as auto, then we can simply return here,
  198. // as the preferred width and min/max constraints are irrelevant for intrinsic sizing.
  199. if (box_state.width_constraint != SizeConstraint::None)
  200. return;
  201. auto try_compute_width = [&](CSS::Length const& a_width) {
  202. CSS::Length width = a_width;
  203. margin_left = computed_values.margin().left().resolved(box, width_of_containing_block);
  204. margin_right = computed_values.margin().right().resolved(box, width_of_containing_block);
  205. CSSPixels total_px = computed_values.border_left().width + computed_values.border_right().width;
  206. for (auto& value : { margin_left, CSS::Length::make_px(padding_left), width, CSS::Length::make_px(padding_right), margin_right }) {
  207. total_px += value.to_px(box);
  208. }
  209. if (!box.is_inline()) {
  210. // 10.3.3 Block-level, non-replaced elements in normal flow
  211. // 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.
  212. if (!width.is_auto() && total_px > width_of_containing_block) {
  213. if (margin_left.is_auto())
  214. margin_left = zero_value;
  215. if (margin_right.is_auto())
  216. margin_right = zero_value;
  217. }
  218. // 10.3.3 cont'd.
  219. auto underflow_px = width_of_containing_block - total_px;
  220. if (available_space.width.is_intrinsic_sizing_constraint())
  221. underflow_px = 0;
  222. if (width.is_auto()) {
  223. if (margin_left.is_auto())
  224. margin_left = zero_value;
  225. if (margin_right.is_auto())
  226. margin_right = zero_value;
  227. if (available_space.width.is_definite()) {
  228. if (underflow_px >= 0) {
  229. width = CSS::Length::make_px(underflow_px);
  230. } else {
  231. width = zero_value;
  232. margin_right = CSS::Length::make_px(margin_right.to_px(box) + underflow_px);
  233. }
  234. }
  235. } else {
  236. if (!margin_left.is_auto() && !margin_right.is_auto()) {
  237. margin_right = CSS::Length::make_px(margin_right.to_px(box) + underflow_px);
  238. } else if (!margin_left.is_auto() && margin_right.is_auto()) {
  239. margin_right = CSS::Length::make_px(underflow_px);
  240. } else if (margin_left.is_auto() && !margin_right.is_auto()) {
  241. margin_left = CSS::Length::make_px(underflow_px);
  242. } else { // margin_left.is_auto() && margin_right.is_auto()
  243. auto half_of_the_underflow = CSS::Length::make_px(underflow_px / 2);
  244. margin_left = half_of_the_underflow;
  245. margin_right = half_of_the_underflow;
  246. }
  247. }
  248. }
  249. return width;
  250. };
  251. auto input_width = [&] {
  252. if (box_is_sized_as_replaced_element(box)) {
  253. // NOTE: Replaced elements had their width calculated independently above.
  254. // We use that width as the input here to ensure that margins get resolved.
  255. return CSS::Length::make_px(box_state.content_width());
  256. }
  257. if (is<TableWrapper>(box))
  258. return CSS::Length::make_px(compute_table_box_width_inside_table_wrapper(box, remaining_available_space));
  259. if (should_treat_width_as_auto(box, remaining_available_space))
  260. return CSS::Length::make_auto();
  261. return CSS::Length::make_px(calculate_inner_width(box, remaining_available_space.width, computed_values.width()));
  262. }();
  263. // 1. The tentative used width is calculated (without 'min-width' and 'max-width')
  264. auto used_width = try_compute_width(input_width);
  265. // 2. The tentative used width is greater than 'max-width', the rules above are applied again,
  266. // but this time using the computed value of 'max-width' as the computed value for 'width'.
  267. if (!should_treat_max_width_as_none(box, available_space.width)) {
  268. auto max_width = calculate_inner_width(box, remaining_available_space.width, computed_values.max_width());
  269. auto used_width_px = used_width.is_auto() ? CSSPixels { 0 } : used_width.to_px(box);
  270. if (used_width_px > max_width) {
  271. used_width = try_compute_width(CSS::Length::make_px(max_width));
  272. }
  273. }
  274. // 3. If the resulting width is smaller than 'min-width', the rules above are applied again,
  275. // but this time using the value of 'min-width' as the computed value for 'width'.
  276. if (!computed_values.min_width().is_auto()) {
  277. auto min_width = calculate_inner_width(box, remaining_available_space.width, computed_values.min_width());
  278. auto used_width_px = used_width.is_auto() ? remaining_available_space.width : AvailableSize::make_definite(used_width.to_px(box));
  279. if (used_width_px < min_width) {
  280. used_width = try_compute_width(CSS::Length::make_px(min_width));
  281. }
  282. }
  283. if (!box_is_sized_as_replaced_element(box) && !used_width.is_auto())
  284. box_state.set_content_width(used_width.to_px(box));
  285. box_state.margin_left = margin_left.to_px(box);
  286. box_state.margin_right = margin_right.to_px(box);
  287. }
  288. void BlockFormattingContext::compute_width_for_floating_box(Box const& box, AvailableSpace const& available_space)
  289. {
  290. // 10.3.5 Floating, non-replaced elements
  291. auto& computed_values = box.computed_values();
  292. auto zero_value = CSS::Length::make_px(0);
  293. auto width_of_containing_block = available_space.width.to_px_or_zero();
  294. auto margin_left = computed_values.margin().left().resolved(box, width_of_containing_block);
  295. auto margin_right = computed_values.margin().right().resolved(box, width_of_containing_block);
  296. // If 'margin-left', or 'margin-right' are computed as 'auto', their used value is '0'.
  297. if (margin_left.is_auto())
  298. margin_left = zero_value;
  299. if (margin_right.is_auto())
  300. margin_right = zero_value;
  301. auto& box_state = m_state.get_mutable(box);
  302. box_state.padding_left = computed_values.padding().left().resolved(box, width_of_containing_block).to_px(box);
  303. box_state.padding_right = computed_values.padding().right().resolved(box, width_of_containing_block).to_px(box);
  304. box_state.margin_left = margin_left.to_px(box);
  305. box_state.margin_right = margin_right.to_px(box);
  306. box_state.border_left = computed_values.border_left().width;
  307. box_state.border_right = computed_values.border_right().width;
  308. auto compute_width = [&](auto width) {
  309. // If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.
  310. if (width.is_auto()) {
  311. auto result = calculate_shrink_to_fit_widths(box);
  312. if (available_space.width.is_definite()) {
  313. // Find the available width: in this case, this is the width of the containing
  314. // block minus the used values of 'margin-left', 'border-left-width', 'padding-left',
  315. // 'padding-right', 'border-right-width', 'margin-right', and the widths of any relevant scroll bars.
  316. auto available_width = available_space.width.to_px_or_zero()
  317. - margin_left.to_px(box) - computed_values.border_left().width - box_state.padding_left
  318. - box_state.padding_right - computed_values.border_right().width - margin_right.to_px(box);
  319. // Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width).
  320. width = CSS::Length::make_px(min(max(result.preferred_minimum_width, available_width), result.preferred_width));
  321. } else if (available_space.width.is_indefinite() || available_space.width.is_max_content()) {
  322. // Fold the formula for shrink-to-fit width for indefinite and max-content available width.
  323. width = CSS::Length::make_px(result.preferred_width);
  324. } else {
  325. // Fold the formula for shrink-to-fit width for min-content available width.
  326. width = CSS::Length::make_px(min(result.preferred_minimum_width, result.preferred_width));
  327. }
  328. }
  329. return width;
  330. };
  331. auto input_width = [&] {
  332. if (should_treat_width_as_auto(box, available_space))
  333. return CSS::Length::make_auto();
  334. return CSS::Length::make_px(calculate_inner_width(box, available_space.width, computed_values.width()));
  335. }();
  336. // 1. The tentative used width is calculated (without 'min-width' and 'max-width')
  337. auto width = compute_width(input_width);
  338. // 2. The tentative used width is greater than 'max-width', the rules above are applied again,
  339. // but this time using the computed value of 'max-width' as the computed value for 'width'.
  340. if (!should_treat_max_width_as_none(box, available_space.width)) {
  341. auto max_width = calculate_inner_width(box, available_space.width, computed_values.max_width());
  342. if (width.to_px(box) > max_width)
  343. width = compute_width(CSS::Length::make_px(max_width));
  344. }
  345. // 3. If the resulting width is smaller than 'min-width', the rules above are applied again,
  346. // but this time using the value of 'min-width' as the computed value for 'width'.
  347. if (!computed_values.min_width().is_auto()) {
  348. auto min_width = calculate_inner_width(box, available_space.width, computed_values.min_width());
  349. if (width.to_px(box) < min_width)
  350. width = compute_width(CSS::Length::make_px(min_width));
  351. }
  352. box_state.set_content_width(width.to_px(box));
  353. }
  354. void BlockFormattingContext::compute_width_for_block_level_replaced_element_in_normal_flow(Box const& box, AvailableSpace const& available_space)
  355. {
  356. // 10.3.6 Floating, replaced elements
  357. auto& computed_values = box.computed_values();
  358. auto zero_value = CSS::Length::make_px(0);
  359. auto width_of_containing_block = available_space.width.to_px_or_zero();
  360. // 10.3.4 Block-level, replaced elements in normal flow
  361. // The used value of 'width' is determined as for inline replaced elements. Then the rules for
  362. // non-replaced block-level elements are applied to determine the margins.
  363. auto margin_left = computed_values.margin().left().resolved(box, width_of_containing_block);
  364. auto margin_right = computed_values.margin().right().resolved(box, width_of_containing_block);
  365. auto const padding_left = computed_values.padding().left().resolved(box, width_of_containing_block).to_px(box);
  366. auto const padding_right = computed_values.padding().right().resolved(box, width_of_containing_block).to_px(box);
  367. // If 'margin-left', or 'margin-right' are computed as 'auto', their used value is '0'.
  368. if (margin_left.is_auto())
  369. margin_left = zero_value;
  370. if (margin_right.is_auto())
  371. margin_right = zero_value;
  372. auto& box_state = m_state.get_mutable(box);
  373. box_state.set_content_width(compute_width_for_replaced_element(box, available_space));
  374. box_state.margin_left = margin_left.to_px(box);
  375. box_state.margin_right = margin_right.to_px(box);
  376. box_state.border_left = computed_values.border_left().width;
  377. box_state.border_right = computed_values.border_right().width;
  378. box_state.padding_left = padding_left;
  379. box_state.padding_right = padding_right;
  380. }
  381. void BlockFormattingContext::resolve_used_height_if_not_treated_as_auto(Box const& box, AvailableSpace const& available_space)
  382. {
  383. if (should_treat_height_as_auto(box, available_space)) {
  384. return;
  385. }
  386. auto const& computed_values = box.computed_values();
  387. auto& box_state = m_state.get_mutable(box);
  388. auto height = calculate_inner_height(box, available_space, box.computed_values().height());
  389. if (!should_treat_max_height_as_none(box, available_space.height)) {
  390. if (!computed_values.max_height().is_auto()) {
  391. auto max_height = calculate_inner_height(box, available_space, computed_values.max_height());
  392. height = min(height, max_height);
  393. }
  394. }
  395. if (!computed_values.min_height().is_auto()) {
  396. height = max(height, calculate_inner_height(box, available_space, computed_values.min_height()));
  397. }
  398. box_state.set_content_height(height);
  399. box_state.set_has_definite_height(true);
  400. }
  401. void BlockFormattingContext::resolve_used_height_if_treated_as_auto(Box const& box, AvailableSpace const& available_space, FormattingContext const* box_formatting_context)
  402. {
  403. if (!should_treat_height_as_auto(box, available_space)) {
  404. return;
  405. }
  406. auto const& computed_values = box.computed_values();
  407. auto& box_state = m_state.get_mutable(box);
  408. CSSPixels height = 0;
  409. if (box_is_sized_as_replaced_element(box)) {
  410. height = compute_height_for_replaced_element(box, available_space);
  411. } else {
  412. if (box_formatting_context) {
  413. height = box_formatting_context->automatic_content_height();
  414. } else {
  415. height = compute_auto_height_for_block_level_element(box, m_state.get(box).available_inner_space_or_constraints_from(available_space));
  416. }
  417. }
  418. if (!should_treat_max_height_as_none(box, available_space.height)) {
  419. if (!computed_values.max_height().is_auto()) {
  420. auto max_height = calculate_inner_height(box, available_space, computed_values.max_height());
  421. height = min(height, max_height);
  422. }
  423. }
  424. if (!computed_values.min_height().is_auto()) {
  425. height = max(height, calculate_inner_height(box, available_space, computed_values.min_height()));
  426. }
  427. if (box.document().in_quirks_mode()
  428. && box.dom_node()
  429. && box.dom_node()->is_html_html_element()
  430. && box.computed_values().height().is_auto()) {
  431. // 3.6. The html element fills the viewport quirk
  432. // https://quirks.spec.whatwg.org/#the-html-element-fills-the-viewport-quirk
  433. // FIXME: Handle vertical writing mode.
  434. // 1. Let margins be sum of the used values of the margin-left and margin-right properties of element
  435. // if element has a vertical writing mode, otherwise let margins be the sum of the used values of
  436. // the margin-top and margin-bottom properties of element.
  437. auto margins = box_state.margin_top + box_state.margin_bottom;
  438. // 2. Let size be the size of the initial containing block in the block flow direction minus margins.
  439. auto size = box_state.containing_block_used_values()->content_height() - margins;
  440. // 3. Return the bigger value of size and the normal border box size the element would have
  441. // according to the CSS specification.
  442. height = max(size, height);
  443. // NOTE: The height of the root element when affected by this quirk is considered to be definite.
  444. box_state.set_has_definite_height(true);
  445. }
  446. box_state.set_content_height(height);
  447. }
  448. void BlockFormattingContext::layout_inline_children(BlockContainer const& block_container, AvailableSpace const& available_space)
  449. {
  450. VERIFY(block_container.children_are_inline());
  451. auto& block_container_state = m_state.get_mutable(block_container);
  452. InlineFormattingContext context(m_state, m_layout_mode, block_container, block_container_state, *this);
  453. context.run(available_space);
  454. if (!block_container_state.has_definite_width()) {
  455. // NOTE: min-width or max-width for boxes with inline children can only be applied after inside layout
  456. // is done and width of box content is known
  457. auto used_width_px = context.automatic_content_width();
  458. // https://www.w3.org/TR/css-sizing-3/#sizing-values
  459. // Percentages are resolved against the width/height, as appropriate, of the box’s containing block.
  460. auto containing_block_width = m_state.get(*block_container.containing_block()).content_width();
  461. auto available_width = AvailableSize::make_definite(containing_block_width);
  462. if (!should_treat_max_width_as_none(block_container, available_space.width)) {
  463. auto max_width_px = calculate_inner_width(block_container, available_width, block_container.computed_values().max_width());
  464. if (used_width_px > max_width_px)
  465. used_width_px = max_width_px;
  466. }
  467. auto should_treat_min_width_as_auto = [&] {
  468. auto const& available_width = available_space.width;
  469. auto const& min_width = block_container.computed_values().min_width();
  470. if (min_width.is_auto())
  471. return true;
  472. if (min_width.is_fit_content() && available_width.is_intrinsic_sizing_constraint())
  473. return true;
  474. if (min_width.is_max_content() && available_width.is_max_content())
  475. return true;
  476. if (min_width.is_min_content() && available_width.is_min_content())
  477. return true;
  478. return false;
  479. }();
  480. if (!should_treat_min_width_as_auto) {
  481. auto min_width_px = calculate_inner_width(block_container, available_width, block_container.computed_values().min_width());
  482. if (used_width_px < min_width_px)
  483. used_width_px = min_width_px;
  484. }
  485. block_container_state.set_content_width(used_width_px);
  486. block_container_state.set_content_height(context.automatic_content_height());
  487. }
  488. }
  489. CSSPixels BlockFormattingContext::compute_auto_height_for_block_level_element(Box const& box, AvailableSpace const& available_space)
  490. {
  491. if (creates_block_formatting_context(box)) {
  492. return compute_auto_height_for_block_formatting_context_root(box);
  493. }
  494. auto const& box_state = m_state.get(box);
  495. auto display = box.display();
  496. if (display.is_flex_inside()) {
  497. // https://drafts.csswg.org/css-flexbox-1/#algo-main-container
  498. // NOTE: The automatic block size of a block-level flex container is its max-content size.
  499. return calculate_max_content_height(box, available_space.width.to_px_or_zero());
  500. }
  501. if (display.is_grid_inside()) {
  502. // https://www.w3.org/TR/css-grid-2/#intrinsic-sizes
  503. // In both inline and block formatting contexts, the grid container’s auto block size is its
  504. // max-content size.
  505. return calculate_max_content_height(box, available_space.width.to_px_or_zero());
  506. }
  507. if (display.is_table_inside()) {
  508. return calculate_max_content_height(box, available_space.width.to_px_or_zero());
  509. }
  510. // https://www.w3.org/TR/CSS22/visudet.html#normal-block
  511. // 10.6.3 Block-level non-replaced elements in normal flow when 'overflow' computes to 'visible'
  512. // The element's height is the distance from its top content edge to the first applicable of the following:
  513. // 1. the bottom edge of the last line box, if the box establishes a inline formatting context with one or more lines
  514. if (box.children_are_inline() && !box_state.line_boxes.is_empty())
  515. return box_state.line_boxes.last().bottom();
  516. // 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
  517. // 3. the bottom border edge of the last in-flow child whose top margin doesn't collapse with the element's bottom margin
  518. if (!box.children_are_inline()) {
  519. for (auto* child_box = box.last_child_of_type<Box>(); child_box; child_box = child_box->previous_sibling_of_type<Box>()) {
  520. if (child_box->is_absolutely_positioned() || child_box->is_floating())
  521. continue;
  522. // FIXME: This is hack. If the last child is a list-item marker box, we ignore it for purposes of height calculation.
  523. // Perhaps markers should not be considered in-flow(?) Perhaps they should always be the first child of the list-item
  524. // box instead of the last child.
  525. if (child_box->is_list_item_marker_box())
  526. continue;
  527. auto const& child_box_state = m_state.get(*child_box);
  528. if (margins_collapse_through(*child_box, m_state))
  529. continue;
  530. auto margin_bottom = m_margin_state.current_collapsed_margin();
  531. if (box_state.padding_bottom == 0 && box_state.border_bottom == 0) {
  532. m_margin_state.box_last_in_flow_child_margin_bottom_collapsed = true;
  533. margin_bottom = 0;
  534. }
  535. return max(CSSPixels(0), child_box_state.offset.y() + child_box_state.content_height() + child_box_state.border_box_bottom() + margin_bottom);
  536. }
  537. }
  538. // 4. zero, otherwise
  539. return 0;
  540. }
  541. static CSSPixels containing_block_height_to_resolve_percentage_in_quirks_mode(Box const& box, LayoutState const& state)
  542. {
  543. // https://quirks.spec.whatwg.org/#the-percentage-height-calculation-quirk
  544. auto const* containing_block = box.containing_block();
  545. while (containing_block) {
  546. // 1. Let element be the nearest ancestor containing block of element, if there is one.
  547. // Otherwise, return the initial containing block.
  548. if (containing_block->is_viewport()) {
  549. return state.get(*containing_block).content_height();
  550. }
  551. // 2. If element has a computed value of the display property that is table-cell, then return a
  552. // UA-defined value.
  553. if (containing_block->display().is_table_cell()) {
  554. // FIXME: Likely UA-defined value should not be 0.
  555. return 0;
  556. }
  557. // 3. If element has a computed value of the height property that is not auto, then return element.
  558. if (!containing_block->computed_values().height().is_auto()) {
  559. return state.get(*containing_block).content_height();
  560. }
  561. // 4. If element has a computed value of the position property that is absolute, or if element is a
  562. // not a block container or a table wrapper box, then return element.
  563. if (containing_block->is_absolutely_positioned() || !is<BlockContainer>(*containing_block) || is<TableWrapper>(*containing_block)) {
  564. return state.get(*containing_block).content_height();
  565. }
  566. // 5. Jump to the first step.
  567. containing_block = containing_block->containing_block();
  568. }
  569. VERIFY_NOT_REACHED();
  570. }
  571. void BlockFormattingContext::layout_block_level_box(Box const& box, BlockContainer const& block_container, CSSPixels& bottom_of_lowest_margin_box, AvailableSpace const& available_space)
  572. {
  573. auto& box_state = m_state.get_mutable(box);
  574. if (box.is_absolutely_positioned()) {
  575. StaticPositionRect static_position;
  576. auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
  577. static_position.rect = { offset_to_static_parent.location().translated(0, m_y_offset_of_current_block_container.value()), { 0, 0 } };
  578. box_state.set_static_position_rect(static_position);
  579. return;
  580. }
  581. // NOTE: ListItemMarkerBoxes are placed by their corresponding ListItemBox.
  582. if (is<ListItemMarkerBox>(box))
  583. return;
  584. resolve_vertical_box_model_metrics(box, m_state.get(block_container).content_width());
  585. if (box.is_floating()) {
  586. auto const y = m_y_offset_of_current_block_container.value();
  587. auto margin_top = !m_margin_state.has_block_container_waiting_for_final_y_position() ? m_margin_state.current_collapsed_margin() : 0;
  588. layout_floating_box(box, block_container, available_space, margin_top + y);
  589. bottom_of_lowest_margin_box = max(bottom_of_lowest_margin_box, box_state.offset.y() + box_state.content_height() + box_state.margin_box_bottom());
  590. return;
  591. }
  592. m_margin_state.add_margin(box_state.margin_top);
  593. auto introduce_clearance = clear_floating_boxes(box, {});
  594. if (introduce_clearance == DidIntroduceClearance::Yes)
  595. m_margin_state.reset();
  596. auto const y = m_y_offset_of_current_block_container.value();
  597. auto box_is_html_element_in_quirks_mode = box.document().in_quirks_mode()
  598. && box.dom_node()
  599. && box.dom_node()->is_html_html_element()
  600. && box.computed_values().height().is_auto();
  601. // NOTE: In quirks mode, the html element's height matches the viewport so it can be treated as definite
  602. if (box_state.has_definite_height() || box_is_html_element_in_quirks_mode) {
  603. resolve_used_height_if_treated_as_auto(box, available_space);
  604. }
  605. auto independent_formatting_context = create_independent_formatting_context_if_needed(m_state, m_layout_mode, box);
  606. // NOTE: It is possible to encounter SVGMaskBox nodes while doing layout of formatting context established by <foreignObject> with a mask.
  607. // We should skip and let SVGFormattingContext take care of them.
  608. if (box.is_svg_mask_box())
  609. return;
  610. if (!independent_formatting_context && !is<BlockContainer>(box)) {
  611. dbgln("FIXME: Block-level box is not BlockContainer but does not create formatting context: {}", box.debug_description());
  612. return;
  613. }
  614. m_margin_state.update_block_waiting_for_final_y_position();
  615. CSSPixels margin_top = m_margin_state.current_collapsed_margin();
  616. if (m_margin_state.has_block_container_waiting_for_final_y_position()) {
  617. // If first child margin top will collapse with margin-top of containing block then margin-top of child is 0
  618. margin_top = 0;
  619. }
  620. if (independent_formatting_context) {
  621. // Margins of elements that establish new formatting contexts do not collapse with their in-flow children
  622. m_margin_state.reset();
  623. }
  624. place_block_level_element_in_normal_flow_vertically(box, y + margin_top);
  625. compute_width(box, available_space);
  626. place_block_level_element_in_normal_flow_horizontally(box, available_space);
  627. AvailableSpace available_space_for_height_resolution = available_space;
  628. auto is_grid_or_flex_container = box.display().is_grid_inside() || box.display().is_flex_inside();
  629. auto is_table_box = box.display().is_table_row() || box.display().is_table_row_group() || box.display().is_table_header_group() || box.display().is_table_footer_group() || box.display().is_table_cell() || box.display().is_table_caption();
  630. // NOTE: Spec doesn't mention this but quirk application needs to be skipped for grid and flex containers.
  631. // See https://github.com/w3c/csswg-drafts/issues/5545
  632. if (box.document().in_quirks_mode() && box.computed_values().height().is_percentage() && !is_table_box && !is_grid_or_flex_container) {
  633. // In quirks mode, for the purpose of calculating the height of an element, if the
  634. // computed value of the position property of element is relative or static, the specified value
  635. // for the height property of element is a <percentage>, and element does not have a computed
  636. // value of the display property that is table-row, table-row-group, table-header-group,
  637. // table-footer-group, table-cell or table-caption, the containing block of element must be
  638. // calculated using the following algorithm, aborting on the first step that returns a value:
  639. auto height = containing_block_height_to_resolve_percentage_in_quirks_mode(box, m_state);
  640. available_space_for_height_resolution.height = AvailableSize::make_definite(height);
  641. }
  642. resolve_used_height_if_not_treated_as_auto(box, available_space_for_height_resolution);
  643. // NOTE: Flex containers with `auto` height are treated as `max-content`, so we can compute their height early.
  644. if (box.is_replaced_box() || box.display().is_flex_inside()) {
  645. resolve_used_height_if_treated_as_auto(box, available_space_for_height_resolution);
  646. }
  647. // Before we insert the children of a list item we need to know the location of the marker.
  648. // If we do not do this then left-floating elements inside the list item will push the marker to the right,
  649. // in some cases even causing it to overlap with the non-floating content of the list.
  650. CSSPixels left_space_before_children_formatted;
  651. if (is<ListItemBox>(box)) {
  652. auto const& li_box = static_cast<ListItemBox const&>(box);
  653. // We need to ensure that our height and width are final before we calculate our left offset.
  654. // Otherwise, the y at which we calculate the intrusion by floats might be incorrect.
  655. ensure_sizes_correct_for_left_offset_calculation(li_box);
  656. auto const& list_item_state = m_state.get(li_box);
  657. auto const& marker_state = m_state.get(*li_box.marker());
  658. auto offset_y = max(CSSPixels(0), (li_box.marker()->computed_values().line_height() - marker_state.content_height()) / 2);
  659. auto space_used_before_children_formatted = intrusion_by_floats_into_box(list_item_state, offset_y);
  660. left_space_before_children_formatted = space_used_before_children_formatted.left;
  661. }
  662. if (independent_formatting_context) {
  663. // This box establishes a new formatting context. Pass control to it.
  664. independent_formatting_context->run(box_state.available_inner_space_or_constraints_from(available_space));
  665. } else {
  666. // This box participates in the current block container's flow.
  667. if (box.children_are_inline()) {
  668. layout_inline_children(verify_cast<BlockContainer>(box), box_state.available_inner_space_or_constraints_from(available_space));
  669. } else {
  670. if (box_state.border_top > 0 || box_state.padding_top > 0) {
  671. // margin-top of block container can't collapse with it's children if it has non zero border or padding
  672. m_margin_state.reset();
  673. } else if (!m_margin_state.has_block_container_waiting_for_final_y_position()) {
  674. // margin-top of block container can be updated during children layout hence it's final y position yet to be determined
  675. m_margin_state.register_block_container_y_position_update_callback([&, introduce_clearance](CSSPixels margin_top) {
  676. if (introduce_clearance == DidIntroduceClearance::No) {
  677. place_block_level_element_in_normal_flow_vertically(box, margin_top + y);
  678. }
  679. });
  680. }
  681. layout_block_level_children(verify_cast<BlockContainer>(box), box_state.available_inner_space_or_constraints_from(available_space));
  682. }
  683. }
  684. // Tables already set their height during the independent formatting context run. When multi-line text cells are involved, using different
  685. // available space here than during the independent formatting context run can result in different line breaks and thus a different height.
  686. if (!box.display().is_table_inside()) {
  687. resolve_used_height_if_treated_as_auto(box, available_space_for_height_resolution, independent_formatting_context);
  688. }
  689. if (independent_formatting_context || !margins_collapse_through(box, m_state)) {
  690. if (!m_margin_state.box_last_in_flow_child_margin_bottom_collapsed) {
  691. m_margin_state.reset();
  692. }
  693. m_y_offset_of_current_block_container = box_state.offset.y() + box_state.content_height() + box_state.border_box_bottom();
  694. }
  695. m_margin_state.box_last_in_flow_child_margin_bottom_collapsed = false;
  696. m_margin_state.add_margin(box_state.margin_bottom);
  697. m_margin_state.update_block_waiting_for_final_y_position();
  698. auto const& block_container_state = m_state.get(block_container);
  699. compute_inset(box, content_box_rect(block_container_state).size());
  700. // Now that our children are formatted we place the ListItemBox with the left space we remembered.
  701. if (is<ListItemBox>(box)) {
  702. layout_list_item_marker(static_cast<ListItemBox const&>(box), left_space_before_children_formatted);
  703. }
  704. bottom_of_lowest_margin_box = max(bottom_of_lowest_margin_box, box_state.offset.y() + box_state.content_height() + box_state.margin_box_bottom());
  705. if (independent_formatting_context)
  706. independent_formatting_context->parent_context_did_dimension_child_root_box();
  707. }
  708. void BlockFormattingContext::layout_block_level_children(BlockContainer const& block_container, AvailableSpace const& available_space)
  709. {
  710. VERIFY(!block_container.children_are_inline());
  711. CSSPixels bottom_of_lowest_margin_box = 0;
  712. TemporaryChange<Optional<CSSPixels>> change { m_y_offset_of_current_block_container, CSSPixels(0) };
  713. block_container.for_each_child_of_type<Box>([&](Box& box) {
  714. layout_block_level_box(box, block_container, bottom_of_lowest_margin_box, available_space);
  715. return IterationDecision::Continue;
  716. });
  717. m_margin_state.block_container_y_position_update_callback = {};
  718. if (m_layout_mode == LayoutMode::IntrinsicSizing) {
  719. auto& block_container_state = m_state.get_mutable(block_container);
  720. if (!block_container_state.has_definite_width()) {
  721. auto width = greatest_child_width(block_container);
  722. auto const& computed_values = block_container.computed_values();
  723. // NOTE: Min and max constraints are not applied to a box that is being sized as intrinsic because
  724. // according to css-sizing-3 spec:
  725. // The min-content size of a box in each axis is the size it would have if it was a float given an
  726. // auto size in that axis (and no minimum or maximum size in that axis) and if its containing block
  727. // was zero-sized in that axis.
  728. if (block_container_state.width_constraint == SizeConstraint::None) {
  729. if (!should_treat_max_width_as_none(block_container, available_space.width)) {
  730. auto max_width = calculate_inner_width(block_container, available_space.width,
  731. computed_values.max_width());
  732. width = min(width, max_width);
  733. }
  734. if (!computed_values.min_width().is_auto()) {
  735. auto min_width = calculate_inner_width(block_container, available_space.width,
  736. computed_values.min_width());
  737. width = max(width, min_width);
  738. }
  739. }
  740. block_container_state.set_content_width(width);
  741. block_container_state.set_content_height(bottom_of_lowest_margin_box);
  742. }
  743. }
  744. }
  745. void BlockFormattingContext::resolve_vertical_box_model_metrics(Box const& box, CSSPixels width_of_containing_block)
  746. {
  747. auto& box_state = m_state.get_mutable(box);
  748. auto const& computed_values = box.computed_values();
  749. box_state.margin_top = computed_values.margin().top().to_px(box, width_of_containing_block);
  750. box_state.margin_bottom = computed_values.margin().bottom().to_px(box, width_of_containing_block);
  751. box_state.border_top = computed_values.border_top().width;
  752. box_state.border_bottom = computed_values.border_bottom().width;
  753. box_state.padding_top = computed_values.padding().top().to_px(box, width_of_containing_block);
  754. box_state.padding_bottom = computed_values.padding().bottom().to_px(box, width_of_containing_block);
  755. }
  756. CSSPixels BlockFormattingContext::BlockMarginState::current_collapsed_margin() const
  757. {
  758. return current_positive_collapsible_margin + current_negative_collapsible_margin;
  759. }
  760. BlockFormattingContext::DidIntroduceClearance BlockFormattingContext::clear_floating_boxes(Node const& child_box, Optional<InlineFormattingContext&> inline_formatting_context)
  761. {
  762. auto const& computed_values = child_box.computed_values();
  763. auto result = DidIntroduceClearance::No;
  764. auto clear_floating_boxes = [&](FloatSideData& float_side) {
  765. if (!float_side.current_boxes.is_empty()) {
  766. // NOTE: Floating boxes are globally relevant within this BFC, *but* their offset coordinates
  767. // are relative to their containing block.
  768. // This means that we have to first convert to a root-space Y coordinate before clearing,
  769. // and then convert back to a local Y coordinate when assigning the cleared offset to
  770. // the `child_box` layout state.
  771. // First, find the lowest margin box edge on this float side and calculate the Y offset just below it.
  772. CSSPixels clearance_y_in_root = 0;
  773. for (auto const& floating_box : float_side.current_boxes) {
  774. auto floating_box_rect_in_root = margin_box_rect_in_ancestor_coordinate_space(floating_box.used_values, root());
  775. clearance_y_in_root = max(clearance_y_in_root, floating_box_rect_in_root.bottom());
  776. }
  777. // Then, convert the clearance Y to a coordinate relative to the containing block of `child_box`.
  778. CSSPixels clearance_y_in_containing_block = clearance_y_in_root;
  779. for (auto* containing_block = child_box.containing_block(); containing_block && containing_block != &root(); containing_block = containing_block->containing_block())
  780. clearance_y_in_containing_block -= m_state.get(*containing_block).offset.y();
  781. if (inline_formatting_context.has_value()) {
  782. if (clearance_y_in_containing_block > inline_formatting_context->vertical_float_clearance()) {
  783. result = DidIntroduceClearance::Yes;
  784. inline_formatting_context->set_vertical_float_clearance(clearance_y_in_containing_block);
  785. }
  786. } else if (clearance_y_in_containing_block > m_y_offset_of_current_block_container.value()) {
  787. result = DidIntroduceClearance::Yes;
  788. m_y_offset_of_current_block_container = clearance_y_in_containing_block;
  789. }
  790. float_side.clear();
  791. }
  792. };
  793. if (computed_values.clear() == CSS::Clear::Left || computed_values.clear() == CSS::Clear::Both)
  794. clear_floating_boxes(m_left_floats);
  795. if (computed_values.clear() == CSS::Clear::Right || computed_values.clear() == CSS::Clear::Both)
  796. clear_floating_boxes(m_right_floats);
  797. return result;
  798. }
  799. void BlockFormattingContext::place_block_level_element_in_normal_flow_vertically(Box const& child_box, CSSPixels y)
  800. {
  801. auto& box_state = m_state.get_mutable(child_box);
  802. y += box_state.border_box_top();
  803. box_state.set_content_offset(CSSPixelPoint { box_state.offset.x(), y });
  804. }
  805. // Returns whether the given box has the given ancestor on the path to root, ignoring the anonymous blocks.
  806. static bool box_has_ancestor_in_non_anonymous_containing_block_chain(Box const* box, Box const& ancestor, Box const& root)
  807. {
  808. Box const* current_ancestor = box ? box->non_anonymous_containing_block() : &root;
  809. while (current_ancestor != &root) {
  810. if (current_ancestor == &ancestor)
  811. return true;
  812. current_ancestor = current_ancestor->non_anonymous_containing_block();
  813. }
  814. return false;
  815. }
  816. void BlockFormattingContext::place_block_level_element_in_normal_flow_horizontally(Box const& child_box, AvailableSpace const& available_space)
  817. {
  818. auto& box_state = m_state.get_mutable(child_box);
  819. CSSPixels x = 0;
  820. CSSPixels available_width_within_containing_block = available_space.width.to_px_or_zero();
  821. if ((!m_left_floats.current_boxes.is_empty() || !m_right_floats.current_boxes.is_empty())
  822. && creates_block_formatting_context(child_box)) {
  823. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(box_state, root());
  824. auto space_and_containing_margin = space_used_and_containing_margin_for_floats(box_in_root_rect.y());
  825. available_width_within_containing_block -= space_and_containing_margin.left_used_space + space_and_containing_margin.right_used_space;
  826. auto const& containing_box_state = m_state.get(*child_box.containing_block());
  827. if (box_has_ancestor_in_non_anonymous_containing_block_chain(space_and_containing_margin.matching_left_float_box, *child_box.non_anonymous_containing_block(), root()))
  828. x = space_and_containing_margin.left_used_space;
  829. else
  830. // If the floating box doesn't share a containing block with the child box, the child box margin should overlap with the width of the floating box.
  831. x = max(space_and_containing_margin.left_used_space - containing_box_state.margin_left, 0);
  832. }
  833. if (child_box.containing_block()->computed_values().text_align() == CSS::TextAlign::LibwebCenter) {
  834. x += (available_width_within_containing_block / 2) - box_state.content_width() / 2;
  835. } else if (child_box.containing_block()->computed_values().text_align() == CSS::TextAlign::LibwebRight) {
  836. // Subtracting the left margin here because left and right margins need to be swapped when aligning to the right
  837. x += available_width_within_containing_block - box_state.content_width() - box_state.margin_box_left();
  838. } else {
  839. x += box_state.margin_box_left();
  840. }
  841. box_state.set_content_offset({ x, box_state.offset.y() });
  842. }
  843. void BlockFormattingContext::layout_viewport(AvailableSpace const& available_space)
  844. {
  845. // NOTE: If we are laying out a standalone SVG document, we give it some special treatment:
  846. // The root <svg> container gets the same size as the viewport,
  847. // and we call directly into the SVG layout code from here.
  848. if (root().first_child() && root().first_child()->is_svg_svg_box()) {
  849. auto const& svg_root = verify_cast<SVGSVGBox>(*root().first_child());
  850. auto content_height = m_state.get(*svg_root.containing_block()).content_height();
  851. m_state.get_mutable(svg_root).set_content_height(content_height);
  852. auto svg_formatting_context = create_independent_formatting_context_if_needed(m_state, m_layout_mode, svg_root);
  853. svg_formatting_context->run(available_space);
  854. } else {
  855. if (root().children_are_inline())
  856. layout_inline_children(root(), available_space);
  857. else
  858. layout_block_level_children(root(), available_space);
  859. }
  860. }
  861. void BlockFormattingContext::layout_floating_box(Box const& box, BlockContainer const& block_container, AvailableSpace const& available_space, CSSPixels y, LineBuilder* line_builder)
  862. {
  863. VERIFY(box.is_floating());
  864. auto& box_state = m_state.get_mutable(box);
  865. auto const& computed_values = box.computed_values();
  866. auto const& block_container_state = m_state.get(block_container);
  867. resolve_vertical_box_model_metrics(box, block_container_state.content_width());
  868. compute_width(box, available_space);
  869. resolve_used_height_if_not_treated_as_auto(box, available_space);
  870. // NOTE: Flex containers with `auto` height are treated as `max-content`, so we can compute their height early.
  871. if (box.is_replaced_box() || box.display().is_flex_inside()) {
  872. resolve_used_height_if_treated_as_auto(box, available_space);
  873. }
  874. auto independent_formatting_context = layout_inside(box, m_layout_mode, box_state.available_inner_space_or_constraints_from(available_space));
  875. resolve_used_height_if_treated_as_auto(box, available_space, independent_formatting_context);
  876. // First we place the box normally (to get the right y coordinate.)
  877. // If we have a LineBuilder, we're in the middle of inline layout, otherwise this is block layout.
  878. if (line_builder) {
  879. auto y = max(line_builder->y_for_float_to_be_inserted_here(box), line_builder->inline_formatting_context().vertical_float_clearance());
  880. box_state.set_content_y(y + box_state.margin_box_top());
  881. } else {
  882. place_block_level_element_in_normal_flow_vertically(box, y + box_state.margin_top);
  883. place_block_level_element_in_normal_flow_horizontally(box, available_space);
  884. }
  885. // Then we float it to the left or right.
  886. auto float_box = [&](FloatSide side, FloatSideData& side_data, FloatSideData& other_side_data) {
  887. CSSPixels offset_from_edge = 0;
  888. auto float_to_edge = [&] {
  889. if (side == FloatSide::Left)
  890. offset_from_edge = box_state.margin_box_left();
  891. else
  892. offset_from_edge = box_state.content_width() + box_state.margin_box_right();
  893. };
  894. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(box_state, root());
  895. CSSPixels y_in_root = box_in_root_rect.y();
  896. CSSPixels y = box_state.offset.y();
  897. if (side_data.current_boxes.is_empty()) {
  898. // This is the first floating box on this side. Go all the way to the edge.
  899. float_to_edge();
  900. side_data.y_offset = 0;
  901. } else {
  902. // NOTE: If we're in inline layout, the LineBuilder has already provided the right Y offset.
  903. // In block layout, we adjust by the side's current Y offset here.
  904. if (!line_builder)
  905. y_in_root += side_data.y_offset;
  906. bool did_touch_preceding_float = false;
  907. bool did_place_next_to_preceding_float = false;
  908. // Walk all currently tracked floats on the side we're floating towards.
  909. // We're looking for the innermost preceding float that intersects vertically with `box`.
  910. for (auto& preceding_float : side_data.current_boxes.in_reverse()) {
  911. auto const preceding_float_rect = margin_box_rect_in_ancestor_coordinate_space(preceding_float.used_values, root());
  912. if (!preceding_float_rect.contains_vertically(y_in_root))
  913. continue;
  914. // We found a preceding float that intersects vertically with the current float.
  915. // Now we need to find out if there's enough inline-axis space to stack them next to each other.
  916. CSSPixels tentative_offset_from_edge = 0;
  917. bool fits_next_to_preceding_float = false;
  918. if (side == FloatSide::Left) {
  919. tentative_offset_from_edge = max(preceding_float.offset_from_edge + preceding_float.used_values.content_width() + preceding_float.used_values.margin_box_right(), 0) + box_state.margin_box_left();
  920. if (available_space.width.is_definite()) {
  921. fits_next_to_preceding_float = (tentative_offset_from_edge + box_state.content_width() + box_state.margin_box_right()) <= available_space.width.to_px_or_zero();
  922. } else if (available_space.width.is_max_content() || available_space.width.is_indefinite()) {
  923. fits_next_to_preceding_float = true;
  924. }
  925. } else {
  926. tentative_offset_from_edge = preceding_float.offset_from_edge + preceding_float.used_values.margin_box_left() + box_state.margin_box_right() + box_state.content_width();
  927. fits_next_to_preceding_float = tentative_offset_from_edge >= 0;
  928. }
  929. did_touch_preceding_float = true;
  930. if (!fits_next_to_preceding_float)
  931. break;
  932. offset_from_edge = tentative_offset_from_edge;
  933. did_place_next_to_preceding_float = true;
  934. break;
  935. }
  936. auto has_clearance = false;
  937. if (side == FloatSide::Left) {
  938. has_clearance = computed_values.clear() == CSS::Clear::Left || computed_values.clear() == CSS::Clear::Both;
  939. } else if (side == FloatSide::Right) {
  940. has_clearance = computed_values.clear() == CSS::Clear::Right || computed_values.clear() == CSS::Clear::Both;
  941. }
  942. if (!did_touch_preceding_float || !did_place_next_to_preceding_float || has_clearance) {
  943. // One of three things happened:
  944. // - This box does not touch another floating box.
  945. // - We ran out of horizontal space on this "float line", and need to break.
  946. // - This box has clearance.
  947. // Either way, we float this box all the way to the edge.
  948. float_to_edge();
  949. CSSPixels lowest_margin_edge = 0;
  950. for (auto const& current : side_data.current_boxes) {
  951. lowest_margin_edge = max(lowest_margin_edge, current.used_values.margin_box_height());
  952. }
  953. side_data.y_offset += lowest_margin_edge;
  954. // Also, forget all previous boxes floated to this side while since they're no longer relevant.
  955. side_data.clear();
  956. }
  957. }
  958. // NOTE: If we're in inline layout, the LineBuilder has already provided the right Y offset.
  959. // In block layout, we adjust by the side's current Y offset here.
  960. // FIXME: It's annoying that we have different behavior for inline vs block here.
  961. // Find a way to unify the behavior so we don't need to branch here.
  962. if (!line_builder)
  963. y += side_data.y_offset;
  964. auto top_margin_edge = y - box_state.margin_box_top();
  965. side_data.all_boxes.append(adopt_own(*new FloatingBox {
  966. .box = box,
  967. .used_values = box_state,
  968. .offset_from_edge = offset_from_edge,
  969. .top_margin_edge = top_margin_edge,
  970. .bottom_margin_edge = y + box_state.content_height() + box_state.margin_box_bottom(),
  971. }));
  972. side_data.current_boxes.append(*side_data.all_boxes.last());
  973. if (side == FloatSide::Left) {
  974. side_data.current_width = offset_from_edge + box_state.content_width() + box_state.margin_box_right();
  975. } else {
  976. side_data.current_width = offset_from_edge + box_state.margin_box_left();
  977. }
  978. side_data.max_width = max(side_data.current_width, side_data.max_width);
  979. // NOTE: We don't set the X position here, that happens later, once we know the root block width.
  980. // See parent_context_did_dimension_child_root_box() for that logic.
  981. box_state.set_content_y(y);
  982. // If the new box was inserted below the bottom of the opposite side,
  983. // we reset the other side back to its edge.
  984. if (top_margin_edge > other_side_data.y_offset)
  985. other_side_data.clear();
  986. };
  987. // Next, float to the left and/or right
  988. if (box.computed_values().float_() == CSS::Float::Left) {
  989. float_box(FloatSide::Left, m_left_floats, m_right_floats);
  990. } else if (box.computed_values().float_() == CSS::Float::Right) {
  991. float_box(FloatSide::Right, m_right_floats, m_left_floats);
  992. }
  993. m_state.get_mutable(root()).add_floating_descendant(box);
  994. if (line_builder)
  995. line_builder->recalculate_available_space();
  996. compute_inset(box, content_box_rect(block_container_state).size());
  997. if (independent_formatting_context)
  998. independent_formatting_context->parent_context_did_dimension_child_root_box();
  999. }
  1000. void BlockFormattingContext::ensure_sizes_correct_for_left_offset_calculation(ListItemBox const& list_item_box)
  1001. {
  1002. if (!list_item_box.marker())
  1003. return;
  1004. auto& marker = *list_item_box.marker();
  1005. auto& marker_state = m_state.get_mutable(marker);
  1006. CSSPixels image_width = 0;
  1007. CSSPixels image_height = 0;
  1008. if (auto const* list_style_image = marker.list_style_image()) {
  1009. image_width = list_style_image->natural_width().value_or(0);
  1010. image_height = list_style_image->natural_height().value_or(0);
  1011. }
  1012. auto default_marker_width = max(4, marker.first_available_font().pixel_size_rounded_up() - 4);
  1013. auto marker_text = marker.text().value_or("");
  1014. if (marker_text.is_empty()) {
  1015. marker_state.set_content_width(image_width + default_marker_width);
  1016. } else {
  1017. // FIXME: Use per-code-point fonts to measure text.
  1018. auto text_width = marker.first_available_font().width(marker_text);
  1019. marker_state.set_content_width(image_width + CSSPixels::nearest_value_for(text_width));
  1020. }
  1021. marker_state.set_content_height(max(image_height, marker.first_available_font().pixel_size_rounded_up() + 1));
  1022. }
  1023. void BlockFormattingContext::layout_list_item_marker(ListItemBox const& list_item_box, CSSPixels const& left_space_before_list_item_elements_formatted)
  1024. {
  1025. if (!list_item_box.marker())
  1026. return;
  1027. auto& marker = *list_item_box.marker();
  1028. auto& marker_state = m_state.get_mutable(marker);
  1029. auto& list_item_state = m_state.get_mutable(list_item_box);
  1030. auto default_marker_width = max(4, marker.first_available_font().pixel_size_rounded_up() - 4);
  1031. auto final_marker_width = marker_state.content_width() + default_marker_width;
  1032. if (marker.list_style_position() == CSS::ListStylePosition::Inside) {
  1033. list_item_state.set_content_offset({ final_marker_width, list_item_state.offset.y() });
  1034. list_item_state.set_content_width(list_item_state.content_width() - final_marker_width);
  1035. }
  1036. auto offset_y = max(CSSPixels(0), (marker.computed_values().line_height() - marker_state.content_height()) / 2);
  1037. marker_state.set_content_offset({ left_space_before_list_item_elements_formatted - final_marker_width, offset_y });
  1038. if (marker_state.content_height() > list_item_state.content_height())
  1039. list_item_state.set_content_height(marker_state.content_height());
  1040. }
  1041. BlockFormattingContext::SpaceUsedAndContainingMarginForFloats BlockFormattingContext::space_used_and_containing_margin_for_floats(CSSPixels y) const
  1042. {
  1043. SpaceUsedAndContainingMarginForFloats space_and_containing_margin;
  1044. for (auto const& floating_box_ptr : m_left_floats.all_boxes.in_reverse()) {
  1045. auto const& floating_box = *floating_box_ptr;
  1046. // NOTE: The floating box is *not* in the final horizontal position yet, but the size and vertical position is valid.
  1047. auto rect = margin_box_rect_in_ancestor_coordinate_space(floating_box.used_values, root());
  1048. if (rect.contains_vertically(y)) {
  1049. CSSPixels offset_from_containing_block_chain_margins_between_here_and_root = 0;
  1050. for (auto const* containing_block = floating_box.used_values.containing_block_used_values(); containing_block && &containing_block->node() != &root(); containing_block = containing_block->containing_block_used_values()) {
  1051. offset_from_containing_block_chain_margins_between_here_and_root += containing_block->margin_box_left();
  1052. }
  1053. space_and_containing_margin.left_used_space = floating_box.offset_from_edge
  1054. + floating_box.used_values.content_width()
  1055. + floating_box.used_values.margin_box_right();
  1056. space_and_containing_margin.left_total_containing_margin = offset_from_containing_block_chain_margins_between_here_and_root;
  1057. space_and_containing_margin.matching_left_float_box = floating_box.box;
  1058. break;
  1059. }
  1060. }
  1061. for (auto const& floating_box_ptr : m_right_floats.all_boxes.in_reverse()) {
  1062. auto const& floating_box = *floating_box_ptr;
  1063. // NOTE: The floating box is *not* in the final horizontal position yet, but the size and vertical position is valid.
  1064. auto rect = margin_box_rect_in_ancestor_coordinate_space(floating_box.used_values, root());
  1065. if (rect.contains_vertically(y)) {
  1066. CSSPixels offset_from_containing_block_chain_margins_between_here_and_root = 0;
  1067. for (auto const* containing_block = floating_box.used_values.containing_block_used_values(); containing_block && &containing_block->node() != &root(); containing_block = containing_block->containing_block_used_values()) {
  1068. offset_from_containing_block_chain_margins_between_here_and_root += containing_block->margin_box_right();
  1069. }
  1070. space_and_containing_margin.right_used_space = floating_box.offset_from_edge
  1071. + floating_box.used_values.margin_box_left();
  1072. space_and_containing_margin.right_total_containing_margin = offset_from_containing_block_chain_margins_between_here_and_root;
  1073. break;
  1074. }
  1075. }
  1076. return space_and_containing_margin;
  1077. }
  1078. FormattingContext::SpaceUsedByFloats BlockFormattingContext::intrusion_by_floats_into_box(Box const& box, CSSPixels y_in_box) const
  1079. {
  1080. return intrusion_by_floats_into_box(m_state.get(box), y_in_box);
  1081. }
  1082. FormattingContext::SpaceUsedByFloats BlockFormattingContext::intrusion_by_floats_into_box(LayoutState::UsedValues const& box_used_values, CSSPixels y_in_box) const
  1083. {
  1084. // NOTE: Floats are relative to the BFC root box, not necessarily the containing block of this IFC.
  1085. auto box_in_root_rect = content_box_rect_in_ancestor_coordinate_space(box_used_values, root());
  1086. CSSPixels y_in_root = box_in_root_rect.y() + y_in_box;
  1087. auto space_and_containing_margin = space_used_and_containing_margin_for_floats(y_in_root);
  1088. auto left_side_floats_limit_to_right = space_and_containing_margin.left_total_containing_margin + space_and_containing_margin.left_used_space;
  1089. auto right_side_floats_limit_to_right = space_and_containing_margin.right_used_space + space_and_containing_margin.right_total_containing_margin;
  1090. auto left_intrusion = max(CSSPixels(0), left_side_floats_limit_to_right - max(CSSPixels(0), box_in_root_rect.x()));
  1091. CSSPixels offset_from_containing_block_chain_margins_between_here_and_root = 0;
  1092. for (auto const* containing_block = &box_used_values; containing_block && &containing_block->node() != &root(); containing_block = containing_block->containing_block_used_values()) {
  1093. offset_from_containing_block_chain_margins_between_here_and_root = max(offset_from_containing_block_chain_margins_between_here_and_root, containing_block->margin_box_right());
  1094. }
  1095. auto right_intrusion = max(CSSPixels(0), right_side_floats_limit_to_right - offset_from_containing_block_chain_margins_between_here_and_root);
  1096. return { left_intrusion, right_intrusion };
  1097. }
  1098. CSSPixels BlockFormattingContext::greatest_child_width(Box const& box) const
  1099. {
  1100. // Similar to FormattingContext::greatest_child_width()
  1101. // but this one takes floats into account!
  1102. CSSPixels max_width = m_left_floats.max_width + m_right_floats.max_width;
  1103. if (box.children_are_inline()) {
  1104. for (auto const& line_box : m_state.get(verify_cast<BlockContainer>(box)).line_boxes) {
  1105. CSSPixels width_here = line_box.width();
  1106. CSSPixels extra_width_from_left_floats = 0;
  1107. for (auto& left_float : m_left_floats.all_boxes) {
  1108. // NOTE: Floats directly affect the automatic size of their containing block, but only indirectly anything above in the tree.
  1109. if (left_float->box->containing_block() != &box)
  1110. continue;
  1111. if (line_box.baseline() >= left_float->top_margin_edge || line_box.baseline() <= left_float->bottom_margin_edge) {
  1112. extra_width_from_left_floats = max(extra_width_from_left_floats, left_float->offset_from_edge + left_float->used_values.content_width() + left_float->used_values.margin_box_right());
  1113. }
  1114. }
  1115. CSSPixels extra_width_from_right_floats = 0;
  1116. for (auto& right_float : m_right_floats.all_boxes) {
  1117. // NOTE: Floats directly affect the automatic size of their containing block, but only indirectly anything above in the tree.
  1118. if (right_float->box->containing_block() != &box)
  1119. continue;
  1120. if (line_box.baseline() >= right_float->top_margin_edge || line_box.baseline() <= right_float->bottom_margin_edge) {
  1121. extra_width_from_right_floats = max(extra_width_from_right_floats, right_float->offset_from_edge + right_float->used_values.margin_box_left());
  1122. }
  1123. }
  1124. width_here += extra_width_from_left_floats + extra_width_from_right_floats;
  1125. max_width = max(max_width, width_here);
  1126. }
  1127. } else {
  1128. box.for_each_child_of_type<Box>([&](Box const& child) {
  1129. if (!child.is_absolutely_positioned())
  1130. max_width = max(max_width, m_state.get(child).margin_box_width());
  1131. return IterationDecision::Continue;
  1132. });
  1133. }
  1134. return max_width;
  1135. }
  1136. }