Skip to content

Truly independent web browser

LibWeb: Preserve shaping across unused line breaks

sideshowbarker7ca5630d6553
diff --git a/Libraries/LibGfx/Rust/src/text_layout.rs b/Libraries/LibGfx/Rust/src/text_layout.rs
index 80efc0693cc..57cc168b379 100644
--- a/Libraries/LibGfx/Rust/src/text_layout.rs
+++ b/Libraries/LibGfx/Rust/src/text_layout.rs
@@ -162,7 +162,7 @@ unsafe extern "C" {
word_spacing: f32,
joining_context: JoiningContext,
sink: *mut c_void,
- emit: unsafe extern "C" fn(*mut c_void, *const ShapedGlyph, usize, f32, usize, f32),
+ emit: unsafe extern "C" fn(*mut c_void, *const ShapedGlyph, usize, f32, usize, f32, bool),
);
fn ladybird_gfx_glyph_run_bounding_box(
@@ -725,6 +725,7 @@ struct CachedShape {
width: f32,
trailing_whitespace_length_in_code_units: usize,
trailing_whitespace_advance: f32,
+ requires_context_for_breaks: bool,
}
impl CachedShape {
@@ -734,6 +735,7 @@ impl CachedShape {
fn is_bitwise_equal_to(&self, other: &CachedShape) -> bool {
self.width.to_bits() == other.width.to_bits()
+ && self.requires_context_for_breaks == other.requires_context_for_breaks
&& self.trailing_whitespace_length_in_code_units == other.trailing_whitespace_length_in_code_units
&& self.trailing_whitespace_advance.to_bits() == other.trailing_whitespace_advance.to_bits()
&& self.glyphs.len() == other.glyphs.len()
@@ -757,6 +759,7 @@ impl SharedShape {
width,
trailing_whitespace_length_in_code_units,
trailing_whitespace_advance,
+ requires_context_for_breaks: true,
}))
}
@@ -780,6 +783,11 @@ impl SharedShape {
self.0.trailing_whitespace_advance
}
+ /// Whether splitting the text can change its glyphs, so that separately shaped chunks might not reproduce it.
+ pub fn requires_context_for_breaks(&self) -> bool {
+ self.0.requires_context_for_breaks
+ }
+
pub fn with_baseline_start(&self, baseline_start_x: f32) -> ShapedText {
shaped_text_with_baseline_start(&self.0, baseline_start_x)
}
@@ -1001,6 +1009,7 @@ fn shape_text_uncached(font: &FontHandle, text: &[u16], params: ShapeParams) ->
width: f32,
trailing_whitespace_length_in_code_units: usize,
trailing_whitespace_advance: f32,
+ requires_context_for_breaks: bool,
) {
// SAFETY: `sink` is the Option<CachedShape> passed below, and the
// glyph pointer stays valid for this synchronous callback.
@@ -1018,6 +1027,7 @@ fn shape_text_uncached(font: &FontHandle, text: &[u16], params: ShapeParams) ->
width,
trailing_whitespace_length_in_code_units,
trailing_whitespace_advance,
+ requires_context_for_breaks,
});
}
// The shape is built in the callback, so a cache miss allocates the glyph
@@ -1380,6 +1390,7 @@ mod shaping_cache_tests {
CachedShape {
glyphs: GlyphBuffer::from_shaped(&vec![ShapedGlyph::default(); glyph_count]),
width: glyph_count as f32,
+ requires_context_for_breaks: false,
trailing_whitespace_length_in_code_units: 0,
trailing_whitespace_advance: 0.0,
}
diff --git a/Libraries/LibGfx/TextLayout.cpp b/Libraries/LibGfx/TextLayout.cpp
index 83ca902481a..b0fc2e35fcb 100644
--- a/Libraries/LibGfx/TextLayout.cpp
+++ b/Libraries/LibGfx/TextLayout.cpp
@@ -493,6 +493,7 @@ struct ShapedGlyphs {
Vector<ShapedGlyph> glyphs;
float width { 0 };
TrailingWhitespace trailing_whitespace;
+ bool requires_context_for_breaks { false };
};
static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font const& font, FFI::TextType text_type, float letter_spacing, float word_spacing, FFI::JoiningContext joining_context)
@@ -507,6 +508,7 @@ static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font co
Vector<ShapedGlyph> glyphs;
glyphs.ensure_capacity(glyph_count);
FloatPoint point;
+ bool requires_context_for_breaks = false;
// The trailing whitespace advance is recorded so that trimming it at line end can subtract exactly what shaping
// added, spacing included.
@@ -557,6 +559,9 @@ static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font co
// Every glyph of a cluster gets the same answer, so it's worked out once, at the cluster's first glyph.
if (i == 0 || glyph_info[i - 1].cluster != glyph_info[i].cluster)
should_paint = should_paint_glyph(i);
+ auto glyph_length = glyph_length_in_code_units(i);
+ requires_context_for_breaks |= glyph_length > 1
+ || (hb_glyph_info_get_glyph_flags(&glyph_info[i]) & HB_GLYPH_FLAG_UNSAFE_TO_BREAK);
auto position = point
- FloatPoint { 0, metrics.ascent }
+ FloatPoint { positions[i].x_offset, -positions[i].y_offset } / text_shaping_resolution;
@@ -568,7 +573,7 @@ static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font co
glyphs.unchecked_append({
.position = position,
- .length_in_code_units = glyph_length_in_code_units(i),
+ .length_in_code_units = glyph_length,
.glyph_width = should_paint ? positions[i].x_advance / text_shaping_resolution + extra_advance : 0,
.glyph_id = glyph_info[i].codepoint,
.cluster_start = glyph_info[i].cluster,
@@ -591,7 +596,7 @@ static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font co
hb_buffer_destroy(buffer);
- return ShapedGlyphs { move(glyphs), point.x(), trailing_whitespace };
+ return ShapedGlyphs { move(glyphs), point.x(), trailing_whitespace, requires_context_for_breaks };
}
float measure_text_width(Utf16View const& string, Font const& font, float letter_spacing)
@@ -624,7 +629,7 @@ static_assert(offsetof(Gfx::FFI::ShapedGlyph, glyph_id) == offsetof(Gfx::ShapedG
static_assert(offsetof(Gfx::FFI::ShapedGlyph, should_paint) == offsetof(Gfx::ShapedGlyph, should_paint));
extern "C" {
-void ladybird_gfx_shape_text_uncached(void const*, u16 const*, size_t, Gfx::FFI::TextType, float, float, Gfx::FFI::JoiningContext, void*, void (*)(void*, Gfx::FFI::ShapedGlyph const*, size_t, float, size_t, float));
+void ladybird_gfx_shape_text_uncached(void const*, u16 const*, size_t, Gfx::FFI::TextType, float, float, Gfx::FFI::JoiningContext, void*, void (*)(void*, Gfx::FFI::ShapedGlyph const*, size_t, float, size_t, float, bool));
float ladybird_gfx_font_measure_text_width(void const*, u16 const*, size_t);
void ladybird_gfx_glyph_run_bounding_box(void const*, Gfx::FFI::ShapedGlyph const*, size_t, float, float*);
void ladybird_gfx_glyph_run_ink_bounding_box(void const*, Gfx::FFI::ShapedGlyph const*, size_t, float, float*);
@@ -640,7 +645,7 @@ extern "C" void ladybird_gfx_shape_text_uncached(
float word_spacing,
Gfx::FFI::JoiningContext joining_context,
void* sink,
- void (*emit)(void*, Gfx::FFI::ShapedGlyph const*, size_t, float, size_t, float))
+ void (*emit)(void*, Gfx::FFI::ShapedGlyph const*, size_t, float, size_t, float, bool))
{
VERIFY(font);
VERIFY(text_utf16 || length_in_code_units == 0);
@@ -661,7 +666,8 @@ extern "C" void ladybird_gfx_shape_text_uncached(
shape.glyphs.size(),
shape.width,
shape.trailing_whitespace.length_in_code_units,
- shape.trailing_whitespace.advance);
+ shape.trailing_whitespace.advance,
+ shape.requires_context_for_breaks);
}
extern "C" float ladybird_gfx_font_measure_text_width(
diff --git a/Libraries/LibWeb/Rust/src/gfx_test_stubs.rs b/Libraries/LibWeb/Rust/src/gfx_test_stubs.rs
index e691f0b02fa..0c8e3ea44f3 100644
--- a/Libraries/LibWeb/Rust/src/gfx_test_stubs.rs
+++ b/Libraries/LibWeb/Rust/src/gfx_test_stubs.rs
@@ -118,7 +118,7 @@ extern "C" fn ladybird_gfx_shape_text_uncached(
_word_spacing: f32,
_joining_context: JoiningContext,
_sink: *mut c_void,
- _emit: unsafe extern "C" fn(*mut c_void, *const ShapedGlyph, usize, f32, usize, f32),
+ _emit: unsafe extern "C" fn(*mut c_void, *const ShapedGlyph, usize, f32, usize, f32, bool),
) {
unreachable!("no unit test shapes text");
}
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
index df3af51eccd..87cc65c7aed 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs
@@ -178,26 +178,71 @@ fn apply_block_ellipsis(
let has_text_overflow_ellipsis = line
.visible_fragments()
.any(|fragment| fragment.has_text_overflow_ellipsis);
- let opportunity = line.fragments.iter().enumerate().rev().find_map(|(index, fragment)| {
- let trailing = fragment.trailing_whitespace;
- let inline_size = fragment.inline_length - trailing.inline_size;
- let inline_offset = fragment.inline_offset + inline_size;
- (fragment.has_soft_wrap_opportunity_after && inline_offset <= available_for_content).then_some((
- index + 1,
- inline_offset,
- fragment.length_in_code_units - trailing.length_in_code_units,
- inline_size,
- ))
- });
- let (first_displaced_fragment, retained_inline_size) = if line.inline_length <= available_for_content
- && !has_text_overflow_ellipsis
- {
+ let content_fits = line.inline_length <= available_for_content && !has_text_overflow_ellipsis;
+ let opportunity = if content_fits {
+ None
+ } else {
+ line.fragments.iter().enumerate().rev().find_map(|(index, fragment)| {
+ let trailing = fragment.trailing_whitespace;
+ let inline_size = fragment.inline_length - trailing.inline_size;
+ let inline_offset = fragment.inline_offset + inline_size;
+ if fragment.has_soft_wrap_opportunity_after && inline_offset <= available_for_content {
+ return Some((
+ index + 1,
+ inline_offset,
+ fragment.length_in_code_units - trailing.length_in_code_units,
+ inline_size,
+ None,
+ ));
+ }
+ let offsets = fragment.internal_soft_wrap_offsets.as_ref()?;
+ let glyphs = fragment.glyphs.as_ref()?;
+ let style = context.style(fragment.style_source);
+ let text_content = context.pass.text_content(fragment.layout_node);
+ offsets.iter().rev().find_map(|offset| {
+ if *offset <= fragment.start || *offset >= fragment.start + fragment.length_in_code_units {
+ return None;
+ }
+ let length = *offset - fragment.start;
+ let shape = libgfx_rust::text_layout::shape_text_shared(
+ &glyphs.font,
+ &fragment.text()[..length],
+ libgfx_rust::text_layout::TextType::try_from(glyphs.text_type)
+ .expect("invalid Gfx::GlyphRun::TextType"),
+ style.letter_spacing().to_double() as f32,
+ style.word_spacing().to_double() as f32,
+ text_chunker::joining_context(&text_content.text, fragment.start..*offset),
+ );
+ let inline_size = CssPixels::nearest_value_for_f32(shape.width());
+ let inline_offset = fragment.inline_offset + inline_size;
+ (inline_offset <= available_for_content).then(|| {
+ (
+ index + 1,
+ inline_offset,
+ length,
+ inline_size,
+ Some(line_box_fragment::GlyphData {
+ glyphs: shape.glyphs().clone(),
+ font: glyphs.font.clone(),
+ text_type: glyphs.text_type,
+ width: shape.width(),
+ is_upright: glyphs.is_upright,
+ derived_placements_end: None,
+ }),
+ )
+ })
+ })
+ })
+ };
+ let (first_displaced_fragment, retained_inline_size) = if content_fits {
(line.fragments.len(), line.inline_length)
- } else if let Some((fragment_count, inline_offset, length, inline_size)) = opportunity {
+ } else if let Some((fragment_count, inline_offset, length, inline_size, reshaped_glyphs)) = opportunity {
let last_retained_fragment = &mut line.fragments[fragment_count - 1];
if last_retained_fragment.length_in_code_units > length || last_retained_fragment.has_text_overflow_ellipsis {
let mut retained_code_units = 0usize;
- if let Some(glyphs) = &mut last_retained_fragment.glyphs {
+ if let Some(glyphs) = reshaped_glyphs {
+ last_retained_fragment.glyphs = Some(glyphs);
+ } else if let Some(glyphs) = &mut last_retained_fragment.glyphs {
let retained_glyph_count = glyphs
.glyphs
.iter()
@@ -1714,8 +1759,10 @@ impl<'context> InlineFormattingContext<'context> {
}
}
+ #[allow(clippy::too_many_arguments)]
fn text_item_wrap_opportunity(
&self,
+ prepared: &prepared_inline_content::PreparedInlineContent,
item: &inline_level_iterator::Item,
style: StyleValues<'_>,
is_whitespace: bool,
@@ -1737,10 +1784,11 @@ impl<'context> InlineFormattingContext<'context> {
TextItemWrapOpportunity::None
};
}
- return inline_level_iterator::whitespace_and_sequence_inline_size(self, item, remaining_items).map_or(
- TextItemWrapOpportunity::None,
- TextItemWrapOpportunity::BeforeWhitespaceSequence,
- );
+ return inline_level_iterator::whitespace_and_sequence_inline_size(self, prepared, item, remaining_items)
+ .map_or(
+ TextItemWrapOpportunity::None,
+ TextItemWrapOpportunity::BeforeWhitespaceSequence,
+ );
}
if item.can_break_before || line_ends_in_whitespace {
TextItemWrapOpportunity::BeforeText
@@ -1775,18 +1823,22 @@ impl<'context> InlineFormattingContext<'context> {
});
}
- fn break_overflowing_text_item<'builder>(
+ #[allow(clippy::too_many_arguments)]
+ fn break_soft_wrapped_text_item<'builder>(
&'builder self,
line_builder: &mut line_builder::LineBuilder<'builder, 'context>,
- prepared: &prepared_inline_content::PreparedInlineContent,
+ iterator: &inline_level_iterator::InlineLevelIterator,
item: &mut inline_level_iterator::Item,
item_index: usize,
+ can_break_before: bool,
mut line_limit: Option<&mut FragmentainerLineLimit>,
state_at_clamp_point: &mut Option<LineBuildingState<'builder, 'context>>,
) -> bool {
+ let prepared = iterator.prepared_content();
+ let following_inline_size = iterator.inline_size_following_text(self, item);
if line_builder
- .remaining_inline_size_for_overflow_break()
- .is_none_or(|remaining_inline_size| item.border_box_inline_size() <= remaining_inline_size)
+ .remaining_inline_size_for_soft_wrap()
+ .is_none_or(|remaining| inline_level_iterator::inline_extent([&*item]) + following_inline_size <= remaining)
{
return false;
}
@@ -1794,6 +1846,110 @@ impl<'context> InlineFormattingContext<'context> {
let text_content = self.pass.text_content(item.node);
let letter_spacing = style.letter_spacing().to_double() as f32;
let word_spacing = style.word_spacing().to_double() as f32;
+ let overflow_break_allowed = self.overflow_break_applies_to_style(style);
+ let end = item.offset_in_node + item.length_in_node;
+ let mut offset = item.offset_in_node;
+ loop {
+ if self.stops_at_line_clamp_point(line_builder, state_at_clamp_point) {
+ return false;
+ }
+ if line_limit.as_deref_mut().is_some_and(|limit| limit.is_reached(self)) {
+ return true;
+ }
+ let remaining = line_builder
+ .remaining_inline_size_for_soft_wrap()
+ .expect("splitting text requires a definite line width");
+ let line_is_empty = line_builder.current_line_is_empty();
+ self.set_current_line_start_offset(item_index, offset);
+ if line_is_empty && line_builder.current_line_has_no_space_left_by_floats() {
+ line_builder.break_line(line_builder::ForcedBreak::No, None, None);
+ continue;
+ }
+ // Keep the remainder as an offset into the item. Each line needs only its candidate prefixes shaped.
+ let mut prefix = item.fragment_at_soft_wrap(
+ prepared,
+ &text_content.text,
+ offset,
+ letter_spacing,
+ word_spacing,
+ remaining,
+ following_inline_size,
+ );
+ if inline_level_iterator::inline_extent([&prefix]) > remaining {
+ if overflow_break_allowed {
+ let physical_remaining = line_builder
+ .remaining_inline_size_for_overflow_break()
+ .expect("splitting text requires a definite line width");
+ if prefix.border_box_inline_size() > physical_remaining {
+ let split = self.pass.with_grapheme_segmenter(item.node, |segmenter| {
+ prefix.split_for_overflow_break(
+ prepared,
+ &text_content.text,
+ segmenter,
+ letter_spacing,
+ word_spacing,
+ physical_remaining,
+ line_is_empty,
+ )
+ });
+ if let Some(split) = split {
+ prefix = split;
+ } else if !line_is_empty {
+ line_builder.break_line(
+ line_builder::ForcedBreak::No,
+ None,
+ Some(prefix.border_box_inline_size()),
+ );
+ continue;
+ }
+ }
+ } else if !line_is_empty && can_break_before {
+ line_builder.break_line(
+ line_builder::ForcedBreak::No,
+ None,
+ Some(prefix.border_box_inline_size()),
+ );
+ continue;
+ }
+ }
+ offset = prefix.offset_in_node + prefix.length_in_node;
+ if offset == end {
+ *item = prefix;
+ return false;
+ }
+ line_builder.append_text_item(&mut prefix, prepared, style);
+ self.set_current_line_start_offset(item_index, offset);
+ line_builder.break_line(line_builder::ForcedBreak::No, None, None);
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn break_overflowing_text_item<'builder>(
+ &'builder self,
+ line_builder: &mut line_builder::LineBuilder<'builder, 'context>,
+ iterator: &inline_level_iterator::InlineLevelIterator,
+ item: &mut inline_level_iterator::Item,
+ item_index: usize,
+ can_break_before: bool,
+ mut line_limit: Option<&mut FragmentainerLineLimit>,
+ state_at_clamp_point: &mut Option<LineBuildingState<'builder, 'context>>,
+ ) -> bool {
+ let prepared = iterator.prepared_content();
+ if item.has_soft_wraps(prepared) {
+ return self.break_soft_wrapped_text_item(
+ line_builder,
+ iterator,
+ item,
+ item_index,
+ can_break_before,
+ line_limit,
+ state_at_clamp_point,
+ );
+ }
+ let style = self.style(self.parent_node(item.node));
+ let text_content = self.pass.text_content(item.node);
+ let letter_spacing = style.letter_spacing().to_double() as f32;
+ let word_spacing = style.word_spacing().to_double() as f32;
loop {
// NB: Splitting one text item can create several lines. Observe the clamp point before creating more,
// preserving the first clamped line while laying out legacy scrollable overflow.
@@ -1809,6 +1965,9 @@ impl<'context> InlineFormattingContext<'context> {
if item.border_box_inline_size() <= remaining_inline_size {
return false;
}
+ if !self.overflow_break_applies_to_style(style) {
+ return false;
+ }
let line_is_empty = self.line_data().line_boxes.last().is_some_and(|line| line.is_empty());
self.set_current_line_start_offset(item_index, item.offset_in_node);
if line_is_empty && line_builder.current_line_has_no_space_left_by_floats() {
@@ -2396,6 +2555,7 @@ impl<'context> InlineFormattingContext<'context> {
.last()
.is_some_and(|line| self.line_is_empty_or_ends_in_whitespace_that_wraps(line));
let opportunity = self.text_item_wrap_opportunity(
+ iterator.prepared_content(),
&item,
style,
is_whitespace,
@@ -2430,7 +2590,9 @@ impl<'context> InlineFormattingContext<'context> {
let measure_rest_of_run = !is_whitespace
&& !run_fits_after_previous_whitespace
&& line_builder.can_break_before_next_item();
- let unbreakable_run_inline_size = if measure_rest_of_run {
+ let unbreakable_run_inline_size = if measure_rest_of_run
+ || item.has_soft_wraps(iterator.prepared_content())
+ {
let stop_at_overflow_breakable_text = opportunity
== TextItemWrapOpportunity::AfterOverflowBreakableText
|| line_builder.current_line_is_empty();
@@ -2448,19 +2610,20 @@ impl<'context> InlineFormattingContext<'context> {
}
TextItemWrapOpportunity::None => {}
}
- if overflow_break_allowed {
+ if overflow_break_allowed || item.has_soft_wraps(iterator.prepared_content()) {
if self.break_overflowing_text_item(
line_builder,
- iterator.prepared_content(),
+ iterator,
&mut item,
item_index,
+ opportunity != TextItemWrapOpportunity::None,
line_limit.as_mut(),
&mut state_at_clamp_point,
) {
stopped_at_line_limit = true;
break;
}
- item_state.previous_text_item_allows_overflow_break_after = true;
+ item_state.previous_text_item_allows_overflow_break_after = overflow_break_allowed;
}
} else if item.can_break_before
|| can_break_after_previous_overflow_item
@@ -3743,6 +3906,7 @@ impl ContentSizingLines {
if self.lines.breaks_before_next_fragment()
&& matches!(
context.text_item_wrap_opportunity(
+ prepared,
item,
context.style(context.parent_node(item.node)),
true,
@@ -3832,6 +3996,7 @@ impl ContentSizingLines {
let can_break_after_previous_grapheme_broken_item =
previous_text_item_breaks_between_graphemes && !breaks_between_graphemes;
context.text_item_wrap_opportunity(
+ prepared,
item,
style,
is_whitespace,
@@ -3871,6 +4036,34 @@ impl ContentSizingLines {
if opportunity == TextItemWrapOpportunity::BeforeText {
self.lines.finish();
}
+ if self.measures_min_content() && item.has_soft_wraps(prepared) {
+ let text = context.pass.text_content(item.node);
+ let sizes = item.soft_wrap_segment_inline_sizes(
+ prepared,
+ &text.text,
+ style.letter_spacing().to_double() as f32,
+ style.word_spacing().to_double() as f32,
+ );
+ let last_index = sizes.len() - 1;
+ for (index, size) in sizes.into_iter().enumerate() {
+ let leading = if index == 0 {
+ margin_start + border_start + padding_start
+ } else {
+ CssPixels::default()
+ };
+ let trailing = if index == last_index {
+ item.padding_end + item.border_end + item.margin_end
+ } else {
+ CssPixels::default()
+ };
+ self.lines
+ .append(leading + size + trailing, false, CssPixels::default());
+ if index != last_index {
+ self.lines.finish();
+ }
+ }
+ return;
+ }
} else if self.lines.breaks_before_next_fragment()
&& (item.can_break_before || previous_text_item_breaks_between_graphemes)
{
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
index bc708e49c42..c5272bab835 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs
@@ -362,23 +362,172 @@ impl Item {
take_first_grapheme_when_none_fits: bool,
) -> Option<Item> {
assert_eq!(self.type_, ItemType::Text);
- self.split_at_shaped_glyph(
- prepared,
- segmenter,
- max_border_box_inline_size,
- take_first_grapheme_when_none_fits,
+ (!self.prepared_item(prepared).has(PreparedItem::SOFT_WRAPS))
+ .then(|| {
+ self.split_at_shaped_glyph(
+ prepared,
+ segmenter,
+ max_border_box_inline_size,
+ take_first_grapheme_when_none_fits,
+ )
+ })
+ .flatten()
+ .or_else(|| {
+ self.split_by_reshaping(
+ prepared,
+ text,
+ segmenter,
+ letter_spacing,
+ word_spacing,
+ max_border_box_inline_size,
+ take_first_grapheme_when_none_fits,
+ )
+ })
+ }
+
+ pub(crate) fn soft_wrap_offsets<'a>(
+ &self,
+ prepared: &'a PreparedInlineContent,
+ ) -> impl Iterator<Item = usize> + 'a {
+ self.soft_wrap_offsets_after(prepared, self.offset_in_node)
+ }
+
+ fn soft_wrap_offsets_after<'a>(
+ &self,
+ prepared: &'a PreparedInlineContent,
+ start: usize,
+ ) -> impl Iterator<Item = usize> + 'a {
+ let end = self.offset_in_node + self.length_in_node;
+ let item_index = self.prepared_item_index;
+ let wraps = if self.type_ == ItemType::Text && self.prepared_item(prepared).has(PreparedItem::SOFT_WRAPS) {
+ let first = prepared
+ .soft_wraps
+ .partition_point(|(index, offset)| (*index, *offset as usize) <= (item_index, start));
+ &prepared.soft_wraps[first..]
+ } else {
+ &[]
+ };
+ wraps
+ .iter()
+ .take_while(move |(index, _)| *index == item_index)
+ .map(|(_, offset)| *offset as usize)
+ .filter(move |offset| *offset > start && *offset < end)
+ }
+
+ pub(crate) fn has_soft_wraps(&self, prepared: &PreparedInlineContent) -> bool {
+ self.soft_wrap_offsets(prepared).next().is_some()
+ }
+
+ pub(crate) fn soft_wrap_segment_inline_sizes(
+ &self,
+ prepared: &PreparedInlineContent,
+ text: &[u16],
+ letter_spacing: f32,
+ word_spacing: f32,
+ ) -> Vec<CssPixels> {
+ let mut start = self.offset_in_node;
+ let item = self.prepared_item(prepared);
+ self.soft_wrap_offsets(prepared)
+ .chain(std::iter::once(start + self.length_in_node))
+ .map(|end| {
+ let width = libgfx_rust::text_layout::shaped_text_width(
+ prepared.font_of(item),
+ &text[start..end],
+ libgfx_rust::text_layout::TextType::try_from(item.text_type())
+ .expect("invalid Gfx::GlyphRun::TextType"),
+ letter_spacing,
+ word_spacing,
+ text_chunker::joining_context(text, start..end),
+ );
+ start = end;
+ CssPixels::nearest_value_for_f32(width)
+ })
+ .collect()
+ }
+
+ fn reshaped_range(
+ &self,
+ prepared: &PreparedInlineContent,
+ text: &[u16],
+ range: std::ops::Range<usize>,
+ letter_spacing: f32,
+ word_spacing: f32,
+ ) -> OwnedGlyphRun {
+ let item = self.prepared_item(prepared);
+ reshaped_glyph_run(
+ text,
+ range,
+ prepared.font_of(item),
+ item.text_type(),
+ letter_spacing,
+ word_spacing,
)
- .or_else(|| {
- self.split_by_reshaping(
- prepared,
- text,
- segmenter,
- letter_spacing,
- word_spacing,
- max_border_box_inline_size,
- take_first_grapheme_when_none_fits,
- )
- })
+ }
+
+ pub(crate) fn reshaped_fragment(
+ &self,
+ prepared: &PreparedInlineContent,
+ text: &[u16],
+ range: std::ops::Range<usize>,
+ letter_spacing: f32,
+ word_spacing: f32,
+ ) -> Item {
+ let end = self.offset_in_node + self.length_in_node;
+ if range == (self.offset_in_node..end) {
+ return self.clone();
+ }
+ let shape = self.reshaped_range(prepared, text, range.clone(), letter_spacing, word_spacing);
+ let mut fragment = self.clone();
+ fragment.offset_in_node = range.start;
+ fragment.length_in_node = range.len();
+ fragment.inline_size = CssPixels::nearest_value_for_f32(shape.width);
+ fragment.owned_glyph_run = Some(Box::new(shape));
+ if range.start != self.offset_in_node {
+ fragment.margin_start = CssPixels::default();
+ fragment.border_start = CssPixels::default();
+ fragment.padding_start = CssPixels::default();
+ fragment.entered_right_to_left_end_margin = CssPixels::default();
+ fragment.can_break_before = false;
+ }
+ if range.end != end {
+ fragment.margin_end = CssPixels::default();
+ fragment.border_end = CssPixels::default();
+ fragment.padding_end = CssPixels::default();
+ fragment.exited_right_to_left_end_margin = CssPixels::default();
+ fragment.trailing_whitespace = Default::default();
+ }
+ fragment
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn fragment_at_soft_wrap(
+ &self,
+ prepared: &PreparedInlineContent,
+ text: &[u16],
+ start: usize,
+ letter_spacing: f32,
+ word_spacing: f32,
+ available: CssPixels,
+ following_inline_size: CssPixels,
+ ) -> Item {
+ let end = self.offset_in_node + self.length_in_node;
+ let mut chosen = None;
+ for offset in self
+ .soft_wrap_offsets_after(prepared, start)
+ .chain(std::iter::once(end))
+ {
+ let fragment = self.reshaped_fragment(prepared, text, start..offset, letter_spacing, word_spacing);
+ let following = if offset == end {
+ following_inline_size
+ } else {
+ CssPixels::default()
+ };
+ if inline_extent([&fragment]) + following > available {
+ return chosen.unwrap_or(fragment);
+ }
+ chosen = Some(fragment);
+ }
+ chosen.expect("a text fragment ends at a soft wrap or the end of its item")
}
pub(crate) fn drop_prefix_before(
@@ -393,8 +542,9 @@ impl Item {
if split_offset_in_node <= self.offset_in_node || split_offset_in_node >= end || self.type_ != ItemType::Text {
return;
}
- let remainder_glyphs = self
- .shaped_glyphs_after(prepared, split_offset_in_node - self.offset_in_node)
+ let remainder_glyphs = (!self.prepared_item(prepared).has(PreparedItem::SOFT_WRAPS))
+ .then(|| self.shaped_glyphs_after(prepared, split_offset_in_node - self.offset_in_node))
+ .flatten()
.unwrap_or_else(|| {
let prepared_item = self.prepared_item(prepared);
reshaped_glyph_run(
@@ -687,6 +837,7 @@ struct TextNodeContext<'pass> {
chunks: std::sync::Arc<super::rendered_text::CachedTextChunks>,
text: &'pass [u16],
next_chunk_index: usize,
+ independent_chunks_until: usize,
style: StyleValues<'pass>,
letter_spacing: f32,
word_spacing: f32,
@@ -1032,6 +1183,7 @@ impl<'pass> InlineContentPreparer<'pass> {
chunks,
text: &self.pass.text_content(text_node).text,
next_chunk_index: 0,
+ independent_chunks_until: 0,
style,
letter_spacing: style.letter_spacing().to_double() as f32,
word_spacing: style.word_spacing().to_double() as f32,
@@ -1095,7 +1247,7 @@ impl<'pass> InlineContentPreparer<'pass> {
&& text_context.should_respect_linebreaks
&& chunks.last().is_some_and(|last| last.has_breaking_newline)
&& text_context.is_text_control_text;
- let (chunk, font) = if let Some(chunk) = chunk {
+ let (mut chunk, font) = if let Some(chunk) = chunk {
(*chunk, chunks.font_of(chunk))
} else if synthesize_zero_length_chunk || synthesize_chunk_after_trailing_newline {
text_context.next_chunk_index = chunks.len() + 1;
@@ -1136,6 +1288,52 @@ impl<'pass> InlineContentPreparer<'pass> {
return None;
};
+ // A possible line break doesn't end the shaping context. Keep compatible non-whitespace chunks together,
+ // and retain their break offsets so that line fitting can reshape the text at a break it actually takes.
+ let first_chunk = chunk;
+ let next_chunk_index = text_context.next_chunk_index;
+ let first_soft_wrap = self.buffers.soft_wraps.len();
+ let mut has_soft_wraps = false;
+ while next_chunk_index >= text_context.independent_chunks_until
+ && !chunk.is_all_whitespace
+ && !chunk.has_breaking_newline
+ && !chunk.has_breaking_tab
+ {
+ let Some(next) = chunks.get(text_context.next_chunk_index) else {
+ break;
+ };
+ if next.is_all_whitespace
+ || next.has_breaking_newline
+ || next.has_breaking_tab
+ || next.font_index != chunk.font_index
+ || next.text_type != chunk.text_type
+ || next.start != chunk.start + chunk.length
+ || text_is_set_upright(
+ text_context.writing_mode,
+ text_context.text_orientation,
+ text_chunker::code_point_at(text_context.text, chunk.start),
+ )
+ || text_is_set_upright(
+ text_context.writing_mode,
+ text_context.text_orientation,
+ text_chunker::code_point_at(text_context.text, next.start),
+ )
+ {
+ break;
+ }
+ if chunk.can_break_after {
+ self.buffers.soft_wraps.push((
+ u32::try_from(self.buffers.items.len()).expect("item indices fit in 32 bits"),
+ u32::try_from(next.start).expect("text offsets fit in 32 bits"),
+ ));
+ has_soft_wraps = true;
+ }
+ chunk.length += next.length;
+ chunk.can_break_after = next.can_break_after;
+ text_context.next_chunk_index += 1;
+ }
+ is_last_chunk = text_context.next_chunk_index >= chunks.len();
+
let mut text_type = chunk.text_type;
if matches!(
text_type,
@@ -1196,7 +1394,7 @@ impl<'pass> InlineContentPreparer<'pass> {
});
}
let shaped_range = shaped_start..shaped_start + shaped_length;
- let shaped_text = &full_text[shaped_range.clone()];
+ let mut shaped_text = &full_text[shaped_range.clone()];
let mut shape = libgfx_rust::text_layout::shape_text_shared(
font,
shaped_text,
@@ -1205,7 +1403,26 @@ impl<'pass> InlineContentPreparer<'pass> {
text_context.word_spacing,
text_chunker::joining_context(full_text, shaped_range),
);
- let mut flags = 0;
+ if has_soft_wraps && !shape.requires_context_for_breaks() {
+ // Independent glyphs can keep their small, separately measured chunks. Remember the end of this run so
+ // that preparing each following chunk doesn't shape the same suffix again.
+ text_context.independent_chunks_until = text_context.next_chunk_index;
+ text_context.next_chunk_index = next_chunk_index;
+ chunk = first_chunk;
+ is_last_chunk = next_chunk_index >= chunks.len();
+ self.buffers.soft_wraps.truncate(first_soft_wrap);
+ has_soft_wraps = false;
+ shaped_text = &full_text[chunk.start..chunk.start + chunk.length];
+ shape = libgfx_rust::text_layout::shape_text_shared(
+ font,
+ shaped_text,
+ libgfx_rust::text_layout::TextType::try_from(text_type).expect("invalid Gfx::GlyphRun::TextType"),
+ text_context.letter_spacing,
+ text_context.word_spacing,
+ text_chunker::joining_context(full_text, chunk.start..chunk.start + chunk.length),
+ );
+ }
+ let mut flags = if has_soft_wraps { PreparedItem::SOFT_WRAPS } else { 0 };
if !shaped_text.is_empty()
&& text_is_set_upright(
text_context.writing_mode,
@@ -2087,17 +2304,35 @@ impl InlineLevelIterator {
stop_at_overflow_breakable_text: bool,
) -> CssPixels {
let items = std::iter::once(item).chain(self.items());
- let (length, end) = sequence_length(context, items.clone(), stop_at_overflow_breakable_text);
- if end == SequenceEnd::OverflowBreakableText {
+ let (length, end) = sequence_length(
+ context,
+ &self.prepared,
+ items.clone(),
+ stop_at_overflow_breakable_text,
+ false,
+ );
+ if matches!(end, SequenceEnd::OverflowBreakableText | SequenceEnd::SoftWrapInText) {
let first_grapheme_cluster = items
.clone()
.nth(length)
- .map(|item| first_grapheme_cluster(context, &self.prepared, item));
+ .map(|item| first_breakable_segment(context, &self.prepared, item, end));
return sequence_inline_extent(context, items.take(length).chain(first_grapheme_cluster.as_ref()));
}
sequence_inline_extent(context, items.take(length.max(1)))
}
+ pub(crate) fn inline_size_following_text(
+ &self,
+ context: &inline_formatting_context::InlineFormattingContext<'_>,
+ item: &Item,
+ ) -> CssPixels {
+ let items = std::iter::once(item).chain(self.items());
+ let (length, end) = sequence_length(context, &self.prepared, items.clone(), false, true);
+ let prefix = (end == SequenceEnd::SoftWrapInText)
+ .then(|| first_breakable_segment(context, &self.prepared, self.items().get(length - 1).unwrap(), end));
+ sequence_inline_extent(context, items.take(length).chain(prefix.as_ref())) - inline_extent([item])
+ }
+
pub(crate) fn next_non_whitespace_text_allows_overflow_break(
&self,
context: &inline_formatting_context::InlineFormattingContext<'_>,
@@ -2122,14 +2357,22 @@ impl InlineLevelIterator {
pub(crate) fn whitespace_and_sequence_inline_size(
context: &inline_formatting_context::InlineFormattingContext<'_>,
+ prepared: &PreparedInlineContent,
whitespace: &Item,
items: &[Item],
) -> Option<CssPixels> {
- let (length, _) = sequence_length(context, items, false);
- if length == 0 {
+ let (length, end) = sequence_length(context, prepared, items, false, false);
+ let prefix =
+ (end == SequenceEnd::SoftWrapInText).then(|| first_breakable_segment(context, prepared, &items[length], end));
+ if length == 0 && prefix.is_none() {
return None;
}
- let size = sequence_inline_extent(context, std::iter::once(whitespace).chain(&items[..length]));
+ let size = sequence_inline_extent(
+ context,
+ std::iter::once(whitespace)
+ .chain(&items[..length])
+ .chain(prefix.as_ref()),
+ );
(size > inline_extent([whitespace])).then_some(size)
}
@@ -2139,9 +2382,9 @@ pub(crate) fn sequence_inline_size(
items: &[Item],
stop_at_overflow_breakable_text: bool,
) -> Option<CssPixels> {
- let (length, end) = sequence_length(context, items, stop_at_overflow_breakable_text);
- let first_grapheme_cluster =
- (end == SequenceEnd::OverflowBreakableText).then(|| first_grapheme_cluster(context, prepared, &items[length]));
+ let (length, end) = sequence_length(context, prepared, items, stop_at_overflow_breakable_text, false);
+ let first_grapheme_cluster = matches!(end, SequenceEnd::OverflowBreakableText | SequenceEnd::SoftWrapInText)
+ .then(|| first_breakable_segment(context, prepared, &items[length], end));
let size = sequence_inline_extent(context, items[..length].iter().chain(first_grapheme_cluster.as_ref()));
(end == SequenceEnd::ForcedBreak || size > CssPixels::default()).then_some(size)
}
@@ -2150,13 +2393,16 @@ pub(crate) fn sequence_inline_size(
enum SequenceEnd {
ForcedBreak,
OverflowBreakableText,
+ SoftWrapInText,
Other,
}
fn sequence_length<'item>(
context: &inline_formatting_context::InlineFormattingContext<'_>,
+ prepared: &PreparedInlineContent,
items: impl IntoIterator<Item = &'item Item>,
stop_at_overflow_breakable_text: bool,
+ include_first_whole_item: bool,
) -> (usize, SequenceEnd) {
let mut length = 0;
for item in items {
@@ -2181,18 +2427,35 @@ fn sequence_length<'item>(
return (length, SequenceEnd::OverflowBreakableText);
}
}
+ if item.has_soft_wraps(prepared) && !(length == 0 && include_first_whole_item) {
+ return (length, SequenceEnd::SoftWrapInText);
+ }
length += 1;
}
(length, SequenceEnd::Other)
}
-fn first_grapheme_cluster(
+fn first_breakable_segment(
context: &inline_formatting_context::InlineFormattingContext<'_>,
prepared: &PreparedInlineContent,
item: &Item,
+ end: SequenceEnd,
) -> Item {
let style = context.style(context.style_source(item.node));
let text_content = context.pass.text_content(item.node);
+ if end == SequenceEnd::SoftWrapInText {
+ let end = item
+ .soft_wrap_offsets(prepared)
+ .next()
+ .expect("a soft wrap ends the measured segment");
+ return item.reshaped_fragment(
+ prepared,
+ &text_content.text,
+ item.offset_in_node..end,
+ style.letter_spacing().to_double() as f32,
+ style.word_spacing().to_double() as f32,
+ );
+ }
let first_grapheme_cluster_inline_size = context.pass.with_grapheme_segmenter(item.node, |segmenter| {
item.first_grapheme_cluster_inline_size(
prepared,
diff --git a/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs b/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs
index cb2a0a243b9..8d033df8464 100644
--- a/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs
+++ b/Libraries/LibWeb/Rust/src/layout/line_box_fragment.rs
@@ -76,6 +76,9 @@ pub(crate) struct LineBoxFragmentData {
pub(crate) current_insert_direction: u8,
pub(crate) has_text_overflow_ellipsis: bool,
pub(crate) has_soft_wrap_opportunity_after: bool,
+ /// Internal soft wraps for standard block ellipses, as UTF-16 offsets in the text node.
+ #[allow(clippy::box_collection, reason = "store optional wrap offsets in one word")]
+ pub(crate) internal_soft_wrap_offsets: Option<Box<Vec<usize>>>,
pub(crate) is_fully_truncated: bool,
pub(crate) trailing_whitespace: TrailingWhitespace,
pub(crate) text_utf16: *const u16,
@@ -162,6 +165,7 @@ impl LineBoxFragmentData {
current_insert_direction: direction::LTR,
has_text_overflow_ellipsis: false,
has_soft_wrap_opportunity_after: false,
+ internal_soft_wrap_offsets: None,
is_fully_truncated: false,
trailing_whitespace: TrailingWhitespace::default(),
text_utf16: std::ptr::null(),
diff --git a/Libraries/LibWeb/Rust/src/layout/line_builder.rs b/Libraries/LibWeb/Rust/src/layout/line_builder.rs
index de42b741c0e..07d82ec14b4 100644
--- a/Libraries/LibWeb/Rust/src/layout/line_builder.rs
+++ b/Libraries/LibWeb/Rust/src/layout/line_builder.rs
@@ -414,6 +414,10 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
Some(available - self.line(line_index).physical_horizontal_extent())
}
+ pub(crate) fn remaining_inline_size_for_soft_wrap(&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 inline size the
/// line breaks at instead.
pub(crate) fn remaining_inline_size_for_overflow_break(&mut self) -> Option<CssPixels> {
@@ -647,6 +651,21 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {
glyphs,
item.trailing_whitespace,
);
+ // https://drafts.csswg.org/css-overflow-4/#block-ellipsis
+ // AD-HOC: Block ellipses displace content at soft wraps. Legacy clamping preserves glyph-based truncation
+ // inside shaped runs, so only standard clamping keeps these internal opportunities.
+ if self.context().parent.has_line_clamp()
+ && !self.context().parent.clamped_content_is_scrollable_overflow()
+ && item.has_soft_wraps(prepared)
+ {
+ let line_index = self.line_count() - 1;
+ let mut line = self.line_mut(line_index);
+ let fragment = line.fragments.last_mut().unwrap();
+ fragment
+ .internal_soft_wrap_offsets
+ .get_or_insert_default()
+ .extend(item.soft_wrap_offsets(prepared));
+ }
}
#[allow(clippy::too_many_arguments)]
diff --git a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs
index 9d24738c05d..151c953bc9d 100644
--- a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs
+++ b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs
@@ -17,6 +17,8 @@ pub(crate) struct PreparedInlineContent {
pub(super) box_events: Box<[InlineBoxEvent]>,
pub(super) fonts: Box<[FontHandle]>,
pub(super) tab_stops: Box<[PreparedTabStop]>,
+ /// Prepared item indices paired with UTF-16 offsets in their text nodes, ordered by item and then offset.
+ pub(super) soft_wraps: Box<[(u32, u32)]>,
}
const _: () = {
@@ -65,6 +67,7 @@ impl PreparedItem {
pub(super) const TAKES_TRAILING_EDGES: u16 = 1 << 10;
pub(super) const UPRIGHT: u16 = 1 << 11;
pub(super) const TAB_STOP: u16 = 1 << 12;
+ pub(super) const SOFT_WRAPS: u16 = 1 << 13;
pub(super) fn new(type_: ItemType, node: Node, flags: u16) -> Self {
Self {
@@ -195,6 +198,7 @@ pub(crate) struct InlineContentPreparationBuffers {
pub(super) box_events: Vec<InlineBoxEvent>,
pub(super) fonts: Vec<FontHandle>,
pub(super) tab_stops: Vec<PreparedTabStop>,
+ pub(super) soft_wraps: Vec<(u32, u32)>,
pub(super) box_stack: Vec<Node>,
}
@@ -219,6 +223,7 @@ impl InlineContentPreparationBuffers {
box_events: self.box_events.drain(..).collect(),
fonts: self.fonts.drain(..).collect(),
tab_stops: self.tab_stops.drain(..).collect(),
+ soft_wraps: self.soft_wraps.drain(..).collect(),
}
}
}
@@ -275,6 +280,7 @@ impl PreparedInlineContent {
.or_else(|| first_difference("inline box event", &self.box_events, &fresh.box_events))
.or_else(|| first_difference("font", &self.fonts, &fresh.fonts))
.or_else(|| first_difference("tab stop", &self.tab_stops, &fresh.tab_stops))
+ .or_else(|| first_difference("soft wrap", &self.soft_wraps, &fresh.soft_wraps))
}
}
diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
index 677abf304ac..7bc8a41c3be 100644
--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
@@ -754,6 +754,7 @@ mod tests {
box_events: Box::default(),
fonts: Box::default(),
tab_stops: Box::default(),
+ soft_wraps: Box::default(),
});
scratch.prepared_inline_content_memos().keep(block, prepared.clone());
(validity, Arc::downgrade(&prepared))
diff --git a/Tests/LibWeb/Assets/FiraCode-LICENSE.txt b/Tests/LibWeb/Assets/FiraCode-LICENSE.txt
new file mode 100644
index 00000000000..8190d0c2ab7
--- /dev/null
+++ b/Tests/LibWeb/Assets/FiraCode-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2014-2020 The Fira Code Project Authors (https://github.com/tonsky/FiraCode)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/Tests/LibWeb/Assets/FiraCode-Latin.woff2 b/Tests/LibWeb/Assets/FiraCode-Latin.woff2
new file mode 100644
index 00000000000..9589c8a91ce
Binary files /dev/null and b/Tests/LibWeb/Assets/FiraCode-Latin.woff2 differ
diff --git a/Tests/LibWeb/Ref/expected/line-clamp-internal-soft-wraps-ref.html b/Tests/LibWeb/Ref/expected/line-clamp-internal-soft-wraps-ref.html
new file mode 100644
index 00000000000..16bbc1fdf8b
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/line-clamp-internal-soft-wraps-ref.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<html class="reftest-wait">
+<style>
+ @font-face { font-family: Programming; src: url("../../Assets/FiraCode-Latin.woff2"); }
+ body { margin: 0; font: 20px/30px Programming; }
+ .case { overflow: hidden; margin-bottom: 10px; }
+ .standard { line-clamp: 1; }
+ .legacy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 1; }
+</style>
+<div class="case standard" style="width: 4ch">a&#x301;-&#x2026;</div>
+<div class="case standard" style="width: 5ch">a&#x301;-a&#x301;-&#x2026;</div>
+<div class="case standard" style="width: 6ch">a&#x301;-a&#x301;-&#x2026;</div>
+<div class="case standard" style="width: 7ch">a&#x301;-a&#x301;-a&#x301;-&#x2026;</div>
+<div class="case standard" style="width: 8ch">a&#x301;-a&#x301;-a&#x301;-&#x2026;</div>
+<div class="case legacy" style="width: 4ch">a&#x301;-a&#x301;&#x2026;</div>
+<div class="case legacy" style="width: 5ch">a&#x301;-a&#x301;-&#x2026;</div>
+<div class="case legacy" style="width: 6ch">a&#x301;-a&#x301;-a&#x301;&#x2026;</div>
+<div class="case legacy" style="width: 7ch">a&#x301;-a&#x301;-a&#x301;-&#x2026;</div>
+<div class="case legacy" style="width: 8ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;&#x2026;</div>
+<script>
+ document.fonts.ready.then(() => document.documentElement.classList.remove("reftest-wait"));
+</script>
diff --git a/Tests/LibWeb/Ref/expected/programming-ligatures-across-soft-breaks-ref.html b/Tests/LibWeb/Ref/expected/programming-ligatures-across-soft-breaks-ref.html
new file mode 100644
index 00000000000..26a0955d41b
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/programming-ligatures-across-soft-breaks-ref.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<style>
+ @font-face {
+ font-family: "Programming";
+ src: url("../../Assets/FiraCode-Latin.woff2");
+ }
+ p { white-space: nowrap; font: 16px "Programming"; }
+ .break-all { word-break: break-all; }
+ .no-context { font-feature-settings: "calt" 0; }
+ .narrow { display: inline-block; vertical-align: top; font-size: 32px; line-height: 40px;
+ width: 2.5ch; border: 1px solid; margin: 4px; }
+</style>
+<p>LYoWAT - ff fi fl ffl -&gt; --&gt; ---&gt; &lt;- &lt;-&gt; &lt;=&gt; =&gt; ==&gt; &lt;==</p>
+<p class="break-all">LYoWAT - ff fi fl ffl -&gt; --&gt; ---&gt; &lt;- &lt;-&gt; &lt;=&gt; =&gt; ==&gt; &lt;==</p>
+<p class="no-context">LYoWAT - ff fi fl ffl -&gt; --&gt; ---&gt; &lt;- &lt;-&gt; &lt;=&gt; =&gt; ==&gt; &lt;==</p>
+<div><p class="narrow">-&gt;</p><p class="narrow">--<br>&gt;</p><p class="narrow">--<br>-&gt;</p><p class="narrow">&lt;-<br>&gt;</p></div>
+<script>
+ document.fonts.ready.then(() => document.documentElement.classList.remove("reftest-wait"));
+</script>
diff --git a/Tests/LibWeb/Ref/expected/wpt-import/css/css-fonts/font-variant-ligatures-09-ref.html b/Tests/LibWeb/Ref/expected/wpt-import/css/css-fonts/font-variant-ligatures-09-ref.html
new file mode 100644
index 00000000000..d4293bdfd6c
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/wpt-import/css/css-fonts/font-variant-ligatures-09-ref.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<html lang="en">
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+<title>CSS Test: font-variant-ligatures: contextual; low level equivalence</title>
+<link rel="author" title="Chris Lilley" href="[email protected]">
+<style>
+ @font-face {
+ font-family: fwf;
+ src: url(support/fonts/FontWithFancyFeatures.otf);
+ }
+ .test {
+ font-family: fwf;
+ font-size: 3em;
+ line-height: 1.1;
+ }
+</style>
+<body>
+<p>Test passes if the three lines below are identical, with one check mark (✓).</p>
+<section class="test">
+ <p class="ref">A</p>
+ <p class="ref">A</p>
+ <p class="ref">A</p>
+</section>
\ No newline at end of file
diff --git a/Tests/LibWeb/Ref/input/line-clamp-internal-soft-wraps.html b/Tests/LibWeb/Ref/input/line-clamp-internal-soft-wraps.html
new file mode 100644
index 00000000000..edc6c89b19e
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/line-clamp-internal-soft-wraps.html
@@ -0,0 +1,23 @@
+<!doctype html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/line-clamp-internal-soft-wraps-ref.html">
+<style>
+ @font-face { font-family: Programming; src: url("../../Assets/FiraCode-Latin.woff2"); }
+ body { margin: 0; font: 20px/30px Programming; }
+ .case { overflow: hidden; margin-bottom: 10px; }
+ .standard { line-clamp: 1; }
+ .legacy { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 1; }
+</style>
+<div class="case standard" style="width: 4ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case standard" style="width: 5ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case standard" style="width: 6ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case standard" style="width: 7ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case standard" style="width: 8ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case legacy" style="width: 4ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case legacy" style="width: 5ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case legacy" style="width: 6ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case legacy" style="width: 7ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<div class="case legacy" style="width: 8ch">a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-a&#x301;-</div>
+<script>
+ document.fonts.ready.then(() => document.documentElement.classList.remove("reftest-wait"));
+</script>
diff --git a/Tests/LibWeb/Ref/input/programming-ligatures-across-soft-breaks.html b/Tests/LibWeb/Ref/input/programming-ligatures-across-soft-breaks.html
new file mode 100644
index 00000000000..2fa26493402
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/programming-ligatures-across-soft-breaks.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/programming-ligatures-across-soft-breaks-ref.html">
+<style>
+ @font-face {
+ font-family: "Programming";
+ src: url("../../Assets/FiraCode-Latin.woff2");
+ }
+ p { font: 16px "Programming"; }
+ .break-all { word-break: break-all; }
+ .no-context { font-feature-settings: "calt" 0; }
+ .narrow { display: inline-block; vertical-align: top; font-size: 32px; line-height: 40px;
+ width: 2.5ch; border: 1px solid; margin: 4px; }
+</style>
+<p>LYoWAT - ff fi fl ffl -&gt; --&gt; ---&gt; &lt;- &lt;-&gt; &lt;=&gt; =&gt; ==&gt; &lt;==</p>
+<p class="break-all">LYoWAT - ff fi fl ffl -&gt; --&gt; ---&gt; &lt;- &lt;-&gt; &lt;=&gt; =&gt; ==&gt; &lt;==</p>
+<p class="no-context">LYoWAT - ff fi fl ffl -&gt; --&gt; ---&gt; &lt;- &lt;-&gt; &lt;=&gt; =&gt; ==&gt; &lt;==</p>
+<div><p class="narrow">-&gt;</p><p class="narrow">--&gt;</p><p class="narrow">---&gt;</p><p class="narrow">&lt;-&gt;</p></div>
+<script>
+ document.fonts.ready.then(() => document.documentElement.classList.remove("reftest-wait"));
+</script>
diff --git a/Tests/LibWeb/Ref/input/wpt-import/css/css-fonts/font-variant-ligatures-09.html b/Tests/LibWeb/Ref/input/wpt-import/css/css-fonts/font-variant-ligatures-09.html
new file mode 100644
index 00000000000..bcd0c797eeb
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/wpt-import/css/css-fonts/font-variant-ligatures-09.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html lang="en">
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+<title>CSS Test: font-variant-ligatures: contextual; low level equivalence</title>
+<link rel="author" title="Chris Lilley" href="[email protected]">
+<link rel="help" href="https://www.w3.org/TR/css-fonts-3/#font-variant-ligatures-prop">
+<link rel="help" href="https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop">
+<link rel="match" href="../../../../expected/wpt-import/css/css-fonts/font-variant-ligatures-09-ref.html">
+<meta name="assert" content="Enables display of contextual alternates (OpenType feature: calt)">
+<style>
+ @font-face {
+ font-family: fwf;
+ src: url(support/fonts/FontWithFancyFeatures.otf);
+ }
+ .test {
+ font-family: fwf;
+ font-size: 3em;
+ line-height: 1.1;
+ }
+ .high {
+ font-variant-ligatures: contextual;
+ }
+ .low {
+ font-feature-settings: "calt" on;
+ }
+</style>
+<body>
+<p>Test passes if the three lines below are identical, with one check mark (✓).</p>
+<section class="test">
+ <p class="high">G</p>
+ <p class="low">G</p>
+ <p class="ref">A</p>
+</section>
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/css/programming-ligature-wrapping.txt b/Tests/LibWeb/Text/expected/css/programming-ligature-wrapping.txt
new file mode 100644
index 00000000000..5345859f021
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/programming-ligature-wrapping.txt
@@ -0,0 +1,8 @@
+normal wraps: true
+break-all wraps: true
+min-content uses soft breaks: true
+max-content preserves the full run: true
+following text stays with the unbreakable suffix: true
+preceding text uses separate lines: true
+widening removes the wrap: true
+narrowing restores the wrap: true
diff --git a/Tests/LibWeb/Text/expected/css/soft-wrap-inline-margins.txt b/Tests/LibWeb/Text/expected/css/soft-wrap-inline-margins.txt
new file mode 100644
index 00000000000..ea743028255
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/soft-wrap-inline-margins.txt
@@ -0,0 +1,8 @@
+start: 2,1
+end: 2,1
+both: 2,1
+exact-fit: 3
+rtl-start: 2,1
+rtl-end: 2,1
+rtl-both: 2,1
+no-margin: 3
diff --git a/Tests/LibWeb/Text/expected/css/soft-wrap-long-shaped-run.txt b/Tests/LibWeb/Text/expected/css/soft-wrap-long-shaped-run.txt
new file mode 100644
index 00000000000..1c6361de68f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/soft-wrap-long-shaped-run.txt
@@ -0,0 +1,4 @@
+10 segments per line: true
+last segment reaches the final line: true
+20 segments per line: true
+last segment reaches the final line: true
diff --git a/Tests/LibWeb/Text/expected/css/soft-wrap-shaping-boundaries.txt b/Tests/LibWeb/Text/expected/css/soft-wrap-shaping-boundaries.txt
new file mode 100644
index 00000000000..31a8b19205f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/soft-wrap-shaping-boundaries.txt
@@ -0,0 +1,7 @@
+balanced-ascii: 8,7
+balanced-clusters: 8,6
+balanced-ligatures: 8,7
+balanced-arrows: 8,7
+no-break-before: ["Abc-","->"]
+break-before: ["A","bc-","->"]
+nested-boundary: ["Abc-","->"]
diff --git a/Tests/LibWeb/Text/input/css/programming-ligature-wrapping.html b/Tests/LibWeb/Text/input/css/programming-ligature-wrapping.html
new file mode 100644
index 00000000000..5ab1b5f794d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/programming-ligature-wrapping.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<style>
+ @font-face { font-family: "Programming"; src: url("../../../Assets/FiraCode-Latin.woff2"); }
+ .measure { font: 32px/40px "Programming"; width: 2.5ch; }
+ .min { width: min-content; }
+ .max { width: max-content; }
+ .break-all { word-break: break-all; }
+ .control { position: absolute; width: auto; white-space: nowrap; }
+</style>
+<div class="measure" id="normal">---&gt;</div>
+<div class="measure break-all" id="break-all">---&gt;</div>
+<div class="measure min" id="min">---&gt;</div>
+<div class="measure max" id="max">---&gt;</div>
+<div class="measure" id="following"><span>--&gt;</span>x</div>
+<div class="measure" id="preceding">x --&gt;</div>
+<span class="measure control" id="one">-</span>
+<span class="measure control" id="four">---&gt;</span>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ await document.fonts.ready;
+ const box = id => document.getElementById(id).getBoundingClientRect();
+ const same = (a, b) => Math.abs(a - b) < 0.05;
+ println(`normal wraps: ${same(box("normal").height, 80)}`);
+ println(`break-all wraps: ${same(box("break-all").height, 80)}`);
+ println(`min-content uses soft breaks: ${same(box("min").width, box("one").width)}`);
+ println(`max-content preserves the full run: ${same(box("max").width, box("four").width)}`);
+ println(`following text stays with the unbreakable suffix: ${same(box("following").height, 80)}`);
+ println(`preceding text uses separate lines: ${same(box("preceding").height, 120)}`);
+ document.getElementById("normal").style.width = "8ch";
+ println(`widening removes the wrap: ${same(box("normal").height, 40)}`);
+ document.getElementById("normal").style.width = "2.5ch";
+ println(`narrowing restores the wrap: ${same(box("normal").height, 80)}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/soft-wrap-inline-margins.html b/Tests/LibWeb/Text/input/css/soft-wrap-inline-margins.html
new file mode 100644
index 00000000000..0dec3f52f9a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/soft-wrap-inline-margins.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @font-face { font-family: Programming; src: url("../../../Assets/FiraCode-Latin.woff2"); }
+ .case { font: 20px/30px Programming; width: 4ch; }
+ .start > span { margin-left: 2ch; }
+ .end > span { margin-right: 2ch; }
+ .both > span { margin-left: 1ch; margin-right: 1ch; }
+ .exact { width: 5ch; }
+ .rtl { direction: rtl; }
+</style>
+<div class="case start" id="start"><span></span></div>
+<div class="case end" id="end"><span></span></div>
+<div class="case both" id="both"><span></span></div>
+<div class="case start exact" id="exact-fit"><span></span></div>
+<div class="case start rtl" id="rtl-start"><span></span></div>
+<div class="case end rtl" id="rtl-end"><span></span></div>
+<div class="case both rtl" id="rtl-both"><span></span></div>
+<div class="case" id="no-margin"><span></span></div>
+<script>
+ const text = "a" + String.fromCharCode(0x301) + "-a" + String.fromCharCode(0x301);
+ for (const span of document.querySelectorAll(".case > span")) span.textContent = text;
+ promiseTest(async () => {
+ await document.fonts.load("20px Programming", text);
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
+ for (const element of document.querySelectorAll(".case")) {
+ const node = element.firstChild.firstChild;
+ const lines = new Map();
+ for (const { index, segment } of segmenter.segment(node.data)) {
+ const range = document.createRange();
+ range.setStart(node, index);
+ range.setEnd(node, index + segment.length);
+ const line = Math.round((range.getBoundingClientRect().top - element.getBoundingClientRect().top) / 30);
+ lines.set(line, (lines.get(line) ?? 0) + 1);
+ }
+ println(`${element.id}: ${[...lines.values()].join(",")}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/soft-wrap-long-shaped-run.html b/Tests/LibWeb/Text/input/css/soft-wrap-long-shaped-run.html
new file mode 100644
index 00000000000..967bab846dd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/soft-wrap-long-shaped-run.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @font-face { font-family: Programming; src: url("../../../Assets/FiraCode-Latin.woff2"); }
+ #run, #segment { font: 20px/30px Programming; }
+ #segment { position: absolute; white-space: nowrap; }
+</style>
+<span id="segment">a&#x301;-</span>
+<div id="run"></div>
+<script>
+ promiseTest(async () => {
+ await document.fonts.load("20px Programming", "a\u0301-");
+ const segment = document.getElementById("segment");
+ const run = document.getElementById("run");
+ const width = segment.getBoundingClientRect().width;
+ run.textContent = "a\u0301-".repeat(80000);
+ for (const perLine of [10, 20]) {
+ run.style.width = `${width * (perLine + 0.5)}px`;
+ const lineCount = 80000 / perLine;
+ println(`${perLine} segments per line: ${run.getBoundingClientRect().height === lineCount * 30}`);
+ const first = document.createRange();
+ first.setStart(run.firstChild, 0);
+ first.setEnd(run.firstChild, 3);
+ const last = document.createRange();
+ last.setStart(run.firstChild, run.firstChild.length - 3);
+ last.setEnd(run.firstChild, run.firstChild.length);
+ const distance = last.getBoundingClientRect().top - first.getBoundingClientRect().top;
+ println(`last segment reaches the final line: ${distance === (lineCount - 1) * 30}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/soft-wrap-shaping-boundaries.html b/Tests/LibWeb/Text/input/css/soft-wrap-shaping-boundaries.html
new file mode 100644
index 00000000000..5ca414aa4c3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/soft-wrap-shaping-boundaries.html
@@ -0,0 +1,48 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @font-face { font-family: Programming; src: url("../../../Assets/FiraCode-Latin.woff2"); }
+ @font-face { font-family: PlusLigatures; src: url("../../../Assets/PlusLigatures.ttf"); }
+ #balanced-clusters { word-break: normal; }
+ #balanced-ligatures { font-family: PlusLigatures; }
+ .case { font: 20px/30px Programming; width: 3.5ch; }
+ .balance { width: 10ch; word-break: break-all; text-wrap: balance; }
+</style>
+<div class="case balance" id="balanced-ascii">aaaaaaaaaaaaaaa</div>
+<div class="case balance" id="balanced-clusters"></div>
+<div class="case balance" id="balanced-ligatures">+++++++++++++++</div>
+<div class="case balance" id="balanced-arrows">--&gt;--&gt;--&gt;--&gt;--&gt;</div>
+<div class="case" id="no-break-before">A<span>bc--&gt;</span></div>
+<div class="case" id="break-before">A <span>bc--&gt;</span></div>
+<div class="case" id="nested-boundary"><span>A</span><span>bc--&gt;</span></div>
+<script>
+ document.getElementById("balanced-clusters").textContent = "a\u0301-".repeat(7);
+ promiseTest(async () => {
+ await document.fonts.load("20px Programming", "a\u0301-->");
+ await document.fonts.load("20px PlusLigatures", "+");
+ await document.fonts.ready;
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
+ for (const element of document.querySelectorAll(".case")) {
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
+ const lines = new Map();
+ while (walker.nextNode()) {
+ const node = walker.currentNode;
+ for (const { index, segment } of segmenter.segment(node.data)) {
+ const range = document.createRange();
+ range.setStart(node, index);
+ range.setEnd(node, index + segment.length);
+ const rect = range.getBoundingClientRect();
+ if (!segment.trim() && !rect.width) continue;
+ const line = Math.round((rect.top - element.getBoundingClientRect().top) / 30);
+ lines.set(line, (lines.get(line) ?? "") + segment);
+ }
+ }
+ const result = [...lines.values()];
+ if (element.classList.contains("balance")) {
+ println(`${element.id}: ${result.map(line => [...segmenter.segment(line)].length).join(",")}`);
+ } else {
+ println(`${element.id}: ${JSON.stringify(result.map(line => line.trimEnd()))}`);
+ }
+ }
+ });
+</script>