Truly independent web browser
LibWeb: Order atomic inline boxes from the paragraph direction
sideshowbarker0fe7e42e0245
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rsindex 1efa99f5daf..c825c5510ac 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_formatting_context.rs@@ -328,7 +328,12 @@ fn apply_block_ellipsis(line.push_fragment(ellipsis);}-pub(crate) fn apply_to_fragments(text_justify: u8, line: &mut line_box::LineBoxData, is_last_line: bool) {+pub(crate) fn apply_to_fragments(+ text_justify: u8,+ atomic_items_are_right_to_left: bool,+ line: &mut line_box::LineBoxData,+ is_last_line: bool,+) {if text_justify == text_justify::NONE || is_last_line || line.has_forced_break {return;}@@ -353,7 +358,15 @@ pub(crate) fn apply_to_fragments(text_justify: u8, line: &mut line_box::LineBoxD};let mut running_diff = CssPixels::default();- for fragment in &mut line.fragments {+ // Expand spaces in increasing inline-coordinate order, including when logical order was mirrored for placement.+ let fragment_count = line.fragments.len();+ for index in 0..fragment_count {+ let index = if atomic_items_are_right_to_left {+ fragment_count - 1 - index+ } else {+ index+ };+ let fragment = &mut line.fragments[index];if fragment.is_fully_truncated {continue;}@@ -988,6 +1001,7 @@ pub(crate) struct InlineFormattingContext<'context> {line_data: RefCell<used_values::LineData>,pub(crate) fragmented_inlines_in_pre_order: Vec<Node>,pub(crate) current_line_start: Cell<fragmentation::LinePosition>,+ pub(crate) atomic_items_are_right_to_left: bool,inline_boxes_continued_from_previous_fragment: Vec<Node>,inline_boxes_continued_in_next_fragment: RefCell<Vec<Node>>,block_axis_float_clearance: Cell<CssPixels>,@@ -1038,6 +1052,7 @@ impl<'context> InlineFormattingContext<'context> {line_data: RefCell::new(used_values::LineData::default()),fragmented_inlines_in_pre_order: Vec::new(),current_line_start: Cell::new(fragmentation::LinePosition::default()),+ atomic_items_are_right_to_left: false,inline_boxes_continued_from_previous_fragment: Vec::new(),inline_boxes_continued_in_next_fragment: RefCell::new(Vec::new()),block_axis_float_clearance: Cell::new(CssPixels::default()),@@ -1537,6 +1552,7 @@ impl<'context> InlineFormattingContext<'context> {iterator: &inline_level_iterator::InlineLevelIterator,) -> (Vec<line_box::LineBoxData>, usize) {if self.containing_block != self.run.box_+ || self.atomic_items_are_right_to_left|| !previous.inline_box_pieces.is_empty()|| iterator.items()@@ -2715,6 +2731,7 @@ impl<'context> InlineFormattingContext<'context> {.is_none();apply_to_fragments(containing_style.text_justify(),+ self.atomic_items_are_right_to_left,&mut self.line_data_mut().line_boxes[index],is_last_line,);diff --git a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rsindex 135e9c8fec2..e2f9cd5e676 100644--- a/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs+++ b/Libraries/LibWeb/Rust/src/layout/inline_level_iterator.rs@@ -728,6 +728,51 @@ struct InlineContentPreparer<'pass> {}impl PreparedInlineContent {+ fn orders_atomic_items_right_to_left(+ &self,+ context: &inline_formatting_context::InlineFormattingContext<'_>,+ ) -> bool {+ let style = context.style(context.containing_block);+ if style.direction() != direction::RTL || style.unicode_bidi() == unicode_bidi::PLAINTEXT {+ return false;+ }+ if self+ .box_events+ .iter()+ .filter_map(InlineBoxEvent::entered_box)+ .any(|node| {+ let style = context.style(node);+ style.unicode_bidi() != unicode_bidi::NORMAL || style.direction() != direction::RTL+ })+ {+ return false;+ }++ // https://drafts.csswg.org/css-writing-modes-4/#bidi-atomic-inlines+ // All other atomic inline-level boxes are treated as neutral characters always.+ // FIXME: Resolve paragraph-wide bidi levels for mixed text and atomic boxes, and for explicit embeddings.+ let mut has_atomic_box = false;+ self.items.iter().all(|item| match item.type_() {+ ItemType::Element => {+ let facts = context.facts(item.node());+ if !facts.is_atomic_inline()+ || (facts.is_replaced_box()+ && matches!(+ context.style(item.node()).unicode_bidi(),+ unicode_bidi::EMBED | unicode_bidi::BIDI_OVERRIDE | unicode_bidi::ISOLATE_OVERRIDE+ ))+ {+ return false;+ }+ has_atomic_box = true;+ true+ }+ ItemType::Text => item.has(PreparedItem::TRAILING_WHITESPACE_IS_WHOLE_ITEM),+ ItemType::ForcedBreak | ItemType::AbsolutelyPositionedElement | ItemType::FloatingElement => true,+ ItemType::BlockLevelBox | ItemType::InlineEdge => false,+ }) && has_atomic_box+ }+pub(super) fn prepare(pass: LayoutPass<'_>, block_container: Node) -> Self {InlineContentPreparer::prepare(pass, block_container)}@@ -737,6 +782,7 @@ impl PreparedInlineContent {context: &mut inline_formatting_context::InlineFormattingContext<'_>,atomic_sizing: AtomicInlineSizing,) -> InlineLevelIterator {+ context.atomic_items_are_right_to_left = self.orders_atomic_items_right_to_left(context);let (entered_box_model_nodes, items) = RunItemResolver {context,prepared: &self,@@ -1461,7 +1507,7 @@ impl<'context> RunItemResolver<'_, 'context> {return false;}let mut item = Item::new(ItemType::InlineEdge, edge.node, Item::NOT_RESOLVED_FROM_A_PREPARED_ITEM);- if edge.is_low {+ if edge.is_low != context.atomic_items_are_right_to_left {item.margin_start = edge.margin;item.border_start = edge.border;item.padding_start = edge.padding;@@ -1498,7 +1544,7 @@ impl<'context> RunItemResolver<'_, 'context> {} else {(sides.margin_right, sides.border_right, sides.padding_right)};- let physical = if is_start {+ let physical = if is_start != self.context().atomic_items_are_right_to_left {ExtraBoxMetrics {margin: sides.margin_left,border: sides.border_left,@@ -1775,6 +1821,11 @@ impl<'context> RunItemResolver<'_, 'context> {box_cells: Some(box_cells),}));}+ if self.context().atomic_items_are_right_to_left {+ std::mem::swap(&mut item.margin_start, &mut item.margin_end);+ std::mem::swap(&mut item.border_start, &mut item.border_end);+ std::mem::swap(&mut item.padding_start, &mut item.padding_end);+ }self.add_extra_box_model_metrics_to_item(&mut item,prepared_item.has(PreparedItem::TAKES_LEADING_EDGES),@@ -1895,6 +1946,7 @@ impl InlineLevelIterator {)});if let Some((items, entered_box_model_nodes, prepared)) = shared {+ context.atomic_items_are_right_to_left = prepared.orders_atomic_items_right_to_left(context);for node in entered_box_model_nodes.iter() {lay_out_entered_inline_box(context, *node);}diff --git a/Libraries/LibWeb/Rust/src/layout/line_builder.rs b/Libraries/LibWeb/Rust/src/layout/line_builder.rsindex 56549ad217b..1fccd31cf18 100644--- a/Libraries/LibWeb/Rust/src/layout/line_builder.rs+++ b/Libraries/LibWeb/Rust/src/layout/line_builder.rs@@ -1146,6 +1146,13 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {);}+ // Mirroring must use the retained line width, so discarded trailing spaces don't become leading gaps.+ if self.context().atomic_items_are_right_to_left+ && self.line(line_index).inline_length_before_block_ellipsis.is_none()+ {+ self.line_mut(line_index).trim_trailing_whitespace();+ }+let current_line_block_size = if self.line(line_index).inline_length_before_block_ellipsis.is_some() {self.line(line_index).visible_fragments()@@ -1378,7 +1385,14 @@ impl<'builder, 'context> LineBuilder<'builder, 'context> {atomic_inline.margin_bottom + atomic_inline.border_box_bottom(false);}let containing_block = self.context().containing_block;- let new_inline_offset = inline_offset + snapshot.inline_offset;+ let fragment_inline_offset = if self.context().atomic_items_are_right_to_left {+ self.line(line_index).inline_length+ - snapshot.inline_offset+ - self.line(line_index).fragments[fragment_index].inline_length+ } else {+ snapshot.inline_offset+ };+ let new_inline_offset = inline_offset + fragment_inline_offset;let own_alignment_is_line_relative = line_relative_alignment(style).is_some();let aligned_subtree = has_line_relative_aligned_subtree.then(|| self.line_relative_aligned_subtree_root(snapshot.style_source))diff --git a/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-box-edges.txt b/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-box-edges.txtnew file mode 100644index 00000000000..2e799c583c6--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-box-edges.txt@@ -0,0 +1,23 @@+plain: 190,0; 140,0; 90,0+own edges: 165,0; 85,0; 5,0+negative margin: 181,0; 127,0; 73,0+parent edges: 158,0; 108,0; 58,0+spaces: 190,0; 120,0; 50,0+wrapped: 90,0; 40,0; 90,20+wrapped parent: 58,0; 8,0; 90,20+initial ltr: 0,50,100+changed to rtl: 190,140,90+appended rtl child: 190,140,90,40+changed back to ltr: 0,50,100+HTML direction: 2,1,0+plaintext: 0,1,2+LTR override: 0,1,2+vertical-rl, mixed: 190,140,90+vertical-rl, upright: 190,140,90+vertical-lr, mixed: 190,140,90+vertical-lr, upright: 190,140,90+sideways-rl, mixed: 190,140,90+sideways-rl, upright: 190,140,90+sideways-lr, mixed: 0,50,100+sideways-lr, upright: 0,50,100+Latin text around atomic box: 0,1,2diff --git a/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-justification.txt b/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-justification.txtnew file mode 100644index 00000000000..6c9f386c49b--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-justification.txt@@ -0,0 +1,16 @@+ltr start 200 direct: 0,80; wrapped=true+ltr start 200 nested: 0,80; wrapped=true+ltr start 280 direct: 0,80,160; wrapped=true+ltr start 280 nested: 0,80,160; wrapped=true+ltr justify 200 direct: 0,140; wrapped=true+ltr justify 200 nested: 0,140; wrapped=true+ltr justify 280 direct: 0,110,220; wrapped=true+ltr justify 280 nested: 0,110,220; wrapped=true+rtl start 200 direct: 140,60; wrapped=true+rtl start 200 nested: 140,60; wrapped=true+rtl start 280 direct: 220,140,60; wrapped=true+rtl start 280 nested: 220,140,60; wrapped=true+rtl justify 200 direct: 140,0; wrapped=true+rtl justify 200 nested: 140,0; wrapped=true+rtl justify 280 direct: 220,110,0; wrapped=true+rtl justify 280 nested: 220,110,0; wrapped=truediff --git a/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-order.txt b/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-order.txtnew file mode 100644index 00000000000..75f9cb20fa8--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/rtl-atomic-inline-order.txt@@ -0,0 +1,8 @@+ltr, nested=false, scroll=0: 0, 80, 580; width=880+ltr, nested=false, scroll=100: -100, -20, 480; width=880+ltr, nested=true, scroll=0: 0, 80, 580; width=880+ltr, nested=true, scroll=100: -100, -20, 480; width=880+rtl, nested=false, scroll=0: 140, -360, -660; width=880+rtl, nested=false, scroll=-100: 240, -260, -560; width=880+rtl, nested=true, scroll=0: 140, -360, -660; width=880+rtl, nested=true, scroll=-100: 240, -260, -560; width=880diff --git a/Tests/LibWeb/Text/expected/wpt-import/mathml/relations/css-styling/writing-mode/writing-mode-002.txt b/Tests/LibWeb/Text/expected/wpt-import/mathml/relations/css-styling/writing-mode/writing-mode-002.txtindex 29e84011a51..af48c164c26 100644--- a/Tests/LibWeb/Text/expected/wpt-import/mathml/relations/css-styling/writing-mode/writing-mode-002.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/mathml/relations/css-styling/writing-mode/writing-mode-002.txt@@ -2,24 +2,23 @@ Harness status: OKFound 30 tests-25 Pass-5 Fail+30 PassPass Layout of a (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of maction (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of menclose (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of merror (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mfrac (writing-mode: horizontal-tb; direction: rtl;)-Fail Layout of mi (writing-mode: horizontal-tb; direction: rtl;)+Pass Layout of mi (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mmultiscripts (writing-mode: horizontal-tb; direction: rtl;)-Fail Layout of mn (writing-mode: horizontal-tb; direction: rtl;)-Fail Layout of mo (writing-mode: horizontal-tb; direction: rtl;)+Pass Layout of mn (writing-mode: horizontal-tb; direction: rtl;)+Pass Layout of mo (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mover (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mpadded (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mphantom (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mprescripts (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mroot (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mrow (writing-mode: horizontal-tb; direction: rtl;)-Fail Layout of ms (writing-mode: horizontal-tb; direction: rtl;)+Pass Layout of ms (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mspace (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of msqrt (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mstyle (writing-mode: horizontal-tb; direction: rtl;)@@ -28,7 +27,7 @@ Pass Layout of msubsup (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of msup (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mtable (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mtd (writing-mode: horizontal-tb; direction: rtl;)-Fail Layout of mtext (writing-mode: horizontal-tb; direction: rtl;)+Pass Layout of mtext (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of mtr (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of munder (writing-mode: horizontal-tb; direction: rtl;)Pass Layout of munderover (writing-mode: horizontal-tb; direction: rtl;)diff --git a/Tests/LibWeb/Text/input/css/rtl-atomic-inline-box-edges.html b/Tests/LibWeb/Text/input/css/rtl-atomic-inline-box-edges.htmlnew file mode 100644index 00000000000..8397ddaf47c--- /dev/null+++ b/Tests/LibWeb/Text/input/css/rtl-atomic-inline-box-edges.html@@ -0,0 +1,97 @@+<!doctype html>+<style>+ @font-face { font-family: Ahem; src: url("../../../Ref/data/fonts/Ahem.ttf"); }+ .line { width: 240px; font: 0/0 Ahem; direction: rtl; }+ .box { display: inline-block; width: 50px; height: 20px; }+</style>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ await document.fonts.load("20px Ahem");+ for (const [name, extra, nested, spaced, wraps] of [+ ["plain", "", false, false, false],+ ["own edges", "padding-left:3px; padding-right:7px; border-left:2px solid; border-right:4px solid; margin-left:5px; margin-right:9px", false, false, false],+ ["negative margin", "margin-left:-5px; margin-right:9px", false, false, false],+ ["parent edges", "", true, false, false],+ ["spaces", "", false, true, false],+ ["wrapped", "", false, false, true],+ ["wrapped parent", "", true, false, true],+ ]) {+ const line = document.createElement("div");+ line.className = "line";+ if (wraps) line.style.width = "140px";+ else line.style.whiteSpace = "nowrap";+ if (spaced) line.style.fontSize = "20px";+ const parent = nested ? line.appendChild(document.createElement("span")) : line;+ if (nested) parent.style.cssText = "padding-left:11px; padding-right:23px; border-left:2px solid; border-right:4px solid; margin-left:3px; margin-right:5px";+ const children = [];+ for (let i = 0; i < 3; ++i) {+ if (spaced && i) parent.append(" ");+ const box = document.createElement("span");+ box.className = "box";+ box.style.cssText = extra;+ children.push(box);+ parent.append(box);+ }+ document.body.append(line);+ const start = line.getBoundingClientRect();+ println(`${name}: ${children.map(c => { const r = c.getBoundingClientRect(); return `${Math.round(r.left - start.left)},${Math.round(r.top - start.top)}`; }).join("; ")}`);+ line.remove();+ }+ const dynamic = document.createElement("div");+ dynamic.className = "line";+ dynamic.style.direction = "ltr";+ dynamic.innerHTML = '<span class="box"></span><span class="box"></span><span class="box"></span>';+ document.body.append(dynamic);+ const printDynamic = label => {+ const start = dynamic.getBoundingClientRect().left;+ println(`${label}: ${[...dynamic.children].map(c => c.getBoundingClientRect().left - start).join(",")}`);+ };+ printDynamic("initial ltr");+ dynamic.style.direction = "rtl";+ printDynamic("changed to rtl");+ dynamic.append(dynamic.firstElementChild.cloneNode());+ printDynamic("appended rtl child");+ dynamic.lastElementChild.remove();+ dynamic.style.direction = "ltr";+ printDynamic("changed back to ltr");+ dynamic.remove();++ for (const [name, direction, bidi] of [+ ["HTML direction", "rtl", "normal"],+ ["plaintext", "rtl", "plaintext"],+ ["LTR override", "ltr", "bidi-override"],+ ]) {+ const line = document.createElement("div");+ line.style.cssText = `width:240px; font-size:0; unicode-bidi:${bidi}`;+ line.dir = direction;+ line.innerHTML = '<span class="box"></span><span class="box"></span><span class="box"></span>';+ document.body.append(line);+ const order = [...line.children].map((e, index) => ({ index, x: e.getBoundingClientRect().x })).sort((a, b) => a.x - b.x);+ println(`${name}: ${order.map(e => e.index).join(",")}`);+ line.remove();+ }++ for (const mode of ["vertical-rl", "vertical-lr", "sideways-rl", "sideways-lr"]) {+ for (const orientation of ["mixed", "upright"]) {+ const line = document.createElement("div");+ line.style.cssText = `direction:rtl; writing-mode:${mode}; text-orientation:${orientation}; inline-size:240px; font-size:0`;+ line.innerHTML = '<span></span><span></span><span></span>';+ for (const child of line.children)+ child.style.cssText = "display:inline-block; inline-size:50px; block-size:20px";+ document.body.append(line);+ const start = line.getBoundingClientRect().top;+ println(`${mode}, ${orientation}: ${[...line.children].map(c => c.getBoundingClientRect().top - start).join(",")}`);+ line.remove();+ }+ }++ const mixed = document.createElement("div");+ mixed.style.cssText = "direction:rtl; width:240px";+ mixed.innerHTML = '<span>A</span><span class="box"></span><span>B</span>';+ document.body.append(mixed);+ const order = [...mixed.children].map((e, index) => ({ index, x: e.getBoundingClientRect().x })).sort((a, b) => a.x - b.x);+ println(`Latin text around atomic box: ${order.map(e => e.index).join(",")}`);+ mixed.remove();+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/rtl-atomic-inline-justification.html b/Tests/LibWeb/Text/input/css/rtl-atomic-inline-justification.htmlnew file mode 100644index 00000000000..c0458bae353--- /dev/null+++ b/Tests/LibWeb/Text/input/css/rtl-atomic-inline-justification.html@@ -0,0 +1,34 @@+<!doctype html>+<style>+ @font-face { font-family: Ahem; src: url("../../../Ref/data/fonts/Ahem.ttf"); }+</style>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ await document.fonts.load("20px Ahem");+ for (const direction of ["ltr", "rtl"]) {+ for (const alignment of ["start", "justify"]) {+ for (const width of [200, 280]) {+ for (const nested of [false, true]) {+ const line = document.createElement("div");+ line.style.cssText = `width:${width}px; font:20px/20px Ahem; direction:${direction}; text-align:${alignment}`;+ const parent = nested ? line.appendChild(document.createElement("span")) : line;+ const count = width === 200 ? 3 : 4;+ for (let i = 0; i < count; ++i) {+ if (i) parent.append(" ");+ const box = document.createElement("span");+ box.style.cssText = "display:inline-block; width:60px; height:20px";+ parent.append(box);+ }+ document.body.append(line);+ const origin = line.getBoundingClientRect();+ const boxes = [...parent.children].map(child => child.getBoundingClientRect());+ const positions = boxes.slice(0, -1).map(box => box.left - origin.left);+ println(`${direction} ${alignment} ${width} ${nested ? "nested" : "direct"}: ${positions.join(",")}; wrapped=${boxes.at(-1).top > boxes[0].top}`);+ line.remove();+ }+ }+ }+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/rtl-atomic-inline-order.html b/Tests/LibWeb/Text/input/css/rtl-atomic-inline-order.htmlnew file mode 100644index 00000000000..79a808b66f4--- /dev/null+++ b/Tests/LibWeb/Text/input/css/rtl-atomic-inline-order.html@@ -0,0 +1,33 @@+<!doctype html>+<style>+ .scroller { width: 220px; height: 140px; border: 4px solid; overflow: auto; white-space: nowrap; font-size: 0; scrollbar-width: none; }+ .atomic { display: inline-block; height: 100px; font-size: 20px; }+</style>+<script src="../include.js"></script>+<script>+ test(() => {+ for (const direction of ["ltr", "rtl"]) {+ for (const nested of [false, true]) {+ const scroller = document.createElement("div");+ scroller.className = "scroller";+ scroller.dir = direction;+ const children = [80, 500, 300].map((width, index) => {+ const box = document.createElement("span");+ box.className = "atomic";+ box.style.width = `${width}px`;+ box.textContent = String.fromCharCode(65 + index);+ return box;+ });+ const parent = nested ? scroller.appendChild(document.createElement("span")) : scroller;+ parent.append(...children);+ document.body.append(scroller);+ for (const scroll of [0, direction === "rtl" ? -100 : 100]) {+ scroller.scrollLeft = scroll;+ const start = scroller.getBoundingClientRect().left + scroller.clientLeft;+ println(`${direction}, nested=${nested}, scroll=${scroll}: ${children.map(c => c.getBoundingClientRect().left - start).join(", ")}; width=${scroller.scrollWidth}`);+ }+ scroller.remove();+ }+ }+ });+</script>