Truly independent web browser
LibWeb: Balance lines beside floats with text-wrap-style: balance
Andreas Kling3fece60908a3
diff --git a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rsindex 3bae03801e9..3b51e5f952a 100644--- a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs@@ -186,6 +186,24 @@ impl LaidOutBlockLevelBox {}}+/// The floats and margins of a block formatting context before finding where lines break changes them.+pub(crate) struct StateBeforeFindingLineBreaks {+ float_count: usize,+ bands: SmallVec<[FloatBand; 4]>,+ lowest_left_margin_edge: CssPixels,+ lowest_right_margin_edge: CssPixels,+ margin_state: BlockMarginState,+}++/// A float whose contents are laid out, which is yet to be positioned and placed.+pub(crate) struct FloatLaidOutAheadOfItsPosition {+ node: Node,+ placed_float: formatting_context::PlacedChild,+ pub(crate) cells: used_values::RootInputCells,+ laid_out_float_handed_back_by_its_run: Option<run_state::LaidOutChildBox>,+ fragment_arrival: Option<fragment_tree::ChildFragmentArrival>,+}+/// A box a block formatting context sizes, in cells the call laying the box out owns: the cells the context lays the/// box out in, or the cells it sizes a child in ahead of the child's layout.#[derive(Clone, Copy)]@@ -4753,13 +4771,41 @@ impl<'pass> BlockFormattingContext<'pass> {input: LayoutInput,containing_block_position_in_root: FfiCssPixelPoint,block_offset: CssPixels,- mut line_builder: Option<&mut line_builder::LineBuilder<'_, '_>>,+ line_builder: Option<&mut line_builder::LineBuilder<'_, '_>>,fragment_facts: run_state::FragmentFactsDecidedByParent,) -> (abspos_engine::InFlowBoxInsets,Option<run_state::LaidOutChildBox>,Option<FfiCssPixelPoint>,) {+ let laid_out_float = self.lay_out_float_ahead_of_its_position(+ run,+ sized_float,+ block_container,+ input,+ containing_block_position_in_root,+ );+ self.position_laid_out_float(+ run,+ laid_out_float,+ block_container,+ input,+ containing_block_position_in_root,+ block_offset,+ line_builder,+ fragment_facts,+ )+ }++ /// Lays out the contents of a float, which does not depend on where the float goes.+ pub(crate) fn lay_out_float_ahead_of_its_position(+ &self,+ run: &FormattingContextRun<'pass>,+ sized_float: ChildSizedHere<'_>,+ block_container: BlockContainer,+ input: LayoutInput,+ containing_block_position_in_root: FfiCssPixelPoint,+ ) -> FloatLaidOutAheadOfItsPosition {let node = sized_float.node;let available_space = input.available_space;assert!(self.facts(node).is_floating());@@ -4783,26 +4829,40 @@ impl<'pass> BlockFormattingContext<'pass> {self.dimension_float_root_inline_size(sized_float, block_container, &float_input);let (float_layout, fragment_arrival, float_box) =self.layout_inside(run, sized_float, block_container, float_input, false);- let placed_float = formatting_context::PlacedChild::of_laid_out_box(&float_box);- let float_box_cells = float_box.cells;- let laid_out_float_handed_back_by_its_run = float_layout.is_some().then_some(float_box);- let containing_block_rect = self.containing_block_rect(block_container, containing_block_position_in_root);- let containing_block_rect_now = containing_block_rect.translated(- CssPixels::default(),- self.block_offset_adjustment_from_pending_ancestor_block_start_margins(block_container.node),- );+ FloatLaidOutAheadOfItsPosition {+ node,+ placed_float: formatting_context::PlacedChild::of_laid_out_box(&float_box),+ cells: float_box.cells,+ laid_out_float_handed_back_by_its_run: float_layout.is_some().then_some(float_box),+ fragment_arrival,+ }+ }- // Next, float to the left and/or right- // FIXME: Honor writing-mode, direction and text-orientation.- let style = self.style(node);- let side = if matches!(style.float_(), float::LEFT | float::INLINE_START) {- Some(FloatSide::Left)- } else if matches!(style.float_(), float::RIGHT | float::INLINE_END) {- Some(FloatSide::Right)- } else {- None- };- let Some(side) = side else {+ /// Positions and places a float laid out ahead of its position.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn position_laid_out_float(+ &self,+ run: &FormattingContextRun<'pass>,+ laid_out_float: FloatLaidOutAheadOfItsPosition,+ block_container: BlockContainer,+ input: LayoutInput,+ containing_block_position_in_root: FfiCssPixelPoint,+ block_offset: CssPixels,+ mut line_builder: Option<&mut line_builder::LineBuilder<'_, '_>>,+ fragment_facts: run_state::FragmentFactsDecidedByParent,+ ) -> (+ abspos_engine::InFlowBoxInsets,+ Option<run_state::LaidOutChildBox>,+ Option<FfiCssPixelPoint>,+ ) {+ let FloatLaidOutAheadOfItsPosition {+ node,+ placed_float,+ cells: float_box,+ laid_out_float_handed_back_by_its_run,+ fragment_arrival,+ } = laid_out_float;+ let Some(side) = Self::float_side(self.style(node)) else {formatting_context::leave_child_unplaced(run,placed_float.with_fragment_facts(fragment_facts),@@ -4814,8 +4874,144 @@ impl<'pass> BlockFormattingContext<'pass> {None,);};- let float_box = float_box_cells;- let mut margin_box_ceiling = if let Some(line_builder) = line_builder.as_deref_mut() {+ let (floating_box, content_block_offset) = self.add_float_beside_lines(+ node,+ side,+ &float_box,+ block_container,+ input,+ containing_block_position_in_root,+ block_offset,+ line_builder.as_deref_mut(),+ );+ let margin_box_rect = floating_box.margin_box_rect_in_root_coordinate_space;++ let bottom_margin_edge = margin_box_rect.bottom();+ if let Some(fragmentainer) = self.run.fragmentainer.as_deref()+ && self.allows_unforced_breaks()+ {+ let bottom_margin_edge_in_column =+ bottom_margin_edge + self.block_offset_adjustment_from_pending_ancestor_block_start_margins(node);+ fragmentainer.note_unbreakable_block_size(margin_box_rect.height);+ if fragmentainer.exceeds(bottom_margin_edge_in_column) {+ fragmentainer.note_space_shortage(bottom_margin_edge_in_column);+ fragmentainer.outcome_mut().overflows = true;+ }+ }+ self.lowest_floating_descendant_bottom_margin_edge.set(Some(+ self.lowest_floating_descendant_bottom_margin_edge+ .get()+ .map_or(bottom_margin_edge, |lowest| lowest.max(bottom_margin_edge)),+ ));+ if let Some(line_builder) = line_builder {+ line_builder.recalculate_available_space();+ }+ let insets = self.compute_inset(run, node, block_container);++ let inline_offset = if side == FloatSide::Left {+ floating_box.offset_from_edge+ } else {+ floating_box.percentage_basis_inline_size.unwrap_or_default() - floating_box.offset_from_edge+ };+ let content_offset = FfiCssPixelPoint {+ x: inline_offset,+ y: content_block_offset,+ };+ formatting_context::place_child(+ &self.run,+ node,+ placed_float+ .with_in_flow_box_insets(insets)+ .with_fragment_facts(fragment_facts),+ content_offset,+ None,+ fragment_arrival,+ );+ (insets, laid_out_float_handed_back_by_its_run, Some(content_offset))+ }++ /// Adds a float laid out in `float_box` beside the lines `line_builder` builds, only to find where they break.+ pub(crate) fn add_float_for_finding_line_breaks(+ &self,+ node: Node,+ float_box: &used_values::RootInputCells,+ block_container: BlockContainer,+ input: LayoutInput,+ containing_block_position_in_root: FfiCssPixelPoint,+ line_builder: &mut line_builder::LineBuilder<'_, '_>,+ ) {+ let Some(side) = Self::float_side(self.style(node)) else {+ return;+ };+ self.add_float_beside_lines(+ node,+ side,+ float_box,+ block_container,+ input,+ containing_block_position_in_root,+ CssPixels::default(),+ Some(&mut *line_builder),+ );+ line_builder.recalculate_available_space();+ }++ /// The floats and margins of this context before finding where lines break changes them.+ pub(crate) fn state_before_finding_line_breaks(&self) -> StateBeforeFindingLineBreaks {+ StateBeforeFindingLineBreaks {+ float_count: self.floating_box_count(),+ bands: self.bands.borrow().clone(),+ lowest_left_margin_edge: self.lowest_left_margin_edge.get(),+ lowest_right_margin_edge: self.lowest_right_margin_edge.get(),+ margin_state: self.margin_state.borrow().clone(),+ }+ }++ /// Takes out the floats added and restores the margins committed to find where lines break since `state` was the+ /// state of this context.+ pub(crate) fn restore_state_after_finding_line_breaks(&self, state: StateBeforeFindingLineBreaks) {+ *self.margin_state.borrow_mut() = state.margin_state;+ if self.floating_box_count() == state.float_count {+ return;+ }+ self.floats.borrow_mut().truncate(state.float_count);+ *self.bands.borrow_mut() = state.bands;+ self.lowest_left_margin_edge.set(state.lowest_left_margin_edge);+ self.lowest_right_margin_edge.set(state.lowest_right_margin_edge);+ }++ fn float_side(style: StyleValues<'_>) -> Option<FloatSide> {+ // FIXME: Honor writing-mode, direction and text-orientation.+ if matches!(style.float_(), float::LEFT | float::INLINE_START) {+ Some(FloatSide::Left)+ } else if matches!(style.float_(), float::RIGHT | float::INLINE_END) {+ Some(FloatSide::Right)+ } else {+ None+ }+ }++ /// Floats the box laid out in `float_box` to `side`, below the content `line_builder` already put on its line+ /// where the float does not fit beside it, and adds it to the floats of this context.+ #[allow(clippy::too_many_arguments)]+ fn add_float_beside_lines(+ &self,+ node: Node,+ side: FloatSide,+ float_box: &used_values::RootInputCells,+ block_container: BlockContainer,+ input: LayoutInput,+ containing_block_position_in_root: FfiCssPixelPoint,+ block_offset: CssPixels,+ line_builder: Option<&mut line_builder::LineBuilder<'_, '_>>,+ ) -> (FloatingBox, CssPixels) {+ let style = self.style(node);+ let containing_block_rect = self.containing_block_rect(block_container, containing_block_position_in_root);+ let containing_block_rect_now = containing_block_rect.translated(+ CssPixels::default(),+ self.block_offset_adjustment_from_pending_ancestor_block_start_margins(block_container.node),+ );+ let mut margin_box_ceiling = if let Some(line_builder) = line_builder {line_builder.ceiling_for_float_to_be_inserted_here(float_box.margin_box_inline_size(false))} else {block_offset@@ -4837,18 +5033,18 @@ impl<'pass> BlockFormattingContext<'pass> {}let placement = self.place_float(side,- &float_box,- available_space,+ float_box,+ input.available_space,containing_block_rect_now,ceiling_in_root,);let content_block_offset = placement.block_start - containing_block_rect_now.y+ float_box.margin_top()+ float_box.border_box_top(false);- let mut margin_box_rect = Self::margin_box_rect(&float_box)+ let mut margin_box_rect = Self::margin_box_rect(float_box).translated(CssPixels::default(), content_block_offset).translated(containing_block_rect.x, containing_block_rect.y);- let floating_box = FloatingBox {+ let mut floating_box = FloatingBox {box_: node,side,offset_from_edge: placement.offset_from_edge,@@ -4864,53 +5060,10 @@ impl<'pass> BlockFormattingContext<'pass> {percentage_basis_inline_size: input.containing_block_constraints.percentage_basis_inline_size,};margin_box_rect.x = floating_box.margin_box_left_in_root_coordinate_space();- let mut floating_box = floating_box;floating_box.margin_box_rect_in_root_coordinate_space = margin_box_rect;self.floats.borrow_mut().push(floating_box);self.add_float_to_bands(floating_box, containing_block_rect);-- let bottom_margin_edge = margin_box_rect.bottom();- if let Some(fragmentainer) = self.run.fragmentainer.as_deref()- && self.allows_unforced_breaks()- {- let bottom_margin_edge_in_column =- bottom_margin_edge + self.block_offset_adjustment_from_pending_ancestor_block_start_margins(node);- fragmentainer.note_unbreakable_block_size(margin_box_rect.height);- if fragmentainer.exceeds(bottom_margin_edge_in_column) {- fragmentainer.note_space_shortage(bottom_margin_edge_in_column);- fragmentainer.outcome_mut().overflows = true;- }- }- self.lowest_floating_descendant_bottom_margin_edge.set(Some(- self.lowest_floating_descendant_bottom_margin_edge- .get()- .map_or(bottom_margin_edge, |lowest| lowest.max(bottom_margin_edge)),- ));- if let Some(line_builder) = line_builder {- line_builder.recalculate_available_space();- }- let insets = self.compute_inset(run, node, block_container);-- let inline_offset = if side == FloatSide::Left {- floating_box.offset_from_edge- } else {- floating_box.percentage_basis_inline_size.unwrap_or_default() - floating_box.offset_from_edge- };- let content_offset = FfiCssPixelPoint {- x: inline_offset,- y: content_block_offset,- };- formatting_context::place_child(- &self.run,- node,- placed_float- .with_in_flow_box_insets(insets)- .with_fragment_facts(fragment_facts),- content_offset,- None,- fragment_arrival,- );- (insets, laid_out_float_handed_back_by_its_run, Some(content_offset))+ (floating_box, content_block_offset)}fn layout_inline_children(diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rsindex aca3c5c6361..2a57bfab03f 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs@@ -1002,6 +1002,8 @@ pub(crate) struct InlineFormattingContext<'context> {entered_inline_boxes: RefCell<HashMap<Node, EnteredInlineBox>>,/// The used insets of each float this context laid out among its lines, as the float's layout resolved them.used_insets_of_floats: RefCell<HashMap<Node, run_state::UsedInsets>>,+ /// The floats among the lines laid out ahead of them, to balance the lines.+ floats_laid_out_ahead_of_lines: RefCell<HashMap<Node, block_formatting_context::FloatLaidOutAheadOfItsPosition>>,}/// What an inline formatting context resolved of an inline box on entering it.@@ -1043,6 +1045,7 @@ impl<'context> InlineFormattingContext<'context> {margins_collapse_through_interrupting_blocks: RefCell::new(HashMap::default()),entered_inline_boxes: RefCell::new(HashMap::default()),used_insets_of_floats: RefCell::new(HashMap::default()),+ floats_laid_out_ahead_of_lines: RefCell::new(HashMap::default()),}}@@ -1780,8 +1783,8 @@ impl<'context> InlineFormattingContext<'context> {}/// Whether text-wrap-style: balance balances the lines of this context. Lines are only balanced while finding where- /// they break leaves the rest of the layout alone, so not beside floats or with floats or block-level boxes among- /// them, and not when they are clamped or fragmented.+ /// they break leaves the rest of the layout alone, so not with block-level boxes among them, and not when they are+ /// clamped or fragmented.fn balances_lines(&self,iterator: &inline_level_iterator::InlineLevelIterator,@@ -1802,10 +1805,45 @@ impl<'context> InlineFormattingContext<'context> {{return false;}- if self.any_floats_intrude_in_block_range(CssPixels::default(), max_dimension_value()) {- return false;+ // NB: Floats are laid out ahead of the lines, before the floats ahead of them are placed, so not the ones whose+ // stretch inline size avoids those floats.+ iterator.items().iter().all(|item| {+ item.type_.stays_on_lines()+ || (item.type_ == inline_level_iterator::ItemType::FloatingElement+ && !self.style(item.node).width().is_stretch())+ })+ }++ /// Lays out the floats among the items of `iterator` ahead of the lines, so that finding where the lines break+ /// can float them beside the lines without laying them out again.+ fn lay_out_floats_ahead_of_lines(&self, iterator: &inline_level_iterator::InlineLevelIterator) {+ for item in iterator.items() {+ if item.type_ == inline_level_iterator::ItemType::FloatingElement {+ let laid_out_float = self.lay_out_float_ahead_of_its_position(item.node);+ self.floats_laid_out_ahead_of_lines+ .borrow_mut()+ .insert(item.node, laid_out_float);+ }}- iterator.items().iter().all(|item| item.type_.stays_on_lines())+ }++ fn lay_out_float_ahead_of_its_position(+ &self,+ node: Node,+ ) -> block_formatting_context::FloatLaidOutAheadOfItsPosition {+ // NB: Every float is sized in cells ahead of its layout, which takes them.+ let cells_of_float_ahead_of_its_layout = Cell::new(used_values::cells_before_sizing(+ &self.callbacks,+ node,+ self.input.containing_block_constraints,+ ));+ self.parent.lay_out_float_ahead_of_its_position(+ self.run,+ block_formatting_context::ChildSizedHere::ahead_of_its_run(node, &cells_of_float_ahead_of_its_layout),+ self.block_container,+ self.input,+ self.containing_block_position_in_bfc_root,+ )}// https://drafts.csswg.org/css-text-4/#valdef-text-wrap-style-balance@@ -1813,37 +1851,65 @@ impl<'context> InlineFormattingContext<'context> {// possible. This should avoid changing-- and in the case of 5 or fewer lines must not change-- the number of line// boxes the block would contain if text-wrap were set to auto.// ...+ // The remaining space to consider is that which remains after placing floats and inline content, but before any+ // adjustments due to text justification. Line boxes are balanced when the standard deviation from the average+ // inline-size of the remaining space in each line box is reduced over the block (including lines that end in a+ // forced line break).+ // ...// Groups of lines separated by a forced line break are processed separately.- /// The inline size the lines of each group break at to balance them, if they are balanced.- fn balanced_inline_sizes(&self, iterator: &inline_level_iterator::InlineLevelIterator) -> Vec<Option<CssPixels>> {+ /// The inline size taken off the available inline size of each line of each group to balance them, if they are+ /// balanced. Leaving each line of a group the same space unused balances the space that remains on them.+ fn balancing_reductions(&self, iterator: &inline_level_iterator::InlineLevelIterator) -> Vec<Option<CssPixels>> {let items = iterator.items();- let mut balanced_inline_sizes = Vec::new();+ let group_ends: Vec<usize> = items+ .iter()+ .enumerate()+ .filter(|(_, item)| item.type_ == inline_level_iterator::ItemType::ForcedBreak)+ .map(|(index, _)| index)+ .chain(std::iter::once(items.len()))+ .collect();+ let state = self.state_before_finding_line_breaks();+ let mut line_builder = line_builder::LineBuilder::new_for_finding_balanced_line_breaks(self);+ let mut reductions = Vec::new();let mut group_start = 0;- for (index, item) in items.iter().enumerate() {- if item.type_ == inline_level_iterator::ItemType::ForcedBreak {- balanced_inline_sizes.push(self.balanced_inline_size_of_group(- iterator,- group_start..index,- !balanced_inline_sizes.is_empty(),- ));- group_start = index + 1;- }- }- balanced_inline_sizes.push(self.balanced_inline_size_of_group(- iterator,- group_start..items.len(),- !balanced_inline_sizes.is_empty(),- ));- balanced_inline_sizes+ for (group_index, &group_end) in group_ends.iter().enumerate() {+ // NB: Breaking the items looks ahead past the forced break after them, as far as the next group reaches.+ let look_ahead_end = group_ends+ .get(group_index + 1)+ .map_or(items.len(), |&next_group_end| (next_group_end + 1).min(items.len()));+ let reduction = self.balancing_reduction_of_group(+ iterator,+ group_start..group_end,+ look_ahead_end,+ &line_builder,+ &reductions,+ );+ reductions.push(reduction);+ if group_end == items.len() {+ break;+ }+ // NB: Break the group and the forced break after it into lines as balanced, so that the lines of the next+ // group are tried from where they start.+ line_builder.set_balancing_reductions(reductions.clone());+ let mut group_items = iterator.duplicate(group_start..group_end + 1, look_ahead_end);+ let item_count = group_items.items().len();+ self.break_items_into_lines(&mut group_items, &mut line_builder, item_count, None, None, None);+ group_start = group_end + 1;+ }+ self.line_data_mut().line_boxes.clear();+ self.restore_state_after_finding_line_breaks(state);+ reductions}- /// The inline size the lines of the items in `group` break at to balance them: found by bisecting down to a pixel,- /// it breaks the items into as many lines as the available inline size does.- fn balanced_inline_size_of_group(- &self,+ /// The inline size taken off the available inline size of each line of the items in `group` to balance them:+ /// found by bisecting down to a pixel, it breaks the items into as many lines as the available inline size does.+ fn balancing_reduction_of_group<'builder>(+ &'builder self,iterator: &inline_level_iterator::InlineLevelIterator,group: std::ops::Range<usize>,- follows_forced_break: bool,+ look_ahead_end: usize,+ line_builder_at_group_start: &line_builder::LineBuilder<'builder, 'context>,+ reductions_of_previous_groups: &[Option<CssPixels>],) -> Option<CssPixels> {// INTEROP: Only balance up to 6 lines, since each try breaks all of the lines again.const MAXIMUM_LINE_COUNT: usize = 6;@@ -1855,49 +1921,89 @@ impl<'context> InlineFormattingContext<'context> {if content_inline_size > available_inline_size * (MAXIMUM_LINE_COUNT * 2) {return None;}- let find_line_breaks = |inline_size| {- self.find_line_breaks_when_breaking_at(iterator, group.clone(), follows_forced_break, inline_size)+ let find_line_breaks = |reduction| {+ self.find_line_breaks_of_group(+ iterator,+ group.clone(),+ look_ahead_end,+ line_builder_at_group_start,+ reductions_of_previous_groups,+ reduction,+ )};- let (line_count, inline_size_of_lines) = find_line_breaks(available_inline_size);+ let (line_count, inline_size_of_lines) = find_line_breaks(CssPixels::default());if line_count <= 1 || line_count > MAXIMUM_LINE_COUNT {return None;}- // NB: Bisect between the available inline size and a bit less than the average line, which is too narrow- // unless lines overflow.- let mut too_narrow = (inline_size_of_lines / line_count).scaled(0.8);- let mut balanced_inline_size = available_inline_size;- while balanced_inline_size - too_narrow > CssPixels::from_integer(1) {- let candidate = too_narrow + (balanced_inline_size - too_narrow) / 2;+ // NB: Bisect between no reduction and one that leaves less than the average line, which is too much unless+ // lines overflow.+ let mut too_much = available_inline_size - (inline_size_of_lines / line_count).scaled(0.8);+ let mut reduction = CssPixels::default();+ while too_much - reduction > CssPixels::from_integer(1) {+ let candidate = reduction + (too_much - reduction) / 2;if find_line_breaks(candidate).0 <= line_count {- balanced_inline_size = candidate;+ reduction = candidate;} else {- too_narrow = candidate;+ too_much = candidate;}}- (balanced_inline_size < available_inline_size).then_some(balanced_inline_size)+ (reduction > CssPixels::default()).then_some(reduction)}- /// The number of lines and the sum of their inline sizes when the items in `group` break into lines at- /// `inline_size`.- fn find_line_breaks_when_breaking_at(- &self,+ /// The number of lines of the items in `group`, and the sum of their inline sizes, when `line_builder_at_group_start`+ /// breaks them into lines reduced by `reduction`. The lines and floats of the context are left as they were.+ fn find_line_breaks_of_group<'builder>(+ &'builder self,iterator: &inline_level_iterator::InlineLevelIterator,group: std::ops::Range<usize>,- follows_forced_break: bool,- inline_size: CssPixels,+ look_ahead_end: usize,+ line_builder_at_group_start: &line_builder::LineBuilder<'builder, 'context>,+ reductions_of_previous_groups: &[Option<CssPixels>],+ reduction: CssPixels,) -> (usize, CssPixels) {- let mut iterator = iterator.duplicate(group);- let item_count = iterator.items().len();- let mut line_builder =- line_builder::LineBuilder::new_for_finding_balanced_line_breaks(self, inline_size, follows_forced_break);- self.break_items_into_lines(&mut iterator, &mut line_builder, item_count, None, None, None);- line_builder.remove_last_line_if_empty();- let mut lines = std::mem::take(&mut self.line_data_mut().line_boxes);- let inline_size_of_lines = lines.iter_mut().fold(CssPixels::default(), |sum, line| {- line.trim_trailing_whitespace();- sum + line.inline_length- });- (lines.len(), inline_size_of_lines)+ let state = self.state_before_finding_line_breaks();+ // NB: The lines of the group start with the current line, and breaking it can change the line before it.+ let first_line_index = self.line_data().line_boxes.len() - 1;+ let first_changed_line_index = first_line_index.saturating_sub(1);+ let lines_before_breaking = self.line_data().line_boxes[first_changed_line_index..].to_vec();+ let mut line_builder = line_builder_at_group_start.clone();+ let mut reductions = reductions_of_previous_groups.to_vec();+ reductions.push(Some(reduction));+ line_builder.set_balancing_reductions(reductions);+ let mut group_items = iterator.duplicate(group, look_ahead_end);+ let item_count = group_items.items().len();+ self.break_items_into_lines(&mut group_items, &mut line_builder, item_count, None, None, None);+ let mut data = self.line_data_mut();+ let lines = &mut data.line_boxes;+ let mut end = lines.len();+ while end > first_line_index && lines[end - 1].is_empty() {+ end -= 1;+ }+ let inline_size_of_lines = lines[first_line_index..end]+ .iter_mut()+ .fold(CssPixels::default(), |sum, line| {+ line.trim_trailing_whitespace();+ sum + line.inline_length+ });+ lines.truncate(first_changed_line_index);+ lines.extend(lines_before_breaking);+ drop(data);+ self.restore_state_after_finding_line_breaks(state);+ (end - first_line_index, inline_size_of_lines)+ }++ /// The state of this context and its parent that breaking items into lines changes beyond the lines.+ fn state_before_finding_line_breaks(&self) -> StateBeforeFindingLineBreaks {+ StateBeforeFindingLineBreaks {+ parent: self.parent.state_before_finding_line_breaks(),+ block_axis_float_clearance: self.block_axis_float_clearance.get(),+ }+ }++ /// Restores the state that breaking items into lines changed beyond the lines, only to find where they break.+ fn restore_state_after_finding_line_breaks(&self, state: StateBeforeFindingLineBreaks) {+ self.parent.restore_state_after_finding_line_breaks(state.parent);+ self.block_axis_float_clearance.set(state.block_axis_float_clearance);}/// Breaks the items left in `iterator` into lines with `line_builder`. `item_count` is the number of items the@@ -1993,11 +2099,7 @@ impl<'context> InlineFormattingContext<'context> {});let continuation = iterator.next_inline_run_size(self);line_builder.break_line(line_builder::ForcedBreak::Yes, item.node, continuation);- // NB: Trials to balance the lines leave clearance to the layout of the lines.- if !item.node.is_invalid()- && !line_builder.only_finds_line_breaks()- && self.clear_floating_boxes(item.node)- {+ if !item.node.is_invalid() && self.clear_floating_boxes(item.node) {line_builder.did_introduce_clearance(self.block_axis_float_clearance.get());self.reset_parent_margin_state();}@@ -2079,33 +2181,43 @@ impl<'context> InlineFormattingContext<'context> {}inline_level_iterator::ItemType::FloatingElement => {line_builder.commit_pending_margin_before_float();- let constraints = self.input.containing_block_constraints;- // NB: Every float is sized in cells ahead of its layout, which takes them.- let cells_of_float_ahead_of_its_layout = Cell::new(used_values::cells_before_sizing(- &self.callbacks,- item.node,- constraints,- ));- let sized_float = block_formatting_context::ChildSizedHere::ahead_of_its_run(- item.node,- &cells_of_float_ahead_of_its_layout,- );self.clear_floating_boxes(item.node);line_builder.set_unbreakable_run_inline_size_interrupted_by_float(iterator.next_unbreakable_run_inline_size(self),);- let (insets, _, _) = self.parent.layout_floating_box(+ if line_builder.only_finds_line_breaks() {+ let cells = self+ .floats_laid_out_ahead_of_lines+ .borrow()+ .get(&item.node)+ .expect("floats among balanced lines are laid out ahead of them")+ .cells;+ self.parent.add_float_for_finding_line_breaks(+ item.node,+ &cells,+ self.block_container,+ self.input,+ self.containing_block_position_in_bfc_root,+ line_builder,+ );+ continue;+ }+ let fragment_facts = run_state::FragmentFactsDecidedByParent {+ is_invisible_for_line_clamp: state_at_clamp_point.is_some(),+ ..run_state::FragmentFactsDecidedByParent::default()+ };+ let laid_out_ahead = self.floats_laid_out_ahead_of_lines.borrow_mut().remove(&item.node);+ let laid_out_float =+ laid_out_ahead.unwrap_or_else(|| self.lay_out_float_ahead_of_its_position(item.node));+ let (insets, _, _) = self.parent.position_laid_out_float(self.run,- sized_float,+ laid_out_float,self.block_container,self.input,self.containing_block_position_in_bfc_root,CssPixels::default(),Some(&mut *line_builder),- run_state::FragmentFactsDecidedByParent {- is_invisible_for_line_clamp: state_at_clamp_point.is_some(),- ..run_state::FragmentFactsDecidedByParent::default()- },+ fragment_facts,);self.used_insets_of_floats.borrow_mut()@@ -2249,8 +2361,9 @@ impl<'context> InlineFormattingContext<'context> {&& iterator.items()[start_item_index - 1].type_ == inline_level_iterator::ItemType::ForcedBreak;iterator.skip_items(start_item_index);// NB: Trials to balance the lines move the start of the current line, so balance before the lines start.- let balanced_inline_sizes = if balances_lines {- self.balanced_inline_sizes(&iterator)+ let balancing_reductions = if balances_lines {+ self.lay_out_floats_ahead_of_lines(&iterator);+ self.balancing_reductions(&iterator)} else {Vec::new()};@@ -2266,9 +2379,7 @@ impl<'context> InlineFormattingContext<'context> {} else {line_builder::LineBuilder::new_after_reused_lines(self)};- if balanced_inline_sizes.iter().any(Option::is_some) {- line_builder.set_balanced_inline_sizes(balanced_inline_sizes);- }+ line_builder.set_balancing_reductions(balancing_reductions);let mut floating_boxes_after_clamp_point = Vec::new();let floating_box_count_before_lines = self.parent.floating_box_count();@@ -2892,6 +3003,12 @@ impl<'context> InlineFormattingContext<'context> {}}+/// The state of an inline formatting context and its parent that breaking items into lines changes beyond the lines.+struct StateBeforeFindingLineBreaks {+ parent: block_formatting_context::StateBeforeFindingLineBreaks,+ block_axis_float_clearance: CssPixels,+}+/// What breaking the items into lines left to finish once the lines are built.struct BrokenLines<'builder, 'context> {absolute_boxes: Vec<Node>,diff --git a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rsindex 04be6265002..0b3a0e0b12d 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs@@ -529,6 +529,7 @@ impl<'iterator, 'context> InlineLevelIteratorGenerator<'iterator, 'context> {InlineLevelIterator {entered_box_model_nodes: iterator.entered_box_model_nodes,items: ItemQueue::Owned(iterator.items.into_iter()),+ items_kept_for_looking_ahead: 0,}}@@ -1164,6 +1165,8 @@ impl ItemQueue {pub(crate) struct InlineLevelIterator {entered_box_model_nodes: Vec<Node>,items: ItemQueue,+ /// The number of items at the end that this iterator only shows to look ahead, and does not hand out.+ items_kept_for_looking_ahead: usize,}impl InlineLevelIterator {@@ -1188,6 +1191,7 @@ impl InlineLevelIterator {return Self {entered_box_model_nodes: entered_box_model_nodes.to_vec(),items: ItemQueue::Shared { items, next: 0 },+ items_kept_for_looking_ahead: 0,};}let iterator = Self::new(context);@@ -1214,6 +1218,7 @@ impl InlineLevelIterator {next: 0,}},+ items_kept_for_looking_ahead: 0,}}@@ -1241,6 +1246,7 @@ impl InlineLevelIterator {Self {entered_box_model_nodes: stash.entered_box_model_nodes,items: ItemQueue::Owned(stash.items.into_iter()),+ items_kept_for_looking_ahead: 0,}}@@ -1282,6 +1288,9 @@ impl InlineLevelIterator {}pub(crate) fn next(&mut self) -> Option<Item> {+ if self.items.as_slice().len() <= self.items_kept_for_looking_ahead {+ return None;+ }self.items.next()}@@ -1301,12 +1310,14 @@ impl InlineLevelIterator {self.items.skip(count);}- /// An iterator over a copy of the items left in `range`, which leaves the items of this one in place.- pub(crate) fn duplicate(&self, range: std::ops::Range<usize>) -> Self {- let items: Vec<Item> = self.items()[range].to_vec();+ /// An iterator over a copy of the items left in `range`, which leaves the items of this one in place. It looks+ /// ahead at the items after `range` up to `look_ahead_end`, without handing them out.+ pub(crate) fn duplicate(&self, range: std::ops::Range<usize>, look_ahead_end: usize) -> Self {+ let items: Vec<Item> = self.items()[range.start..look_ahead_end].to_vec();Self {entered_box_model_nodes: self.entered_box_model_nodes.clone(),items: ItemQueue::Owned(items.into_iter()),+ items_kept_for_looking_ahead: look_ahead_end - range.end,}}diff --git a/Libraries/LibWeb/Rust/src/layout/line_builder.rs b/Libraries/LibWeb/Rust/src/layout/line_builder.rsindex 62e557fe94c..708de9f1922 100644--- a/Libraries/LibWeb/Rust/src/layout/line_builder.rs+++ b/Libraries/LibWeb/Rust/src/layout/line_builder.rs@@ -54,12 +54,11 @@ struct LineRelativeAlignedSubtree {pub(crate) struct LineBuilder<'builder, 'context> {context: &'builder inline_formatting_context::InlineFormattingContext<'context>,available_inline_size_for_current_line: AvailableSize,- /// The inline size that text-wrap-style: balance chose for the lines of each group between forced breaks to break- /// at, below the available inline size.- balanced_inline_sizes: Vec<Option<CssPixels>>,+ /// The inline size that text-wrap-style: balance takes off the available inline size of each line of each group+ /// between forced breaks, for the lines to break at.+ balancing_reductions: Vec<Option<CssPixels>>,forced_break_count: usize,- /// Whether this builder only finds where lines break, to balance them, and leaves the margins of the parent as- /// they are.+ /// Whether this builder only finds where lines break, to balance them, and leaves the boxes on the lines unplaced.only_finds_line_breaks: bool,current_block_offset: CssPixels,max_block_size_on_current_line: CssPixels,@@ -86,31 +85,18 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {builder}- /// A builder that only finds where the lines of one group between forced breaks break when they break at- /// `balanced_inline_size`.+ /// A builder that only finds where the lines break, to balance them.pub(crate) fn new_for_finding_balanced_line_breaks(context: &'builder inline_formatting_context::InlineFormattingContext<'context>,- balanced_inline_size: CssPixels,- follows_forced_break: bool,) -> Self {let mut builder = Self::initialized(context);- builder.balanced_inline_sizes = vec![Some(balanced_inline_size)];builder.only_finds_line_breaks = true;- builder.is_continuation = follows_forced_break;- builder.begin_new_line(- false,- true,- if follows_forced_break {- ForcedBreak::Yes- } else {- ForcedBreak::No- },- );+ builder.begin_new_line(false, true, ForcedBreak::No);builder}- pub(crate) fn set_balanced_inline_sizes(&mut self, balanced_inline_sizes: Vec<Option<CssPixels>>) {- self.balanced_inline_sizes = balanced_inline_sizes;+ pub(crate) fn set_balancing_reductions(&mut self, balancing_reductions: Vec<Option<CssPixels>>) {+ self.balancing_reductions = balancing_reductions;}pub(crate) fn new_for_continuation(@@ -137,7 +123,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {Self {context,available_inline_size_for_current_line: AvailableSize::Indefinite,- balanced_inline_sizes: Vec::new(),+ balancing_reductions: Vec::new(),forced_break_count: 0,only_finds_line_breaks: false,current_block_offset: CssPixels::default(),@@ -342,13 +328,13 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {/// The inline size the current line breaks at. Balancing breaks lines before they fill the available inline size,/// but they still align within it.fn inline_size_to_break_current_line_at(&self) -> AvailableSize {- let balanced_inline_size = self- .balanced_inline_sizes+ let balancing_reduction = self+ .balancing_reductions.get(self.forced_break_count).copied().flatten();- match (self.available_inline_size_for_current_line, balanced_inline_size) {- (AvailableSize::Definite(available), Some(balanced)) => AvailableSize::Definite(available.min(balanced)),+ match (self.available_inline_size_for_current_line, balancing_reduction) {+ (AvailableSize::Definite(available), Some(reduction)) => AvailableSize::Definite(available - reduction),(available, _) => available,}}@@ -361,12 +347,8 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {Some(available - self.line(line_index).physical_horizontal_extent())}- fn remaining_inline_size_on_current_line(&mut self) -> Option<CssPixels> {- self.remaining_inline_size_on_current_line_within(self.inline_size_to_break_current_line_at())- }-- /// NB: Balancing does not break words that fit the available inline size, so they overflow the balanced inline- /// size instead.+ /// NB: Balancing does not break words that fit the available inline size, so they overflow the inline size the+ /// line breaks at instead.pub(crate) fn remaining_inline_size_for_overflow_break(&mut self) -> Option<CssPixels> {self.remaining_inline_size_on_current_line_within(self.available_inline_size_for_current_line)}@@ -407,7 +389,9 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {}}pub(crate) fn current_line_has_no_space_left_by_floats(&mut self) -> bool {- let Some(remaining) = self.remaining_inline_size_on_current_line() else {+ let Some(remaining) =+ self.remaining_inline_size_on_current_line_within(self.available_inline_size_for_current_line)+ else {return false;};if remaining > CssPixels::default() {@@ -544,7 +528,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {return;}let line_index = self.ensure_last_line_index();- if self.line(line_index).has_block_level_box || self.only_finds_line_breaks {+ if self.line(line_index).has_block_level_box {return;}let margin = self.context().parent_commit_pending_margin_before_inline_content();@@ -667,7 +651,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {}fn should_break(&mut self, next_item_inline_size: CssPixels) -> bool {- if self.current_line_is_empty() {+ let inline_size_to_break_at = if self.current_line_is_empty() {let line_height = self.containing_style().line_height();if !self.context()@@ -675,11 +659,14 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {{return false;}- }+ // NB: Balancing moves breaks between the content of lines, not lines past floats.+ self.available_inline_size_for_current_line+ } else {+ self.inline_size_to_break_current_line_at()+ };let line_index = self.ensure_last_line_index();let current_inline_size = self.line(line_index).physical_horizontal_extent();- self.inline_size_to_break_current_line_at()- .pixels_greater_than(current_inline_size + next_item_inline_size)+ inline_size_to_break_at.pixels_greater_than(current_inline_size + next_item_inline_size)}pub(super) fn baseline_for_style(style: StyleValues, line_height: CssPixels) -> CssPixels {diff --git a/Tests/LibWeb/Layout/expected/text-wrap-balance-below-float-after-margin.txt b/Tests/LibWeb/Layout/expected/text-wrap-balance-below-float-after-margin.txtnew file mode 100644index 00000000000..dea1c26d4cd--- /dev/null+++ b/Tests/LibWeb/Layout/expected/text-wrap-balance-below-float-after-margin.txt@@ -0,0 +1,40 @@+Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children: not-inline+ BlockContainer <html> at [0,0] [0+0+0 800 0+0+0] [0+0+0 208 0+0+0] [BFC] children: not-inline+ BlockContainer <body> at [8,8] [8+0+0 784 0+0+8] [8+0+0 190 0+0+8] children: not-inline+ BlockContainer <div.container> at [8,8] [0+0+0 784 0+0+0] [0+0+0 90 0+0+10] [BFC] children: not-inline+ BlockContainer <(anonymous)> at [8,8] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <div.float> at [8,8] floating [0+0+0 200 0+0+0] [0+0+0 20 0+0+0] [BFC] children: not-inline+ TextNode <#text> (not painted)+ BlockContainer <p> at [8,38] [0+0+0 300 0+0+484] [30+0+0 60 0+0+0] children: inline+ frag 0 from TextNode start: 0, length: 15, rect: [8,38 172.28125x20] baseline: 16+ "The quick brown"+ frag 1 from TextNode start: 16, length: 18, rect: [8,58 198.359375x20] baseline: 16+ "fox jumps over the"+ frag 2 from TextNode start: 35, length: 21, rect: [8,78 210.125x20] baseline: 16+ "lazy dog and the cat."+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,98] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,108] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <div.container> at [8,108] [0+0+0 784 0+0+0] [0+0+0 90 0+0+10] [BFC] children: not-inline+ BlockContainer <(anonymous)> at [8,108] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <div.float> at [8,108] floating [0+0+0 200 0+0+0] [0+0+0 20 0+0+0] [BFC] children: not-inline+ TextNode <#text> (not painted)+ BlockContainer <p> at [8,138] [0+0+0 300 0+0+484] [30+0+0 60 0+0+0] children: inline+ frag 0 from TextNode start: 0, length: 25, rect: [8,138 284.390625x20] baseline: 16+ "The quick brown fox jumps"+ frag 1 from TextNode start: 26, length: 25, rect: [8,158 259.5625x20] baseline: 16+ "over the lazy dog and the"+ frag 2 from TextNode start: 52, length: 4, rect: [8,178 36.8125x20] baseline: 16+ "cat."+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,198] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,208] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)++SC for Viewport<#document> [0,0 800x600] (z-index: auto)+ SC for BlockContainer<HTML> [0,0 800x208] (z-index: auto)diff --git a/Tests/LibWeb/Layout/expected/text-wrap-balance-narrow-space-beside-float.txt b/Tests/LibWeb/Layout/expected/text-wrap-balance-narrow-space-beside-float.txtnew file mode 100644index 00000000000..99db58a0d30--- /dev/null+++ b/Tests/LibWeb/Layout/expected/text-wrap-balance-narrow-space-beside-float.txt@@ -0,0 +1,30 @@+Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children: not-inline+ BlockContainer <html> at [0,0] [0+0+0 800 0+0+0] [0+0+0 148 0+0+0] [BFC] children: not-inline+ BlockContainer <body> at [8,8] [8+0+0 784 0+0+8] [8+0+0 130 0+0+8] children: not-inline+ BlockContainer <div.container> at [8,8] [0+0+0 400 0+0+384] [0+0+0 60 0+0+10] children: inline+ frag 0 from TextNode start: 5, length: 7, rect: [308,8 73.421875x20] baseline: 16+ "abc def"+ frag 1 from TextNode start: 13, length: 7, rect: [308,28 59.796875x20] baseline: 16+ "ghi jkl"+ frag 2 from TextNode start: 21, length: 34, rect: [8,48 358.40625x20] baseline: 16+ "mno pqr stu vwx yz abc def ghi jkl"+ TextNode <#text> (not painted)+ BlockContainer <div.float> at [8,8] floating [0+0+0 300 0+0+0] [0+0+0 40 0+0+0] [BFC] children: not-inline+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,78] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <div.container> at [8,78] [0+0+0 400 0+0+384] [0+0+0 60 0+0+10] children: inline+ frag 0 from TextNode start: 5, length: 7, rect: [308,78 73.421875x20] baseline: 16+ "abc def"+ frag 1 from TextNode start: 13, length: 7, rect: [308,98 59.796875x20] baseline: 16+ "ghi jkl"+ frag 2 from TextNode start: 21, length: 34, rect: [8,118 358.40625x20] baseline: 16+ "mno pqr stu vwx yz abc def ghi jkl"+ TextNode <#text> (not painted)+ BlockContainer <div.float> at [8,78] floating [0+0+0 300 0+0+0] [0+0+0 40 0+0+0] [BFC] children: not-inline+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,148] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)++SC for Viewport<#document> [0,0 800x600] (z-index: auto)+ SC for BlockContainer<HTML> [0,0 800x148] (z-index: auto)diff --git a/Tests/LibWeb/Layout/expected/text-wrap-balance-stretch-float-after-float.txt b/Tests/LibWeb/Layout/expected/text-wrap-balance-stretch-float-after-float.txtnew file mode 100644index 00000000000..121d8ec5ab0--- /dev/null+++ b/Tests/LibWeb/Layout/expected/text-wrap-balance-stretch-float-after-float.txt@@ -0,0 +1,30 @@+Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children: not-inline+ BlockContainer <html> at [0,0] [0+0+0 800 0+0+0] [0+0+0 148 0+0+0] [BFC] children: not-inline+ BlockContainer <body> at [8,8] [8+0+0 784 0+0+8] [8+0+0 130 0+0+8] children: not-inline+ BlockContainer <div.container> at [8,8] [0+0+0 400 0+0+384] [0+0+0 60 0+0+10] children: inline+ frag 0 from TextNode start: 5, length: 27, rect: [108,28 282.546875x20] baseline: 16+ "abc def ghi jkl mno pqr stu"+ frag 1 from TextNode start: 33, length: 22, rect: [8,48 219.078125x20] baseline: 16+ "vwx yz abc def ghi jkl"+ TextNode <#text> (not painted)+ BlockContainer <div.first> at [8,8] floating [0+0+0 100 0+0+0] [0+0+0 40 0+0+0] [BFC] children: not-inline+ TextNode <#text> (not painted)+ CanvasBox <canvas.stretch> at [108,8] floating [0+0+0 300 0+0+0] [0+0+0 20 0+0+0] children: not-inline+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,78] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)+ BlockContainer <div.container> at [8,78] [0+0+0 400 0+0+384] [0+0+0 60 0+0+10] children: inline+ frag 0 from TextNode start: 5, length: 27, rect: [108,98 282.546875x20] baseline: 16+ "abc def ghi jkl mno pqr stu"+ frag 1 from TextNode start: 33, length: 22, rect: [8,118 219.078125x20] baseline: 16+ "vwx yz abc def ghi jkl"+ TextNode <#text> (not painted)+ BlockContainer <div.first> at [8,78] floating [0+0+0 100 0+0+0] [0+0+0 40 0+0+0] [BFC] children: not-inline+ TextNode <#text> (not painted)+ CanvasBox <canvas.stretch> at [108,78] floating [0+0+0 300 0+0+0] [0+0+0 20 0+0+0] children: not-inline+ TextNode <#text> (not painted)+ BlockContainer <(anonymous)> at [8,148] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline+ TextNode <#text> (not painted)++SC for Viewport<#document> [0,0 800x600] (z-index: auto)+ SC for BlockContainer<HTML> [0,0 800x148] (z-index: auto)diff --git a/Tests/LibWeb/Layout/input/text-wrap-balance-below-float-after-margin.html b/Tests/LibWeb/Layout/input/text-wrap-balance-below-float-after-margin.htmlnew file mode 100644index 00000000000..bebf0720e99--- /dev/null+++ b/Tests/LibWeb/Layout/input/text-wrap-balance-below-float-after-margin.html@@ -0,0 +1,28 @@+<!DOCTYPE html>+<style>+ body {+ font: 20px monospace;+ }+ .container {+ display: flow-root;+ margin-bottom: 10px;+ }+ .float {+ float: left;+ width: 200px;+ height: 20px;+ background: orange;+ }+ p {+ width: 300px;+ margin: 30px 0 0;+ }+</style>+<div class="container">+ <div class="float"></div>+ <p style="text-wrap: balance">The quick brown fox jumps over the lazy dog and the cat.</p>+</div>+<div class="container">+ <div class="float"></div>+ <p style="text-wrap: wrap">The quick brown fox jumps over the lazy dog and the cat.</p>+</div>diff --git a/Tests/LibWeb/Layout/input/text-wrap-balance-narrow-space-beside-float.html b/Tests/LibWeb/Layout/input/text-wrap-balance-narrow-space-beside-float.htmlnew file mode 100644index 00000000000..089919de338--- /dev/null+++ b/Tests/LibWeb/Layout/input/text-wrap-balance-narrow-space-beside-float.html@@ -0,0 +1,24 @@+<!DOCTYPE html>+<style>+ body {+ font: 20px monospace;+ }+ .container {+ width: 400px;+ margin-bottom: 10px;+ }+ .float {+ float: left;+ width: 300px;+ height: 40px;+ background: orange;+ }+</style>+<div class="container" style="text-wrap: balance">+ <div class="float"></div>+ abc def ghi jkl mno pqr stu vwx yz abc def ghi jkl+</div>+<div class="container" style="text-wrap: wrap">+ <div class="float"></div>+ abc def ghi jkl mno pqr stu vwx yz abc def ghi jkl+</div>diff --git a/Tests/LibWeb/Layout/input/text-wrap-balance-stretch-float-after-float.html b/Tests/LibWeb/Layout/input/text-wrap-balance-stretch-float-after-float.htmlnew file mode 100644index 00000000000..5b52239ee3d--- /dev/null+++ b/Tests/LibWeb/Layout/input/text-wrap-balance-stretch-float-after-float.html@@ -0,0 +1,32 @@+<!DOCTYPE html>+<style>+ body {+ font: 20px monospace;+ }+ .container {+ width: 400px;+ margin-bottom: 10px;+ }+ .first {+ float: left;+ width: 100px;+ height: 40px;+ background: orange;+ }+ .stretch {+ float: left;+ width: stretch;+ height: 20px;+ background: green;+ }+</style>+<div class="container" style="text-wrap: balance">+ <div class="first"></div>+ <canvas class="stretch"></canvas>+ abc def ghi jkl mno pqr stu vwx yz abc def ghi jkl+</div>+<div class="container" style="text-wrap: wrap">+ <div class="first"></div>+ <canvas class="stretch"></canvas>+ abc def ghi jkl mno pqr stu vwx yz abc def ghi jkl+</div>diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-001-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-001-ref.htmlnew file mode 100644index 00000000000..0e3e5c79677--- /dev/null+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-001-ref.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<style>+.container {+ font: 20px/1.5 monospace;+ width: 23.5ch;+ border: solid 1px;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: left;+}+</style>++<div class="container"><div class="float">FLOAT<br>FLOAT</div>abc de fg<br>hij klm<br>nop qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-002-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-002-ref.htmlnew file mode 100644index 00000000000..fc068905f2f--- /dev/null+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-002-ref.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<style>+.container {+ font: 20px/1.5 monospace;+ width: 23.5ch;+ border: solid 1px;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: right;+}+</style>++<div class="container"><div class="float">FLOAT<br>FLOAT</div>abc de fg<br>hij klm<br>nop qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-005-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-005-ref.htmlnew file mode 100644index 00000000000..b28426f5754--- /dev/null+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-005-ref.html@@ -0,0 +1,22 @@+<!DOCTYPE html>+<style>+.container {+ font: 20px/1.5 monospace;+ width: 26.5ch;+ border: solid 1px;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: left;+}+.float2 {+ background: cyan;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: right;+}+</style>++<div class="container"><div class="float">FLOAT<br>FLOAT</div>abcde fghi<br>jklm nop<div class="float2">FLOAT<br>FLOAT</div><br>qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-006-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-006-ref.htmlnew file mode 100644index 00000000000..6e017371730--- /dev/null+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-006-ref.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<html>+<head>+<meta charset=utf-8>+<style>+body {+ font: 20px/1 monospace;+}+.float {+ float: left;+ width: 15ch;+ height: 150px;+ background: silver;+}+.mask {+ width: 15ch;+ height: 150px;+ background: green;+ position: absolute;+ left: 15ch;+}+.test {+ width: 28ch;+ background: red;+}+</style>+</head>++<body>+<p>There should be no red:</p>+<div class="float">+ <div class="mask"></div>+</div>+<p class="test">+Lorem ipsum dolor <span>sit</span> amet consectetur adipisicing elit.+</p>+</body>+diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-001.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-001.htmlnew file mode 100644index 00000000000..b6b71285aa0--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-001.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<link rel="help" href="https://drafts.csswg.org/css-text-4/#valdef-text-wrap-balance">+<link rel="match" href="../../../../../expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-001-ref.html">+<style>+.container {+ font: 20px/1.5 monospace;+ width: 23.5ch;+ border: solid 1px;+ text-wrap: balance;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: left;+}+</style>++<div class="container"><div class="float">FLOAT<br>FLOAT</div>abc de fg hij klm nop qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-002.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-002.htmlnew file mode 100644index 00000000000..448b48d69c8--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-002.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<link rel="help" href="https://drafts.csswg.org/css-text-4/#valdef-text-wrap-balance">+<link rel="match" href="../../../../../expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-002-ref.html">+<style>+.container {+ font: 20px/1.5 monospace;+ width: 23.5ch;+ border: solid 1px;+ text-wrap: balance;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: right;+}+</style>++<div class="container"><div class="float">FLOAT<br>FLOAT</div>abc de fg hij klm nop qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-003.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-003.htmlnew file mode 100644index 00000000000..1cbe431ef6d--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-003.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<link rel="help" href="https://drafts.csswg.org/css-text-4/#valdef-text-wrap-balance">+<link rel="match" href="../../../../../expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-001-ref.html">+<style>+.container {+ font: 20px/1.5 monospace;+ width: 23.5ch;+ border: solid 1px;+ text-wrap: balance;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: left;+}+</style>++<div class="container">abc de<div class="float">FLOAT<br>FLOAT</div> fg hij klm nop qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-004.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-004.htmlnew file mode 100644index 00000000000..23d3249522b--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-004.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<link rel="help" href="https://drafts.csswg.org/css-text-4/#valdef-text-wrap-balance">+<link rel="match" href="../../../../../expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-002-ref.html">+<style>+.container {+ font: 20px/1.5 monospace;+ width: 23.5ch;+ border: solid 1px;+ text-wrap: balance;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: right;+}+</style>++<div class="container">abc de <div class="float">FLOAT<br>FLOAT</div>fg hij klm nop qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-005.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-005.htmlnew file mode 100644index 00000000000..d132aee7392--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-005.html@@ -0,0 +1,41 @@+<!DOCTYPE html>+<link rel="help" href="https://drafts.csswg.org/css-text-4/#valdef-text-wrap-balance">+<link rel="match" href="../../../../../expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-005-ref.html">+<style>+.container {+ font: 20px/1.5 monospace;+ width: 26.5ch;+ border: solid 1px;+ text-wrap: balance;+}+.float {+ background: yellow;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: left;+}+.float2 {+ background: cyan;+ padding: 0.2em 1ch;+ line-height: 1.2;+ float: right;+}+</style>++<!--+The floats (inc. padding) are 7ch wide, and occupy ~2 lines,+so without balancing, layout would be+ +--------------------------++ | FLOAT abcde fghi jklm nop|+ | FLOAT qrst uvw FLOAT |+ |xyx! FLOAT |+ +--------------------------+++Applying text-wrap:balance results in+ +--------------------------++ | FLOAT abcde fghi |+ | FLOAT jklm nop FLOAT |+ |qrst uvw xyx! FLOAT |+ +--------------------------++-->+<div class="container"><div class="float">FLOAT<br>FLOAT</div>abcde fghi jklm nop<div class="float2">FLOAT<br>FLOAT</div> qrst uvw xyz!</div>diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-006.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-006.htmlnew file mode 100644index 00000000000..3b998ad8701--- /dev/null+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-text/white-space/text-wrap-balance-float-006.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<html>+<head>+<meta charset=utf-8>+<link rel="match" href="../../../../../expected/wpt-import/css/css-text/white-space/reference/text-wrap-balance-float-006-ref.html">+<link rel="help" href="https://drafts.csswg.org/css-text-4/#valdef-text-wrap-balance">+<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1888449">+<style>+body {+ font: 20px/1 monospace;+}+.float {+ float: left;+ width: 15ch;+ height: 150px;+ background: silver;+}+.mask {+ width: 15ch;+ height: 150px;+ background: green;+ position: absolute;+ left: 15ch;+}+.test {+ width: 28ch;+ text-wrap: balance;+ background: red;+}+</style>+</head>++<body>+<p>There should be no red:</p>+<div class="float">+ <div class="mask"></div>+</div>+<p class="test">+Lorem ipsum dolor <span>sit</span> amet consectetur adipisicing elit.+</p>+</body>+