Skip to content

Truly independent web browser

LibWeb: Implement text-wrap-style: balance

Andreas Klingaf794712651f
diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
index 0035938b21e..803805347f3 100644
--- a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
+++ b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs
@@ -1075,6 +1075,10 @@ impl<'a> ComputedValuesView<'a> {
self.inherited_text().overflow_wrap
}
+ pub(crate) fn text_wrap_style(self) -> u8 {
+ self.inherited_text().text_wrap_style
+ }
+
pub(crate) fn text_indent(self) -> LengthPercentageRef<'a> {
self.inherited_text_facts()
.text_indent
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
index 48bae543711..aca3c5c6361 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
@@ -1779,114 +1779,149 @@ impl<'context> InlineFormattingContext<'context> {
}
}
- pub(crate) fn generate_line_boxes(&mut self, mut iterator: inline_level_iterator::InlineLevelIterator) {
- self.fragmented_inlines_in_pre_order = iterator.fragmented_inlines_in_pre_order(self);
- let fragmentation = self.parent.line_root_fragmentation(self.containing_block);
- let resume = fragmentation.and_then(|fragmentation| fragmentation.resume);
- let (reused_lines, reused_item_count) = if self.parent.has_line_clamp() || resume.is_some() {
- Default::default()
- } else {
- self.parent
- .previous_line_data
- .as_deref()
- .map(|previous| self.reusable_atomic_line_prefix(previous, &iterator))
- .unwrap_or_default()
- };
+ /// 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.
+ fn balances_lines(
+ &self,
+ iterator: &inline_level_iterator::InlineLevelIterator,
+ fragmentation: Option<fragmentation::LineRootFragmentation>,
+ ) -> bool {
+ let style = self.style(self.containing_block);
+ if style.text_wrap_style() != text_wrap_style::BALANCE || style.text_wrap_mode() != text_wrap_mode::WRAP {
+ return false;
+ }
+ if self.parent.has_line_clamp()
+ || self.run.fragmentainer.is_some()
+ || iterator.shares_items()
+ || fragmentation.is_some()
{
- let mut data = self.line_data_mut();
- data.line_boxes = reused_lines;
- data.inline_box_pieces.clear();
- data.lines_after_clamp_point_rect = None;
+ return false;
}
- let item_count = iterator.items().len();
- let start_item_index = resume.map_or(reused_item_count, |resume| resume.item_index.min(item_count));
- let shares_items = iterator.shares_items();
- let skipped_atomic_inlines: Vec<Node> = if resume.is_some() && !shares_items {
- iterator.items()[..start_item_index]
- .iter()
- .filter(|item| item.type_ == inline_level_iterator::ItemType::Element)
- .map(|item| item.node)
- .collect()
- } else {
- Vec::new()
+ if !matches!(self.input.available_space.inline_size, AvailableSize::Definite(available) if available > CssPixels::default())
+ {
+ return false;
+ }
+ if self.any_floats_intrude_in_block_range(CssPixels::default(), max_dimension_value()) {
+ return false;
+ }
+ iterator.items().iter().all(|item| item.type_.stays_on_lines())
+ }
+
+ // https://drafts.csswg.org/css-text-4/#valdef-text-wrap-style-balance
+ // Line breaks are chosen to balance the remaining (empty) space in each line box, if better balance than auto is
+ // 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.
+ // ...
+ // 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>> {
+ let items = iterator.items();
+ let mut balanced_inline_sizes = 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
+ }
+
+ /// 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,
+ iterator: &inline_level_iterator::InlineLevelIterator,
+ group: std::ops::Range<usize>,
+ follows_forced_break: bool,
+ ) -> Option<CssPixels> {
+ // INTEROP: Only balance up to 6 lines, since each try breaks all of the lines again.
+ const MAXIMUM_LINE_COUNT: usize = 6;
+ let available_inline_size = self.input.available_space.inline_size.to_px_or_zero();
+ // NB: Skip measuring lines for content far too long to balance.
+ let content_inline_size = iterator.items()[group.clone()]
+ .iter()
+ .fold(CssPixels::default(), |sum, item| sum + item.border_box_inline_size());
+ 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 mut pending_resume_offset = resume.map(|resume| resume.offset_in_node);
- self.inline_boxes_continued_from_previous_fragment = {
- let (before, after) = iterator.items().split_at(start_item_index.min(item_count));
- let has_node = |item: &&inline_level_iterator::Item| !item.node.is_invalid();
- let left_fragment = |item: &&inline_level_iterator::Item| {
- has_node(item)
- && item.type_ != inline_level_iterator::ItemType::ForcedBreak
- && item.type_ != inline_level_iterator::ItemType::AbsolutelyPositionedElement
- && !item.is_collapsible_whitespace
- };
- match after.first() {
- Some(item) if pending_resume_offset.is_some_and(|offset| offset > item.offset_in_node) => {
- self.fragmented_inline_ancestors(item.node)
- }
- _ if resume.is_some() => match (before.iter().rev().find(left_fragment), after.iter().find(has_node)) {
- (Some(before), Some(after)) => self.fragmented_inline_ancestors_spanning(before.node, after.node),
- _ => Vec::new(),
- },
- _ => Vec::new(),
+ let (line_count, inline_size_of_lines) = find_line_breaks(available_inline_size);
+ 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;
+ if find_line_breaks(candidate).0 <= line_count {
+ balanced_inline_size = candidate;
+ } else {
+ too_narrow = candidate;
}
- };
- let resumes_after_forced_break = resume.is_some()
- && start_item_index > 0
- && iterator.items()[start_item_index - 1].type_ == inline_level_iterator::ItemType::ForcedBreak;
- iterator.skip_items(start_item_index);
- self.current_line_start.set(fragmentation::LinePosition {
- item_index: start_item_index,
- offset_in_node: pending_resume_offset.unwrap_or_default(),
+ }
+ (balanced_inline_size < available_inline_size).then_some(balanced_inline_size)
+ }
+
+ /// 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,
+ iterator: &inline_level_iterator::InlineLevelIterator,
+ group: std::ops::Range<usize>,
+ follows_forced_break: bool,
+ inline_size: 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
});
- let reused_line_count = self.line_data().line_boxes.len();
- let mut line_builder = if resume.is_some() {
- line_builder::LineBuilder::new_for_continuation(self, resumes_after_forced_break)
- } else if reused_line_count == 0 {
- line_builder::LineBuilder::new(self)
- } else {
- line_builder::LineBuilder::new_after_reused_lines(self)
- };
+ (lines.len(), inline_size_of_lines)
+ }
+ /// Breaks the items left in `iterator` into lines with `line_builder`. `item_count` is the number of items the
+ /// iterator started with.
+ fn break_items_into_lines<'builder>(
+ &'builder self,
+ iterator: &mut inline_level_iterator::InlineLevelIterator,
+ line_builder: &mut line_builder::LineBuilder<'builder, 'context>,
+ item_count: usize,
+ mut pending_resume_offset: Option<usize>,
+ mut line_limit: Option<FragmentainerLineLimit>,
+ mut consumed_item_nodes: Option<Vec<(usize, Node)>>,
+ ) -> BrokenLines<'builder, 'context> {
+ let shares_items = iterator.shares_items();
let mut leading_margin = CssPixels::default();
let mut leading_border = CssPixels::default();
let mut leading_padding = CssPixels::default();
let mut absolute_boxes = Vec::new();
-
let mut previous_text_item_allows_overflow_break_after = false;
let mut state_at_clamp_point = None;
let mut items_after_clamp_point = Vec::new();
- let mut floating_boxes_after_clamp_point = Vec::new();
- let floating_box_count_before_lines = self.parent.floating_box_count();
- let mut line_limit = fragmentation
- .filter(|_| !self.parent.has_line_clamp())
- .and_then(|fragmentation| fragmentation.block_size)
- .filter(|_| {
- shares_items
- || iterator.items().iter().all(|item| {
- matches!(
- item.type_,
- inline_level_iterator::ItemType::Text
- | inline_level_iterator::ItemType::Element
- | inline_level_iterator::ItemType::ForcedBreak
- | inline_level_iterator::ItemType::AbsolutelyPositionedElement
- )
- })
- })
- .map(|block_size| FragmentainerLineLimit {
- block_size,
- widows: self.style(self.containing_block).widows().max(1) as usize,
- checked_line_count: 0,
- lines_past_end: 0,
- minimum_line_block_size: None,
- });
let mut stopped_at_line_limit = false;
- let mut consumed_item_nodes = (self.run.fragmentainer.is_some()
- && self.run.fragments.is_some()
- && !iterator.entered_inline_boxes().is_empty())
- .then(Vec::new);
loop {
- if self.stops_at_line_clamp_point(&line_builder, &mut state_at_clamp_point) {
+ if self.stops_at_line_clamp_point(line_builder, &mut state_at_clamp_point) {
break;
}
if line_limit.as_mut().is_some_and(|limit| limit.is_reached(self)) {
@@ -1958,7 +1993,11 @@ impl<'context> InlineFormattingContext<'context> {
});
let continuation = iterator.next_inline_run_size(self);
line_builder.break_line(line_builder::ForcedBreak::Yes, item.node, continuation);
- if !item.node.is_invalid() && self.clear_floating_boxes(item.node) {
+ // 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)
+ {
line_builder.did_introduce_clearance(self.block_axis_float_clearance.get());
self.reset_parent_margin_state();
}
@@ -1971,10 +2010,12 @@ impl<'context> InlineFormattingContext<'context> {
let (_, laid_out_cells) = self.dimension_box_on_line(item.node, cells);
item.box_cells = Some(Box::new(laid_out_cells));
}
- let insets = self.compute_inset(item.node);
- self.update_placed_atomic_inline(item.node, |placed_child| {
- placed_child.with_in_flow_box_insets(insets)
- });
+ if !line_builder.only_finds_line_breaks() {
+ let insets = self.compute_inset(item.node);
+ self.update_placed_atomic_inline(item.node, |placed_child| {
+ placed_child.with_in_flow_box_insets(insets)
+ });
+ }
if self.style(self.containing_block).text_wrap_mode() == text_wrap_mode::WRAP {
let mut minimum = item.border_box_inline_size();
if item.margin_start < CssPixels::default() {
@@ -1986,7 +2027,7 @@ impl<'context> InlineFormattingContext<'context> {
line_builder.break_if_needed(minimum);
line_builder.note_soft_wrap_opportunity();
}
- if self.stops_at_line_clamp_point(&line_builder, &mut state_at_clamp_point) {
+ if self.stops_at_line_clamp_point(line_builder, &mut state_at_clamp_point) {
break;
}
line_builder.append_box(&item);
@@ -1996,7 +2037,7 @@ impl<'context> InlineFormattingContext<'context> {
leading_border += item.border_start;
leading_padding += item.padding_start;
line_builder.finish_current_line_before_block_level_box();
- if self.stops_at_line_clamp_point(&line_builder, &mut state_at_clamp_point) {
+ if self.stops_at_line_clamp_point(line_builder, &mut state_at_clamp_point) {
break;
}
let relative_insets = self.relative_insets_of_inline_ancestors(self.callbacks.parent(item.node));
@@ -2006,7 +2047,7 @@ impl<'context> InlineFormattingContext<'context> {
self.block_container,
self.input,
self.containing_block_position_in_bfc_root,
- &mut line_builder,
+ line_builder,
state_at_clamp_point.is_some(),
if relative_insets.found_fragmented_inline_node {
FfiCssPixelPoint {
@@ -2060,7 +2101,7 @@ impl<'context> InlineFormattingContext<'context> {
self.input,
self.containing_block_position_in_bfc_root,
CssPixels::default(),
- Some(&mut line_builder),
+ Some(&mut *line_builder),
run_state::FragmentFactsDecidedByParent {
is_invisible_for_line_clamp: state_at_clamp_point.is_some(),
..run_state::FragmentFactsDecidedByParent::default()
@@ -2122,7 +2163,7 @@ impl<'context> InlineFormattingContext<'context> {
}
if overflow_break_allowed {
if self.break_overflowing_text_item(
- &mut line_builder,
+ line_builder,
&mut item,
item_index,
line_limit.as_mut(),
@@ -2134,13 +2175,132 @@ impl<'context> InlineFormattingContext<'context> {
previous_text_item_allows_overflow_break_after = true;
}
}
- if self.stops_at_line_clamp_point(&line_builder, &mut state_at_clamp_point) {
+ if self.stops_at_line_clamp_point(line_builder, &mut state_at_clamp_point) {
break;
}
line_builder.append_text_item(&mut item, style.line_height());
}
}
}
+ BrokenLines {
+ absolute_boxes,
+ state_at_clamp_point,
+ items_after_clamp_point,
+ stopped_at_line_limit,
+ consumed_item_nodes,
+ }
+ }
+
+ pub(crate) fn generate_line_boxes(&mut self, mut iterator: inline_level_iterator::InlineLevelIterator) {
+ self.fragmented_inlines_in_pre_order = iterator.fragmented_inlines_in_pre_order(self);
+ let fragmentation = self.parent.line_root_fragmentation(self.containing_block);
+ let resume = fragmentation.and_then(|fragmentation| fragmentation.resume);
+ let balances_lines = self.balances_lines(&iterator, fragmentation);
+ let (reused_lines, reused_item_count) = if self.parent.has_line_clamp() || resume.is_some() || balances_lines {
+ Default::default()
+ } else {
+ self.parent
+ .previous_line_data
+ .as_deref()
+ .map(|previous| self.reusable_atomic_line_prefix(previous, &iterator))
+ .unwrap_or_default()
+ };
+ {
+ let mut data = self.line_data_mut();
+ data.line_boxes = reused_lines;
+ data.inline_box_pieces.clear();
+ data.lines_after_clamp_point_rect = None;
+ }
+ let item_count = iterator.items().len();
+ let start_item_index = resume.map_or(reused_item_count, |resume| resume.item_index.min(item_count));
+ let shares_items = iterator.shares_items();
+ let skipped_atomic_inlines: Vec<Node> = if resume.is_some() && !shares_items {
+ iterator.items()[..start_item_index]
+ .iter()
+ .filter(|item| item.type_ == inline_level_iterator::ItemType::Element)
+ .map(|item| item.node)
+ .collect()
+ } else {
+ Vec::new()
+ };
+ let pending_resume_offset = resume.map(|resume| resume.offset_in_node);
+ self.inline_boxes_continued_from_previous_fragment = {
+ let (before, after) = iterator.items().split_at(start_item_index.min(item_count));
+ let has_node = |item: &&inline_level_iterator::Item| !item.node.is_invalid();
+ let left_fragment = |item: &&inline_level_iterator::Item| {
+ has_node(item)
+ && item.type_ != inline_level_iterator::ItemType::ForcedBreak
+ && item.type_ != inline_level_iterator::ItemType::AbsolutelyPositionedElement
+ && !item.is_collapsible_whitespace
+ };
+ match after.first() {
+ Some(item) if pending_resume_offset.is_some_and(|offset| offset > item.offset_in_node) => {
+ self.fragmented_inline_ancestors(item.node)
+ }
+ _ if resume.is_some() => match (before.iter().rev().find(left_fragment), after.iter().find(has_node)) {
+ (Some(before), Some(after)) => self.fragmented_inline_ancestors_spanning(before.node, after.node),
+ _ => Vec::new(),
+ },
+ _ => Vec::new(),
+ }
+ };
+ let resumes_after_forced_break = resume.is_some()
+ && start_item_index > 0
+ && 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)
+ } else {
+ Vec::new()
+ };
+ self.current_line_start.set(fragmentation::LinePosition {
+ item_index: start_item_index,
+ offset_in_node: pending_resume_offset.unwrap_or_default(),
+ });
+ let reused_line_count = self.line_data().line_boxes.len();
+ let mut line_builder = if resume.is_some() {
+ line_builder::LineBuilder::new_for_continuation(self, resumes_after_forced_break)
+ } else if reused_line_count == 0 {
+ line_builder::LineBuilder::new(self)
+ } 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);
+ }
+
+ let mut floating_boxes_after_clamp_point = Vec::new();
+ let floating_box_count_before_lines = self.parent.floating_box_count();
+ let line_limit = fragmentation
+ .filter(|_| !self.parent.has_line_clamp())
+ .and_then(|fragmentation| fragmentation.block_size)
+ .filter(|_| shares_items || iterator.items().iter().all(|item| item.type_.stays_on_lines()))
+ .map(|block_size| FragmentainerLineLimit {
+ block_size,
+ widows: self.style(self.containing_block).widows().max(1) as usize,
+ checked_line_count: 0,
+ lines_past_end: 0,
+ minimum_line_block_size: None,
+ });
+ let consumed_item_nodes = (self.run.fragmentainer.is_some()
+ && self.run.fragments.is_some()
+ && !iterator.entered_inline_boxes().is_empty())
+ .then(Vec::new);
+ let BrokenLines {
+ mut absolute_boxes,
+ state_at_clamp_point,
+ items_after_clamp_point,
+ stopped_at_line_limit,
+ consumed_item_nodes,
+ } = self.break_items_into_lines(
+ &mut iterator,
+ &mut line_builder,
+ item_count,
+ pending_resume_offset,
+ line_limit,
+ consumed_item_nodes,
+ );
if let Some(state_at_clamp_point) = state_at_clamp_point {
line_builder.update_last_line(false);
@@ -2732,6 +2892,15 @@ impl<'context> InlineFormattingContext<'context> {
}
}
+/// What breaking the items into lines left to finish once the lines are built.
+struct BrokenLines<'builder, 'context> {
+ absolute_boxes: Vec<Node>,
+ state_at_clamp_point: Option<LineBuildingState<'builder, 'context>>,
+ items_after_clamp_point: Vec<(inline_level_iterator::ItemType, Node)>,
+ stopped_at_line_limit: bool,
+ consumed_item_nodes: Option<Vec<(usize, Node)>>,
+}
+
struct LineBuildingState<'builder, 'context> {
line_builder: line_builder::LineBuilder<'builder, 'context>,
current_line_index: usize,
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
index df962f7733d..04be6265002 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
@@ -16,6 +16,17 @@ pub(crate) enum ItemType {
FloatingElement,
}
+impl ItemType {
+ /// Whether an item of this type takes its place on the lines alone, unlike floats and block-level boxes, which lay
+ /// out beside or between the lines.
+ pub(crate) fn stays_on_lines(self) -> bool {
+ matches!(
+ self,
+ Self::Text | Self::Element | Self::ForcedBreak | Self::AbsolutelyPositionedElement
+ )
+ }
+}
+
#[derive(Clone, Debug)]
pub(crate) struct Item {
pub(crate) type_: ItemType,
@@ -1180,12 +1191,7 @@ impl InlineLevelIterator {
};
}
let iterator = Self::new(context);
- if !iterator.items.as_slice().iter().all(|item| {
- matches!(
- item.type_,
- ItemType::Text | ItemType::ForcedBreak | ItemType::Element | ItemType::AbsolutelyPositionedElement
- )
- }) {
+ if !iterator.items.as_slice().iter().all(|item| item.type_.stays_on_lines()) {
return iterator;
}
let items = iterator.items.into_vec();
@@ -1295,6 +1301,15 @@ 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();
+ Self {
+ entered_box_model_nodes: self.entered_box_model_nodes.clone(),
+ items: ItemQueue::Owned(items.into_iter()),
+ }
+ }
+
pub(crate) fn next_inline_run_size(
&self,
context: &inline_formatting_context::InlineFormattingContext<'_>,
diff --git a/Libraries/LibWeb/Rust/src/layout/line_builder.rs b/Libraries/LibWeb/Rust/src/layout/line_builder.rs
index 24a81a1cb46..62e557fe94c 100644
--- a/Libraries/LibWeb/Rust/src/layout/line_builder.rs
+++ b/Libraries/LibWeb/Rust/src/layout/line_builder.rs
@@ -54,6 +54,13 @@ 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>>,
+ 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.
+ only_finds_line_breaks: bool,
current_block_offset: CssPixels,
max_block_size_on_current_line: CssPixels,
unbreakable_run_inline_size_interrupted_by_float: CssPixels,
@@ -79,6 +86,33 @@ 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`.
+ 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
+ }
+
+ 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 new_for_continuation(
context: &'builder inline_formatting_context::InlineFormattingContext<'context>,
after_forced_break: bool,
@@ -103,6 +137,9 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
Self {
context,
available_inline_size_for_current_line: AvailableSize::Indefinite,
+ balanced_inline_sizes: Vec::new(),
+ forced_break_count: 0,
+ only_finds_line_breaks: false,
current_block_offset: CssPixels::default(),
max_block_size_on_current_line: CssPixels::default(),
unbreakable_run_inline_size_interrupted_by_float: CssPixels::default(),
@@ -270,6 +307,9 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
}
self.last_line_needs_update = true;
self.update_last_line(forced == ForcedBreak::No || next_size.is_some());
+ if forced == ForcedBreak::Yes {
+ self.forced_break_count += 1;
+ }
let mut break_count = 0usize;
loop {
@@ -299,19 +339,40 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
self.line_count() == 0 || self.line(self.line_count() - 1).is_empty()
}
- fn remaining_inline_size_on_current_line(&mut self) -> Option<CssPixels> {
- let AvailableSize::Definite(available) = self.available_inline_size_for_current_line else {
+ /// 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
+ .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)),
+ (available, _) => available,
+ }
+ }
+
+ fn remaining_inline_size_on_current_line_within(&mut self, inline_size: AvailableSize) -> Option<CssPixels> {
+ let AvailableSize::Definite(available) = inline_size else {
return None;
};
let line_index = self.ensure_last_line_index();
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.
pub(crate) fn remaining_inline_size_for_overflow_break(&mut self) -> Option<CssPixels> {
- match self.available_inline_size_for_current_line {
- AvailableSize::Definite(_) => self.remaining_inline_size_on_current_line(),
- _ => None,
- }
+ self.remaining_inline_size_on_current_line_within(self.available_inline_size_for_current_line)
+ }
+
+ pub(crate) fn only_finds_line_breaks(&self) -> bool {
+ self.only_finds_line_breaks
}
pub(crate) fn break_if_needed(&mut self, next_item_inline_size: CssPixels) -> bool {
@@ -483,7 +544,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 {
+ if self.line(line_index).has_block_level_box || self.only_finds_line_breaks {
return;
}
let margin = self.context().parent_commit_pending_margin_before_inline_content();
@@ -617,7 +678,7 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
}
let line_index = self.ensure_last_line_index();
let current_inline_size = self.line(line_index).physical_horizontal_extent();
- self.available_inline_size_for_current_line
+ self.inline_size_to_break_current_line_at()
.pixels_greater_than(current_inline_size + next_item_inline_size)
}
diff --git a/Tests/LibWeb/Layout/expected/text-wrap-balance.txt b/Tests/LibWeb/Layout/expected/text-wrap-balance.txt
new file mode 100644
index 00000000000..28e3010d175
--- /dev/null
+++ b/Tests/LibWeb/Layout/expected/text-wrap-balance.txt
@@ -0,0 +1,87 @@
+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 468 0+0+0] [BFC] children: not-inline
+ BlockContainer <body> at [8,8] [8+0+0 784 0+0+8] [8+0+0 450 0+0+8] children: not-inline
+ BlockContainer <div#two-lines> at [8,8] [0+0+0 300 0+0+484] [0+0+0 40 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 19, rect: [8,8 215.40625x20] baseline: 16
+ "The quick brown fox"
+ frag 1 from TextNode start: 20, length: 24, rect: [8,28 249.34375x20] baseline: 16
+ "jumps over the lazy dog."
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,58] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline
+ TextNode <#text> (not painted)
+ BlockContainer <div#three-lines-centered> at [8,58] [0+0+0 300 0+0+484] [0+0+0 100 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 21, rect: [36.578125,58 242.828125x20] baseline: 16
+ "Servo aims to empower"
+ frag 1 from TextNode start: 22, length: 17, rect: [69.40625,78 177.171875x20] baseline: 16
+ "developers with a"
+ frag 2 from TextNode start: 40, length: 29, rect: [12.75,98 290.5x20] baseline: 16
+ "lightweight, high-performance"
+ frag 3 from TextNode start: 70, length: 25, rect: [30.796875,118 254.40625x20] baseline: 16
+ "alternative for embedding"
+ frag 4 from TextNode start: 96, length: 17, rect: [70.296875,138 175.40625x20] baseline: 16
+ "web technologies."
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,168] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline
+ TextNode <#text> (not painted)
+ BlockContainer <div#one-line> at [8,168] [0+0+0 300 0+0+484] [0+0+0 20 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 11, rect: [8,168 114.78125x20] baseline: 16
+ "Short text."
+ 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 <div#forced-break> at [8,198] [0+0+0 300 0+0+484] [0+0+0 40 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 25, rect: [8,198 284.390625x20] baseline: 16
+ "The quick brown fox jumps"
+ frag 1 from TextNode start: 0, length: 18, rect: [8,218 180.359375x20] baseline: 16
+ "over the lazy dog."
+ TextNode <#text> (not painted)
+ BreakNode <br> (not painted)
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,248] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline
+ TextNode <#text> (not painted)
+ BlockContainer <div#inline-box> at [8,248] [0+0+0 300 0+0+484] [0+0+0 40 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 10, rect: [8,248 110.40625x20] baseline: 16
+ "The quick "
+ frag 1 from TextNode start: 0, length: 14, rect: [122.125,268 135.21875x20] baseline: 16
+ " the lazy dog."
+ TextNode <#text> (not painted)
+ InlineNode <b> at [8,248] [0+0+0 215.40625 0+0+0] [0+0+0 40 0+0+0]
+ frag 0 from TextNode start: 0, length: 9, rect: [118.40625,248 105x20] baseline: 16
+ "brown fox"
+ frag 0 from TextNode start: 10, length: 10, rect: [8,268 114.125x20] baseline: 16
+ "jumps over"
+ TextNode <#text> (not painted)
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,298] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline
+ TextNode <#text> (not painted)
+ BlockContainer <div#not-balanced> at [8,298] [0+0+0 300 0+0+484] [0+0+0 40 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 25, rect: [8,298 284.390625x20] baseline: 16
+ "The quick brown fox jumps"
+ frag 1 from TextNode start: 26, length: 18, rect: [8,318 180.359375x20] baseline: 16
+ "over the lazy dog."
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,348] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline
+ TextNode <#text> (not painted)
+ BlockContainer <div#overflow-wrap-anywhere> at [8,348] [0+0+0 300 0+0+484] [0+0+0 40 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 17, rect: [8,348 170.203125x20] baseline: 16
+ "a b c d e f g h i"
+ frag 1 from TextNode start: 18, length: 30, rect: [8,368 285.78125x20] baseline: 16
+ "Supercalifragilisticexpialidoc"
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,398] [0+0+0 784 0+0+0] [0+0+0 0 0+0+0] children: inline
+ TextNode <#text> (not painted)
+ BlockContainer <div#groups-balanced-separately> at [8,398] [0+0+0 300 0+0+484] [0+0+0 60 0+0+10] children: inline
+ frag 0 from TextNode start: 0, length: 29, rect: [8,398 294.1875x20] baseline: 16
+ "The first group fits one line"
+ frag 1 from TextNode start: 0, length: 19, rect: [8,418 215.40625x20] baseline: 16
+ "The quick brown fox"
+ frag 2 from TextNode start: 20, length: 24, rect: [8,438 249.34375x20] baseline: 16
+ "jumps over the lazy dog."
+ TextNode <#text> (not painted)
+ BreakNode <br> (not painted)
+ TextNode <#text> (not painted)
+ BlockContainer <(anonymous)> at [8,468] [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 800x468] (z-index: auto)
diff --git a/Tests/LibWeb/Layout/input/text-wrap-balance.html b/Tests/LibWeb/Layout/input/text-wrap-balance.html
new file mode 100644
index 00000000000..c154e442e04
--- /dev/null
+++ b/Tests/LibWeb/Layout/input/text-wrap-balance.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<style>
+ div {
+ font: 20px monospace;
+ width: 300px;
+ text-wrap: balance;
+ margin-bottom: 10px;
+ }
+</style>
+<div id="two-lines">The quick brown fox jumps over the lazy dog.</div>
+<div id="three-lines-centered" style="text-align: center">Servo aims to empower developers with a lightweight, high-performance alternative for embedding web technologies.</div>
+<div id="one-line">Short text.</div>
+<div id="forced-break">The quick brown fox jumps<br>over the lazy dog.</div>
+<div id="inline-box">The quick <b>brown fox jumps over</b> the lazy dog.</div>
+<div id="not-balanced" style="text-wrap: wrap">The quick brown fox jumps over the lazy dog.</div>
+<div id="overflow-wrap-anywhere" style="overflow-wrap: anywhere">a b c d e f g h i Supercalifragilisticexpialidoc</div>
+<div id="groups-balanced-separately">The first group fits one line<br>The quick brown fox jumps over the lazy dog.</div>