FlexFormattingContext.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Layout/BlockBox.h>
  7. #include <LibWeb/Layout/Box.h>
  8. #include <LibWeb/Layout/FlexFormattingContext.h>
  9. namespace Web::Layout {
  10. FlexFormattingContext::FlexFormattingContext(Box& context_box, FormattingContext* parent)
  11. : FormattingContext(context_box, parent)
  12. {
  13. }
  14. FlexFormattingContext::~FlexFormattingContext()
  15. {
  16. }
  17. void FlexFormattingContext::run(Box& box, LayoutMode layout_mode)
  18. {
  19. // FIXME: This is *extremely* naive and only supports flex items laid out on a single line.
  20. auto flex_direction = box.computed_values().flex_direction();
  21. bool horizontal = flex_direction == CSS::FlexDirection::Row || flex_direction == CSS::FlexDirection::RowReverse;
  22. auto available_width = box.containing_block()->width();
  23. // First, compute the size of each flex item.
  24. box.for_each_child_of_type<Box>([&](Box& child_box) {
  25. auto shrink_to_fit_result = calculate_shrink_to_fit_widths(child_box);
  26. auto shrink_to_fit_width = min(max(shrink_to_fit_result.preferred_minimum_width, available_width), shrink_to_fit_result.preferred_width);
  27. child_box.set_width(shrink_to_fit_width);
  28. layout_inside(child_box, layout_mode);
  29. });
  30. // Then, place the items on a vertical or horizontal line.
  31. float x = 0;
  32. float y = 0;
  33. float tallest_child_height = 0;
  34. float widest_child_width = 0;
  35. box.for_each_child_of_type<Box>([&](Box& child_box) {
  36. child_box.set_flex_item(true);
  37. child_box.set_offset(x, y);
  38. tallest_child_height = max(tallest_child_height, child_box.height());
  39. widest_child_width = max(widest_child_width, child_box.width());
  40. if (horizontal)
  41. x += child_box.margin_box_width();
  42. else
  43. y += child_box.margin_box_height();
  44. });
  45. // Then, compute the height of the entire flex container.
  46. // FIXME: This is not correct height calculation..
  47. if (horizontal) {
  48. box.set_height(tallest_child_height);
  49. box.set_width(x);
  50. } else {
  51. box.set_width(widest_child_width);
  52. box.set_height(y);
  53. }
  54. }
  55. }