Truly independent web browser
LibWeb: Keep prepared inline content across layout passes
Aliaksandr Kalenika67882c23ab2
diff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex 46c9989dae8..d0db1470076 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -1278,11 +1278,18 @@ mod tests {let store = FcRunCacheStore::default();let in_flow_block_cache = InFlowBlockCacheStore::default();let text_memos = crate::layout::rendered_text::TextMemos::default();+ let prepared_inline_content = crate::layout::prepared_inline_content::PreparedInlineContentMemos::default();let intrinsic_size_caches = crate::layout::layout_node_arena::IntrinsicSizeCaches::default();let node = Node::new(0, 1);let mut notes = MemoInvalidations::default();notes.note_structural_inline_change(node);- notes.apply_to(&store, &in_flow_block_cache, &text_memos, &intrinsic_size_caches);+ notes.apply_to(+ &store,+ &in_flow_block_cache,+ &text_memos,+ &prepared_inline_content,+ &intrinsic_size_caches,+ );assert_eq!(store.structural_epoch_bumps_of(node), 0);store.store(node, entry(at(100), 1, Some(root_with_a_descendant()), 0));@@ -1290,7 +1297,13 @@ mod tests {notes.note_structural_inline_change(node);notes.note_fragment_cache_epoch_bumped(node);notes.note_structural_inline_change(node);- notes.apply_to(&store, &in_flow_block_cache, &text_memos, &intrinsic_size_caches);+ notes.apply_to(+ &store,+ &in_flow_block_cache,+ &text_memos,+ &prepared_inline_content,+ &intrinsic_size_caches,+ );assert_eq!(store.structural_epoch_bumps_of(node), 2);let reused = Node::new(0, 2);@@ -1298,7 +1311,13 @@ mod tests {notes.note_structural_inline_change(node);notes.note_slot_freed(node.slot_index());notes.note_structural_inline_change(reused);- notes.apply_to(&store, &in_flow_block_cache, &text_memos, &intrinsic_size_caches);+ notes.apply_to(+ &store,+ &in_flow_block_cache,+ &text_memos,+ &prepared_inline_content,+ &intrinsic_size_caches,+ );assert!(!store.slot_holds_entries(0));assert_eq!(store.structural_epoch_bumps_of(reused), 0);}diff --git a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rsindex 7ed794565ab..40a6a4e5f2c 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs@@ -541,7 +541,7 @@ struct InlineContentPreparer<'pass> {}impl PreparedInlineContent {- pub(crate) fn prepare(pass: LayoutPass<'_>, block_container: Node) -> Self {+ pub(super) fn prepare(pass: LayoutPass<'_>, block_container: Node) -> Self {InlineContentPreparer::prepare(pass, block_container)}@@ -590,7 +590,9 @@ impl<'pass> InlineContentPreparer<'pass> {while let Some(item) = preparer.prepare_next_item() {preparer.buffers.items.push(item);}- let prepared = preparer.buffers.take_prepared_inline_content();+ let prepared = preparer+ .buffers+ .take_prepared_inline_content(super::fc_run_cache::run_root_validity(&pass, block_container));pass.return_inline_content_preparation_buffers(preparer.buffers);prepared}@@ -1486,7 +1488,7 @@ impl InlineLevelIterator {let callbacks = context.callbacks;match callbacks.inline_item_stash(context.containing_block) {Some(stash) => Self::from_stash(context, stash),- None => PreparedInlineContent::prepare(callbacks, context.containing_block)+ None => PreparedInlineContent::for_block_container(callbacks, context.containing_block).resolve_items_for_run(context, atomic_sizing),}}diff --git a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs b/Libraries/LibWeb/Rust/src/layout/layout_pass.rsindex 4723aab82e8..5e7dd074de5 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs@@ -38,7 +38,8 @@ pub(crate) struct LayoutPass<'arena> {/// passes after them, or inside a run whose result is discarded, that run's own.intrinsic_size_caches: &'arena super::layout_node_arena::IntrinsicSizeCaches,/// Whether this pass view is inside a run whose result is discarded, which reads no memoized layout from before it- /// and keeps none: the run cache, the in-flow block cache, inline item stashes and intrinsic sizes.+ /// and keeps none: the run cache, the in-flow block cache, inline item stashes, prepared inline content and+ /// intrinsic sizes.reads_no_memoized_layout: bool,/// The innermost of the position options the boxes this pass view lays out are laid out with.position_option_styles: Option<&'arena PositionOptionStyle<'arena>>,@@ -132,6 +133,10 @@ impl<'arena> LayoutPass<'arena> {})}+ pub(crate) fn lays_out_with_position_option(&self) -> bool {+ self.position_option_styles.is_some()+ }+/// Runs `run` with this pass as it lays out `node` with `style`, the style of one of its position options, which/// the style reads of `node` see in place of the style of its row. The payloads `style` names must stay alive/// until `run` returns.@@ -254,6 +259,12 @@ impl<'arena> LayoutPass<'arena> {.text_chunks(node, self.text_content(node).rendered(), key, compute)}+ pub(crate) fn prepared_inline_content_memos(+ &self,+ ) -> &'arena super::prepared_inline_content::PreparedInlineContentMemos {+ self.scratch.prepared_inline_content_memos()+ }+pub(crate) fn take_inline_content_preparation_buffers(&self,) -> super::prepared_inline_content::InlineContentPreparationBuffers {diff --git a/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs b/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rsindex dd5dabaa2b8..9ae3de011cd 100644--- a/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs+++ b/Libraries/LibWeb/Rust/src/layout/memo_invalidations.rs@@ -16,12 +16,14 @@ use super::fc_run_cache::FcRunCacheStore;use super::in_flow_block_cache::InFlowBlockCacheStore;use super::layout_node_arena::IntrinsicSizeCaches;use super::node_data::NodeSlotId;+use super::prepared_inline_content::PreparedInlineContentMemos;use super::rendered_text::TextMemos;#[derive(Clone, Copy, Default)]struct SlotNotes {noted: bool,text_memos_dropped: bool,+ prepared_inline_content_dropped: bool,run_cache_entries_dropped: bool,in_flow_block_entries_dropped: bool,intrinsic_sizes_dropped: bool,@@ -64,6 +66,7 @@ impl MemoInvalidations {self.note_run_cache_entries_dropped(slot);let notes = self.notes_of(slot);notes.text_memos_dropped = true;+ notes.prepared_inline_content_dropped = true;notes.in_flow_block_entries_dropped = true;notes.intrinsic_sizes_dropped = true;}@@ -79,11 +82,12 @@ impl MemoInvalidations {self.notes_of(slot).text_memos_dropped = true;}- /// The fragment cache epoch of `node` moved on: its run cache entries need the sweep, and its in-flow block entry,- /// valid for one epoch only, is dropped.+ /// The fragment cache epoch of `node` moved on: its run cache entries need the sweep, and its in-flow block entry+ /// and prepared inline content, valid for one epoch only, are dropped.pub(crate) fn note_fragment_cache_epoch_bumped(&mut self, node: NodeSlotId) {let notes = self.notes_of(node.slot_index());notes.in_flow_block_entries_dropped = true;+ notes.prepared_inline_content_dropped = true;if !notes.run_cache_entries_dropped {notes.fragment_cache_epoch_bumped = true;notes.generation = node.generation();@@ -105,6 +109,7 @@ impl MemoInvalidations {run_cache: &FcRunCacheStore,in_flow_block_cache: &InFlowBlockCacheStore,text_memos: &TextMemos,+ prepared_inline_content: &PreparedInlineContentMemos,intrinsic_size_caches: &IntrinsicSizeCaches,) {for slot in self.noted_slots {@@ -126,6 +131,9 @@ impl MemoInvalidations {if notes.text_memos_dropped {text_memos.forget(slot);}+ if notes.prepared_inline_content_dropped {+ prepared_inline_content.forget(slot);+ }if notes.intrinsic_sizes_dropped {intrinsic_size_caches.drop_entries_of_slot(slot);}diff --git a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rsindex 9a7baeee3fb..a0499da51a0 100644--- a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs+++ b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs@@ -4,12 +4,15 @@* SPDX-License-Identifier: BSD-2-Clause*/+use super::fc_run_cache::{FcRunCacheValidity, run_root_validity};use super::inline_level_iterator::ItemType;use super::*;use libgfx_rust::font::FontHandle;use libgfx_rust::text_layout::SharedShape;+use std::sync::Arc;pub(crate) struct PreparedInlineContent {+ pub(super) validity: FcRunCacheValidity,pub(super) items: Box<[PreparedItem]>,pub(super) box_events: Box<[InlineBoxEvent]>,pub(super) fonts: Box<[FontHandle]>,@@ -21,7 +24,7 @@ const _: () = {assert_send_and_sync::<PreparedInlineContent>();};-#[derive(Clone)]+#[derive(Clone, Debug, PartialEq)]pub(super) struct PreparedItem {shape: Option<SharedShape>,node: Node,@@ -119,7 +122,7 @@ impl PreparedItem {}}-#[derive(Clone, Copy)]+#[derive(Clone, Copy, Debug, PartialEq)]pub(super) struct InlineBoxEvent {position: u32,entered_box: Node,@@ -155,7 +158,7 @@ impl InlineBoxEvent {}}-#[derive(Clone, Copy)]+#[derive(Clone, Copy, Debug, PartialEq)]pub(super) struct PreparedTabStop {pub(super) tab_count: u32,pub(super) tab_inline_size: CssPixels,@@ -175,9 +178,10 @@ pub(crate) struct InlineContentPreparationBuffers {}impl InlineContentPreparationBuffers {- pub(super) fn take_prepared_inline_content(&mut self) -> PreparedInlineContent {+ pub(super) fn take_prepared_inline_content(&mut self, validity: FcRunCacheValidity) -> PreparedInlineContent {self.box_stack.clear();PreparedInlineContent {+ validity,items: self.items.drain(..).collect(),box_events: self.box_events.drain(..).collect(),fonts: self.fonts.drain(..).collect(),@@ -185,3 +189,92 @@ impl InlineContentPreparationBuffers {}}}++impl PreparedInlineContent {+ pub(crate) fn for_block_container(pass: LayoutPass<'_>, block_container: Node) -> Arc<Self> {+ if pass.reads_no_memoized_layout() || pass.lays_out_with_position_option() {+ return Arc::new(Self::prepare(pass, block_container));+ }+ let memos = pass.prepared_inline_content_memos();+ if let Some(kept) = memos.kept(block_container, run_root_validity(&pass, block_container)) {+ if cfg!(debug_assertions) || run_repeatability::verification_is_enabled() {+ kept.verify_against_fresh_preparation(pass, block_container);+ }+ return kept;+ }+ let prepared = Arc::new(Self::prepare(pass, block_container));+ if !prepared.is_empty() {+ memos.keep(block_container, prepared.clone());+ }+ prepared+ }++ fn is_empty(&self) -> bool {+ self.items.is_empty() && self.box_events.is_empty()+ }++ fn verify_against_fresh_preparation(&self, pass: LayoutPass<'_>, block_container: Node) {+ let fresh = Self::prepare(pass, block_container);+ if let Some(difference) = self.first_difference_from(&fresh) {+ panic!(+ "the inline content kept for {block_container:?} differs from its fresh preparation in {difference}"+ );+ }+ }++ fn first_difference_from(&self, fresh: &Self) -> Option<String> {+ fn first_difference<T: PartialEq + std::fmt::Debug>(name: &str, kept: &[T], fresh: &[T]) -> Option<String> {+ let index = (0..kept.len().max(fresh.len())).find(|index| kept.get(*index) != fresh.get(*index))?;+ Some(format!(+ "{name} {index}: kept {:?}, prepared {:?}",+ kept.get(index),+ fresh.get(index)+ ))+ }+ first_difference("item", &self.items, &fresh.items)+ .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))+ }+}++#[derive(Default)]+pub(crate) struct PreparedInlineContentMemos {+ by_slot: RefCell<Vec<Option<Arc<PreparedInlineContent>>>>,+}++impl PreparedInlineContentMemos {+ pub(crate) fn fork(&self) -> Self {+ Self {+ by_slot: self.by_slot.clone(),+ }+ }++ pub(crate) fn kept(+ &self,+ block_container: Node,+ validity: FcRunCacheValidity,+ ) -> Option<Arc<PreparedInlineContent>> {+ self.by_slot+ .borrow()+ .get(block_container.slot_index() as usize)?+ .as_ref()+ .filter(|kept| kept.validity == validity)+ .cloned()+ }++ pub(crate) fn keep(&self, block_container: Node, prepared: Arc<PreparedInlineContent>) {+ let index = block_container.slot_index() as usize;+ let mut by_slot = self.by_slot.borrow_mut();+ if by_slot.len() <= index {+ by_slot.resize_with(index + 1, || None);+ }+ by_slot[index] = Some(prepared);+ }++ pub(crate) fn forget(&self, slot: u32) {+ if let Some(kept) = self.by_slot.borrow_mut().get_mut(slot as usize) {+ *kept = None;+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rsindex 69086a5d226..0871693035a 100644--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs@@ -647,6 +647,52 @@ mod tests {assert_eq!(Arc::strong_count(&new_chunks), 1);}+ #[test]+ fn kept_prepared_inline_content_goes_with_an_epoch_bump_or_a_freed_slot_and_survives_a_fork() {+ use crate::layout::LayoutPass;+ use crate::layout::fc_run_cache::run_root_validity;+ use crate::layout::prepared_inline_content::PreparedInlineContent;+ use crate::layout::run_state::LayoutScratch;+ use std::sync::Arc;++ let mut arena = LayoutNodeArena::new();+ let scratch = LayoutScratch::default();+ let block = arena.allocate_for_test().slot;+ scratch.apply_memo_invalidations(&mut arena);+ let keep = |arena: &LayoutNodeArena, scratch: &LayoutScratch| {+ let validity = run_root_validity(&LayoutPass::for_test(arena, scratch), block);+ let prepared = Arc::new(PreparedInlineContent {+ validity,+ items: Box::default(),+ box_events: Box::default(),+ fonts: Box::default(),+ tab_stops: Box::default(),+ });+ scratch.prepared_inline_content_memos().keep(block, prepared.clone());+ (validity, Arc::downgrade(&prepared))+ };+ let kept = |scratch: &LayoutScratch, validity| scratch.prepared_inline_content_memos().kept(block, validity);++ let (validity, prepared) = keep(&arena, &scratch);+ arena.clear_committed_fragment_link(block);+ scratch.apply_memo_invalidations(&mut arena);+ assert!(kept(&scratch, validity).is_some_and(|kept| Arc::ptr_eq(&kept, &prepared.upgrade().unwrap())));++ let fork = scratch.fork();+ arena.invalidate_fragments_of_self_and_ancestors_for_change_that_sizes_no_box(block);+ scratch.apply_memo_invalidations(&mut arena);+ assert!(kept(&scratch, validity).is_none());+ assert!(kept(&fork, validity).is_some_and(|kept| Arc::ptr_eq(&kept, &prepared.upgrade().unwrap())));+ drop(fork);+ assert!(prepared.upgrade().is_none());++ let (validity, prepared) = keep(&arena, &scratch);+ assert!(kept(&scratch, validity).is_some());+ let _ = arena.free_subtree(block);+ scratch.apply_memo_invalidations(&mut arena);+ assert!(prepared.upgrade().is_none());+ }+#[test]fn identity_mapping_clamps_offsets_to_the_dom_slice() {let text = content("hello", 3, 5, Vec::new());diff --git a/Libraries/LibWeb/Rust/src/layout/run_state.rs b/Libraries/LibWeb/Rust/src/layout/run_state.rsindex b3413cf126f..1173b23f428 100644--- a/Libraries/LibWeb/Rust/src/layout/run_state.rs+++ b/Libraries/LibWeb/Rust/src/layout/run_state.rs@@ -27,6 +27,7 @@ pub(crate) struct LayoutScratch {/// The chunks and grapheme segmenters of the text rows the passes laid out.text_memos: super::rendered_text::TextMemos,inline_content_preparation_buffers: Cell<super::prepared_inline_content::InlineContentPreparationBuffers>,+ prepared_inline_content_memos: super::prepared_inline_content::PreparedInlineContentMemos,}/// What layout found out that the host hears of once the layout that found it is committed: what the@@ -103,6 +104,7 @@ impl Default for LayoutScratch {layout_trace: Default::default(),text_memos: Default::default(),inline_content_preparation_buffers: Default::default(),+ prepared_inline_content_memos: Default::default(),}}}@@ -115,6 +117,7 @@ impl LayoutScratch {fc_run_cache_store: self.fc_run_cache_store.clone(),in_flow_block_cache_store: self.in_flow_block_cache_store.clone(),text_memos: self.text_memos.fork(),+ prepared_inline_content_memos: self.prepared_inline_content_memos.fork(),..Self::default()}}@@ -131,6 +134,10 @@ impl LayoutScratch {&self.text_memos}+ pub(super) fn prepared_inline_content_memos(&self) -> &super::prepared_inline_content::PreparedInlineContentMemos {+ &self.prepared_inline_content_memos+ }+pub(super) fn inline_content_preparation_buffers(&self,) -> &Cell<super::prepared_inline_content::InlineContentPreparationBuffers> {@@ -143,6 +150,7 @@ impl LayoutScratch {&self.fc_run_cache_store,&self.in_flow_block_cache_store,&self.text_memos,+ &self.prepared_inline_content_memos,&self.intrinsic_size_caches,);}diff --git a/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-after-font-load.txt b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-after-font-load.txtnew file mode 100644index 00000000000..71a9a6467df--- /dev/null+++ b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-after-font-load.txt@@ -0,0 +1,3 @@+before the font loads: true true true+font load: moved true, matches a fresh layout: true true true+font removal: moved true, matches a fresh layout: true true truediff --git a/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-after-text-and-style-changes.txt b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-after-text-and-style-changes.txtnew file mode 100644index 00000000000..2b9ef3b2a59--- /dev/null+++ b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-after-text-and-style-changes.txt@@ -0,0 +1,12 @@+before any change: true true true+text edit: moved true, matches a fresh layout: true true true+font-size: moved true, matches a fresh layout: true true true+letter-spacing: moved true, matches a fresh layout: true true true+word-spacing: moved true, matches a fresh layout: true true true+text-transform on: moved true, matches a fresh layout: true true true+text-transform off: moved true, matches a fresh layout: true true true+white-space: moved true, matches a fresh layout: true true true+span insert: moved true, matches a fresh layout: true true true+span remove: moved true, matches a fresh layout: true true true+lang: moved true, matches a fresh layout: true true true+direction: moved true, matches a fresh layout: true true truediff --git a/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-with-balance-and-columns.txt b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-with-balance-and-columns.txtnew file mode 100644index 00000000000..8bc1a7deb30--- /dev/null+++ b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-with-balance-and-columns.txt@@ -0,0 +1,5 @@+before any change: true true true+balances its lines: true true true true true true+fills three columns: 3 3 3+text edit in columns: moved true, matches a fresh layout: true true true+fills three columns after the edit: 3 3 3diff --git a/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-with-width-dependent-parts.txt b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-with-width-dependent-parts.txtnew file mode 100644index 00000000000..f54c2844b45--- /dev/null+++ b/Tests/LibWeb/Text/expected/inline-content-reused-across-widths-with-width-dependent-parts.txt@@ -0,0 +1,5 @@+before any change: true true true+percentage padding: moved true, matches a fresh layout: true true true+text after tabs: moved true, matches a fresh layout: true true true+float width: moved true, matches a fresh layout: true true true+vertical text: moved true, matches a fresh layout: true true truediff --git a/Tests/LibWeb/Text/input/inline-content-reused-across-widths-after-font-load.html b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-after-font-load.htmlnew file mode 100644index 00000000000..8b8bd137c3c--- /dev/null+++ b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-after-font-load.html@@ -0,0 +1,65 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ body { margin: 0; font: 16px/20px serif; }+ p { margin: 0 0 8px; }+ .loaded { font-family: ReusedAcrossWidths, monospace; }+</style>+<div id="container">+ <p class="loaded">This paragraph is shaped with a fallback font until its own font face loads.</p>+ <p>Only <span class="loaded">these few words</span> of this paragraph use the face that loads.</p>+ <p>This paragraph never uses the face, so it keeps the inline content it prepared.</p>+</div>+<script>+ const widths = [240, 320, 410];++ function geometry(root) {+ const origin = root.getBoundingClientRect();+ const relative = rect => `${rect.left - origin.left},${rect.top - origin.top},${rect.width},${rect.height}`;+ const parts = Array.from(root.querySelectorAll("*"), element => relative(element.getBoundingClientRect()));+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const range = document.createRange();+ while (walker.nextNode()) {+ range.selectNodeContents(walker.currentNode);+ parts.push(Array.from(range.getClientRects(), relative).join(";"));+ }+ return parts.join(" ");+ }++ function layOutAt(width) {+ container.style.width = `${width}px`;+ return geometry(container);+ }++ function matchesFreshLayoutAt(width) {+ const relaidOut = layOutAt(width);+ const fresh = container.cloneNode(true);+ fresh.removeAttribute("id");+ document.body.appendChild(fresh);+ const freshGeometry = geometry(fresh);+ fresh.remove();+ return relaidOut === freshGeometry;+ }++ async function afterChange(name, change) {+ const before = layOutAt(widths[0]);+ await change();+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ const moved = layOutAt(widths[0]) !== before;+ const matches = [...widths.slice(1), widths[0]].map(matchesFreshLayoutAt);+ println(`${name}: moved ${moved}, matches a fresh layout: ${matches.join(" ")}`);+ }++ asyncTest(async done => {+ for (const width of widths)+ layOutAt(width);+ println(`before the font loads: ${widths.map(matchesFreshLayoutAt).join(" ")}`);+ const face = new FontFace("ReusedAcrossWidths", "url(../../Assets/HashSans.woff)");+ await afterChange("font load", async () => {+ await face.load();+ document.fonts.add(face);+ });+ await afterChange("font removal", () => document.fonts.delete(face));+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/inline-content-reused-across-widths-after-text-and-style-changes.html b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-after-text-and-style-changes.htmlnew file mode 100644index 00000000000..b6fec5b244e--- /dev/null+++ b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-after-text-and-style-changes.html@@ -0,0 +1,91 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ @font-face {+ font-family: Mplus;+ src: url("wpt-import/fonts/mplus-1p-regular.woff");+ }+ body { margin: 0; font: 16px/20px serif; }+ p { margin: 0 0 8px; }+ .cjk { font: 20px/1 Mplus; line-break: loose; }+ .min-content { display: inline-block; width: min-content; }+</style>+<div id="container">+ <p class="edited">The quick brown fox jumps over the lazy dog and then runs far away from it.</p>+ <p>Some <span class="sized">sized text</span> and <span class="spaced">letter spaced words</span> in a line.</p>+ <p class="words">Word spacing moves every word of this paragraph a little further apart.</p>+ <p class="transformed">transformed text changes its case and with it the shaping of the line</p>+ <p class="spaces">Collapsible spaces become preserved spaces here</p>+ <p class="host">A paragraph that gets an inserted span and then loses it again.</p>+ <p class="cjk">文文文文文文・字字 <span class="min-content">文・文・</span></p>+ <p class="bidi">Mixed English and עברית text with 123 numbers and more words after it.</p>+</div>+<script>+ const widths = [240, 320, 410];++ function geometry(root) {+ const origin = root.getBoundingClientRect();+ const relative = rect => `${rect.left - origin.left},${rect.top - origin.top},${rect.width},${rect.height}`;+ const parts = Array.from(root.querySelectorAll("*"), element => relative(element.getBoundingClientRect()));+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const range = document.createRange();+ while (walker.nextNode()) {+ range.selectNodeContents(walker.currentNode);+ parts.push(Array.from(range.getClientRects(), relative).join(";"));+ }+ return parts.join(" ");+ }++ function layOutAt(width) {+ container.style.width = `${width}px`;+ return geometry(container);+ }++ function matchesFreshLayoutAt(width) {+ const relaidOut = layOutAt(width);+ const fresh = container.cloneNode(true);+ fresh.removeAttribute("id");+ document.body.appendChild(fresh);+ const freshGeometry = geometry(fresh);+ fresh.remove();+ return relaidOut === freshGeometry;+ }++ asyncTest(async done => {+ await document.fonts.load("20px Mplus");+ const paragraph = name => container.querySelector(`.${name}`);+ let inserted = null;+ const changes = [+ ["text edit", () => (paragraph("edited").firstChild.data = "A different sentence, which wraps in other places than the first one.")],+ ["font-size", () => (paragraph("sized").style.fontSize = "26px")],+ ["letter-spacing", () => (paragraph("spaced").style.letterSpacing = "3px")],+ ["word-spacing", () => (paragraph("words").style.wordSpacing = "9px")],+ ["text-transform on", () => (paragraph("transformed").style.textTransform = "uppercase")],+ ["text-transform off", () => (paragraph("transformed").style.textTransform = "none")],+ ["white-space", () => (paragraph("spaces").style.whiteSpace = "pre-wrap")],+ [+ "span insert",+ () => {+ inserted = document.createElement("span");+ inserted.textContent = "with a few more inserted words ";+ paragraph("host").insertBefore(inserted, paragraph("host").firstChild.splitText(2));+ },+ ],+ ["span remove", () => inserted.remove()],+ ["lang", () => (paragraph("cjk").lang = "ja")],+ ["direction", () => (paragraph("bidi").style.direction = "rtl")],+ ];++ for (const width of widths)+ layOutAt(width);+ println(`before any change: ${widths.map(matchesFreshLayoutAt).join(" ")}`);+ for (const [name, change] of changes) {+ const before = layOutAt(widths[0]);+ change();+ const moved = layOutAt(widths[0]) !== before;+ const matches = [...widths.slice(1), widths[0]].map(matchesFreshLayoutAt);+ println(`${name}: moved ${moved}, matches a fresh layout: ${matches.join(" ")}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/inline-content-reused-across-widths-with-balance-and-columns.html b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-with-balance-and-columns.htmlnew file mode 100644index 00000000000..cd4eb9e4e03--- /dev/null+++ b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-with-balance-and-columns.html@@ -0,0 +1,76 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ body { margin: 0; font: 16px/20px serif; }+ p { margin: 0 0 8px; }+ .balanced { text-wrap: balance; }+ .columns { columns: 3; column-gap: 12px; }+</style>+<div id="container">+ <p class="balanced">A balanced paragraph spreads its words over its lines evenly, so its last line is about as long as the others are.</p>+ <p class="wrapped">A balanced paragraph spreads its words over its lines evenly, so its last line is about as long as the others are.</p>+ <div class="columns"><p class="in-columns">The text of this paragraph flows through three columns, and each relayout at another width moves the column breaks to other words of it. Then an edit gives the paragraph other text, which the columns have to break anew at every width.</p></div>+</div>+<script>+ const widths = [240, 320, 410];++ function geometry(root) {+ const origin = root.getBoundingClientRect();+ const relative = rect => `${rect.left - origin.left},${rect.top - origin.top},${rect.width},${rect.height}`;+ const parts = Array.from(root.querySelectorAll("*"), element => relative(element.getBoundingClientRect()));+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const range = document.createRange();+ while (walker.nextNode()) {+ range.selectNodeContents(walker.currentNode);+ parts.push(Array.from(range.getClientRects(), relative).join(";"));+ }+ return parts.join(" ");+ }++ function layOutAt(width) {+ container.style.width = `${width}px`;+ return geometry(container);+ }++ function matchesFreshLayoutAt(width) {+ const relaidOut = layOutAt(width);+ const fresh = container.cloneNode(true);+ fresh.removeAttribute("id");+ document.body.appendChild(fresh);+ const freshGeometry = geometry(fresh);+ fresh.remove();+ return relaidOut === freshGeometry;+ }++ function lineRects(paragraph) {+ const range = document.createRange();+ range.selectNodeContents(paragraph.firstChild);+ return Array.from(range.getClientRects());+ }++ test(() => {+ const part = selector => container.querySelector(selector);+ for (const width of widths)+ layOutAt(width);+ println(`before any change: ${widths.map(matchesFreshLayoutAt).join(" ")}`);+ const balancesLinesAt = width => {+ layOutAt(width);+ const balanced = lineRects(part(".balanced"));+ const wrapped = lineRects(part(".wrapped"));+ return balanced.length === wrapped.length && balanced.at(-1).width > wrapped.at(-1).width;+ };+ println(`balances its lines: ${[...widths, ...widths].map(balancesLinesAt).join(" ")}`);+ const columnCountAt = width => {+ layOutAt(width);+ return new Set(lineRects(part(".in-columns")).map(rect => rect.left)).size;+ };+ println(`fills three columns: ${widths.map(columnCountAt).join(" ")}`);++ const before = layOutAt(widths[0]);+ part(".in-columns").firstChild.data = "Other text for the paragraph in columns, shorter than the text it replaces but still long enough to fill all of the three columns at every width.";+ const moved = layOutAt(widths[0]) !== before;+ const matches = [...widths.slice(1), widths[0]].map(matchesFreshLayoutAt);+ println(`text edit in columns: moved ${moved}, matches a fresh layout: ${matches.join(" ")}`);+ println(`fills three columns after the edit: ${widths.map(columnCountAt).join(" ")}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/inline-content-reused-across-widths-with-width-dependent-parts.html b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-with-width-dependent-parts.htmlnew file mode 100644index 00000000000..eb9005e0509--- /dev/null+++ b/Tests/LibWeb/Text/input/inline-content-reused-across-widths-with-width-dependent-parts.html@@ -0,0 +1,76 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ body { margin: 0; font: 16px/20px serif; }+ #container { display: flow-root; }+ p { margin: 0 0 8px; }+ .padded { padding: 0 5%; margin: 0 3%; border: 1px solid; }+ .percentage-width { display: inline-block; width: 20%; height: 10px; }+ .tabs { white-space: pre-wrap; tab-size: 4; }+ .tabs .atomic { display: inline-block; width: 12%; height: 10px; }+ .bordered { border: 3px solid; padding: 0 4px; position: relative; }+ .float { float: left; width: 15%; height: 20px; }+ .abspos { position: absolute; left: 10%; top: 0; width: 25%; height: 6px; }+ .vertical { writing-mode: vertical-rl; text-orientation: upright; white-space: pre-wrap; height: 50%; }+ .vertical span { padding-top: 10%; }+</style>+<div id="container">+ <p>Words around <span class="padded">a span with percentage padding and margin</span> that wraps.</p>+ <p>An inline-block <span class="percentage-width"></span> whose width is a percentage of the line.</p>+ <p class="tabs">a<span class="atomic"></span> b c d end of the tabbed line</p>+ <p>Before <span class="bordered">a bordered span with <span class="float"></span>a float and <span class="abspos"></span>an abspos inside it</span> after.</p>+ <div class="vertical">up<span>right</span> tab and more upright text</div>+</div>+<script>+ const widths = [240, 320, 410];++ function geometry(root) {+ const origin = root.getBoundingClientRect();+ const relative = rect => `${rect.left - origin.left},${rect.top - origin.top},${rect.width},${rect.height}`;+ const parts = Array.from(root.querySelectorAll("*"), element => relative(element.getBoundingClientRect()));+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const range = document.createRange();+ while (walker.nextNode()) {+ range.selectNodeContents(walker.currentNode);+ parts.push(Array.from(range.getClientRects(), relative).join(";"));+ }+ return parts.join(" ");+ }++ function layOutAt(width) {+ container.style.width = `${width}px`;+ container.style.height = `${width / 2}px`;+ return geometry(container);+ }++ function matchesFreshLayoutAt(width) {+ const relaidOut = layOutAt(width);+ const fresh = container.cloneNode(true);+ fresh.removeAttribute("id");+ document.body.appendChild(fresh);+ const freshGeometry = geometry(fresh);+ fresh.remove();+ return relaidOut === freshGeometry;+ }++ test(() => {+ const part = selector => container.querySelector(selector);+ const changes = [+ ["percentage padding", () => (part(".padded").style.paddingLeft = "8%")],+ ["text after tabs", () => (part(".tabs").lastChild.data = " b c the line goes on with other text")],+ ["float width", () => (part(".float").style.width = "25%")],+ ["vertical text", () => (part(".vertical").lastChild.data = " tab and other upright text")],+ ];++ for (const width of widths)+ layOutAt(width);+ println(`before any change: ${widths.map(matchesFreshLayoutAt).join(" ")}`);+ for (const [name, change] of changes) {+ const before = layOutAt(widths[0]);+ change();+ const moved = layOutAt(widths[0]) !== before;+ const matches = [...widths.slice(1), widths[0]].map(matchesFreshLayoutAt);+ println(`${name}: moved ${moved}, matches a fresh layout: ${matches.join(" ")}`);+ }+ });+</script>