FlexFormattingContext.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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_offset(x, y);
  37. tallest_child_height = max(tallest_child_height, child_box.height());
  38. widest_child_width = max(widest_child_width, child_box.width());
  39. if (horizontal)
  40. x += child_box.margin_box_width();
  41. else
  42. y += child_box.margin_box_height();
  43. });
  44. // Then, compute the height of the entire flex container.
  45. // FIXME: This is not correct height calculation..
  46. if (horizontal) {
  47. box.set_height(tallest_child_height);
  48. box.set_width(x);
  49. } else {
  50. box.set_width(widest_child_width);
  51. box.set_height(y);
  52. }
  53. }
  54. }