From 1f6bcc6f51d87232c7f725219afff646aeea21d2 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 09:25:34 +0100 Subject: [PATCH 01/23] Enhancements for Acid2 --- CHANGELOG.md | 14 ++ src/AngleSharp.Renderer.Docs/package.json | 2 +- .../Acid2RegressionTests.cs | 161 ++++++++++++ .../CaseRegressionTests.cs | 9 +- .../HtmlRenderer.Canvas.cs | 2 +- .../HtmlRenderer.Columns.cs | 4 +- .../HtmlRenderer.Frames.cs | 7 +- .../HtmlRenderer.Incremental.cs | 11 +- .../HtmlRenderer.Inline.cs | 33 ++- .../HtmlRenderer.Sticky.cs | 2 +- .../HtmlRenderer.Tables.cs | 10 +- .../HtmlRenderer.WritingModes.cs | 8 +- src/AngleSharp.Renderer/HtmlRenderer.cs | 234 ++++++++++++++---- src/AngleSharp.Renderer/MarginStrut.cs | 33 +++ src/Directory.Build.props | 2 +- 15 files changed, 444 insertions(+), 88 deletions(-) create mode 100644 src/AngleSharp.Renderer.Tests/Acid2RegressionTests.cs create mode 100644 src/AngleSharp.Renderer/MarginStrut.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index af40eae..927b03b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,17 @@ +# 0.12.1 + +Released on tbd. + +- Fixed adjoining vertical margins collapsing pairwise instead of all together, e.g. those of an empty block with a negative margin inside (75px and -72px with 48px before them are 3px, not 48px) +- Fixed the bottom margin of a block being left out before inline content following it, and before a float or an absolutely positioned box placed after it +- Fixed `min-height` not winning over `max-height` +- Fixed `position: relative` with only `bottom` or `right` not moving the box +- Fixed `background-attachment: fixed` being ignored: such a background is positioned in the viewport, where it stays while the page scrolls +- Fixed atomic inlines (e.g. an image overflowing a block of no height) being painted below the floats they overlap, as all inline content paints above the floats +- Fixed the background showing through where two border sides of different colors meet on a diagonal +- Fixed `data:` images whose base64 is percent-encoded (e.g. `%2F` for `/`) not being shown +- Added `object` elements showing an image instead of their fallback content + # 0.12.0 Released on Wednesday, November 18 2026. diff --git a/src/AngleSharp.Renderer.Docs/package.json b/src/AngleSharp.Renderer.Docs/package.json index 96acd0e..ff7ac87 100644 --- a/src/AngleSharp.Renderer.Docs/package.json +++ b/src/AngleSharp.Renderer.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/renderer", - "version": "0.12.0", + "version": "0.12.1", "preview": true, "description": "The doclet for the AngleSharp.Renderer documentation.", "keywords": [ diff --git a/src/AngleSharp.Renderer.Tests/Acid2RegressionTests.cs b/src/AngleSharp.Renderer.Tests/Acid2RegressionTests.cs new file mode 100644 index 0000000..b4778ca --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/Acid2RegressionTests.cs @@ -0,0 +1,161 @@ +namespace AngleSharp.Renderer.Tests; + +using AngleSharp; +using AngleSharp.Css; +using AngleSharp.Dom; +using AngleSharp.Renderer; +using AngleSharp.Renderer.Rendering; + +/// +/// Reduced versions of what the Acid2 test (acid2.acidtests.org) showed to differ from its +/// reference rendering, compared with the boxes Chromium lays out. +/// +public sealed class Acid2RegressionTests +{ + private static readonly DefaultRenderDevice Device = new() { ViewPortWidth = 800, ViewPortHeight = 600, FontSize = 16 }; + + // a 1x1 yellow PNG, its base64 percent-encoded as Acid2 has it + private const string YellowPixel = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4%2F58BAAT%2FAf9jgNErAAAAAElFTkSuQmCC"; + + [Fact] + public async Task MinHeight_WinsOverMaxHeight() + { + // the scalp: max-height is applied first, then min-height (CSS 2.1 §10.7) + var document = await OpenAsync(""" +
+
+ """); + + Assert.Equal(12f, Rect(document, "fixed").Height, precision: 1); + Assert.Equal(12f, Rect(document, "flow").Height, precision: 1); + } + + [Fact] + public async Task MarginsOfAnEmptyBlock_CollapseWithAllAdjoiningOnes() + { + // 48, 75 and 75 with the -72 of the empty child collapse to 75 - 72, not to 48 or 75 + var document = await OpenAsync(""" +
+
+ + """); + + Assert.Equal(15f, Rect(document, "empty").Y, precision: 1); + Assert.Equal(15f, Rect(document, "next").Y, precision: 1); + } + + [Fact] + public async Task ClearedBlock_IsAtTheBottomOfTheFloat() + { + var document = await OpenAsync(""" +
+
+
+
+ """); + + // the float is at 12 + 48 - 24 and ends 12px above its border box + Assert.Equal(72f, Rect(document, "cleared").Y, precision: 1); + } + + [Fact] + public async Task FloatAfterAnAbsoluteBox_IsBelowTheMarginOfTheBlockBefore() + { + var document = await OpenAsync(""" +
+
+
+ """); + + Assert.Equal(36f, Rect(document, "float").Y, precision: 1); + } + + [Fact] + public async Task RelativeBox_MovesByItsBottomWithoutATop() + { + var document = await OpenAsync(""" +
+
+ """); + + Assert.Equal(22f, Rect(document, "moved").Y, precision: 1); + Assert.Equal(-5f, Rect(document, "moved").X, precision: 1); + } + + [Fact] + public async Task InlineContentAfterABlock_IsBelowItsBottomMargin() + { + var document = await OpenAsync(""" +
text x
+
just text
+
a
+ """); + + Assert.Equal(30f, Rect(document, "span").Y, precision: 1); + Assert.True(Rect(document, "text").Height > 30f); + Assert.Equal(Rect(document, "positioned").Y + 30f, Rect(document, "absolute").Y, precision: 1); + } + + [Fact] + public async Task ObjectWithAnImage_IsReplacedByIt() + { + var document = await OpenAsync($$""" + ERROR + """); + + // the image takes the place of its fallback content, which the unknown type shows + Assert.Equal(1f, Rect(document, "image").Width, precision: 1); + Assert.Equal(1f, Rect(document, "image").Height, precision: 1); + Assert.DoesNotContain(new HtmlRenderer().BuildDisplayList(document, Device).Commands, command => command.GetType().Name.Contains("Text")); + } + + [Fact] + public async Task FixedBackground_IsPositionedInTheViewport() + { + var document = await OpenAsync($$""" +
+
+ """); + var commands = new HtmlRenderer().BuildDisplayList(document, Device).Commands.ToList(); + var anchor = commands.FindIndex(command => command is PushViewportAnchorCommand); + + // clipped to the box, which moves with the page, while the image stays in the viewport + Assert.True(anchor > 0); + Assert.IsType(commands[anchor - 1]); + var image = Assert.IsType(commands[anchor + 1]); + Assert.Equal(new RenderRect(0f, 0f, 800f, 600f), image.Rect); + Assert.IsType(commands[anchor + 2]); + } + + [Fact] + public async Task AtomicInlineOverlappingAFloat_PaintsAboveIt() + { + // the eyes: the line of a block of no height paints above the float after it (Appendix E) + var document = await OpenAsync(""" +
+
+ """); + var fills = new HtmlRenderer().BuildDisplayList(document, Device).Commands.OfType().ToList(); + var inline = fills.FindIndex(fill => fill.Paint is RenderColorPaint { Color: { R: 0, B: 255 } }); + var floated = fills.FindIndex(fill => fill.Paint is RenderColorPaint { Color: { R: 255, G: 0 } }); + + Assert.True(floated >= 0 && inline > floated); + } + + private static RenderRect Rect(IDocument document, string id) + { + var rect = document.GetElementById(id)!.GetBoundingClientRect(); + return new RenderRect((float)rect.Left, (float)rect.Top, (float)rect.Width, (float)rect.Height); + } + + private static async Task OpenAsync(string body) + { + var context = BrowsingContext.New(Configuration.Default.WithCss().WithRenderDevice(Device)); + var document = await context.OpenAsync(request => request.Content($$""" + + {{body}} + """)); + context.GetDomHarness(); + return document; + } +} diff --git a/src/AngleSharp.Renderer.Tests/CaseRegressionTests.cs b/src/AngleSharp.Renderer.Tests/CaseRegressionTests.cs index 377a77e..0942281 100644 --- a/src/AngleSharp.Renderer.Tests/CaseRegressionTests.cs +++ b/src/AngleSharp.Renderer.Tests/CaseRegressionTests.cs @@ -333,9 +333,14 @@ public async Task Border_WithDifferentColors_MeetsOnTheDiagonals() // the region of the top edge: its sides run through the outer and inner corners var top = regions[0].Points; + var innerTopLeft = top.Single(point => point.X > 0f && point.X < 50f && point.Y > 0f); Assert.Equal(4f / 6f, (0f - top[0].Y) / (0f - top[0].X), precision: 3); - Assert.Equal(4f / 6f, top[3].Y / top[3].X, precision: 3); - Assert.True(top[0].X < 0f && top[0].Y < 0f && top[3].X > 6f && top[3].Y > 4f); + Assert.Equal(4f / 6f, innerTopLeft.Y / innerTopLeft.X, precision: 3); + Assert.True(top[0].X < 0f && top[0].Y < 0f && innerTopLeft.X > 6f && innerTopLeft.Y > 4f); + // and it reaches under the corners of the sides painted after it, so that their diagonals + // are anti-aliased against its color rather than what is behind the border + Assert.Contains(top, point => point.X < 0f && point.Y > 4f); + Assert.Contains(top, point => point.X > 112f && point.Y > 4f); } [Theory] diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Canvas.cs b/src/AngleSharp.Renderer/HtmlRenderer.Canvas.cs index b0d30e2..e9dfdf8 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Canvas.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Canvas.cs @@ -30,7 +30,7 @@ element is not IPseudoElement && /// private static bool HidesChildren(IElement element) => element is not IPseudoElement && - (string.Equals(element.LocalName, "svg", StringComparison.OrdinalIgnoreCase) || IsCanvas(element)); + (string.Equals(element.LocalName, "svg", StringComparison.OrdinalIgnoreCase) || IsCanvas(element) || IsImageObject(element)); private static bool TryResolveCanvas(ElementRenderNode node, Dictionary styleMap, float containingWidth, float x, float y, out RenderedImage? image, out RenderRect rect, out RenderRect? clipRect, (float Width, float Height)? usedSize = null) { diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Columns.cs b/src/AngleSharp.Renderer/HtmlRenderer.Columns.cs index f50b337..57bbfae 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Columns.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Columns.cs @@ -278,7 +278,7 @@ private static float LayoutMultiColumnChildren( cursorY += LayoutColumnSet(set, columns, styleMap, contentX, cursorY, float.NaN, float.NaN, specifiedContentHeight, ref textIndentConsumed, textStyle, context, displayList, positionedContainingX, positionedContainingY, positionedContainingWidth, positionedContainingHeight); set = []; - var previousMarginBottom = 0f; + var previousMarginBottom = MarginStrut.Zero; var suppressTopMargin = false; LayoutNode( @@ -370,7 +370,7 @@ private static float LayoutColumnSet( try { - var previousBlockMarginBottom = 0f; + var previousBlockMarginBottom = MarginStrut.Zero; var suppressNextBlockTopMargin = false; var floats = new FloatArea(); diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs b/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs index 5578ec9..781df15 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs @@ -192,7 +192,12 @@ private RenderedFrame CreateFrame(IDocument document, LayoutSnapshot snapshot, D ? styleMap.GetValueOrDefault("position")?.Trim() : null; - // boxes attached to the viewport do not move with the page + // boxes attached to the viewport do not move with the page, nor do fixed backgrounds + if (styleMap is not null && styleMap.TryGetValue("background-attachment", out var attachment) && attachment.Contains("fixed", StringComparison.OrdinalIgnoreCase)) + { + isScrollShiftable = false; + } + if (string.Equals(position, "fixed", StringComparison.OrdinalIgnoreCase) || string.Equals(position, "sticky", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs b/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs index 610dac3..34583ef 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs @@ -70,7 +70,7 @@ private sealed record LayoutEntry( bool HasBox, bool HasStaticPosition = true, bool IsInFlow = false, - float PreviousBlockMarginBottom = 0f, + MarginStrut PreviousBlockMarginBottom = default, bool SuppressNextBlockTopMargin = false, FlowResult? Result = null, ItemLayout? Item = null, @@ -112,7 +112,7 @@ private static float GetCollapsedTopMargin(ElementRenderNode node, float contain return box.BorderWidth.Top <= 0f && paddingTop <= 0f && !EstablishesBlockFormattingContext(styleMap, false, false, false, false) && TryGetFirstCollapsibleChildTopMargin(node, containingWidth, context, out var firstChildTopMargin) - ? CollapseMargins(marginTop, firstChildTopMargin) + ? MarginStrut.From(marginTop).Append(firstChildTopMargin).Value : marginTop; } @@ -202,7 +202,7 @@ private static void RecordDeferredMainSize(ElementRenderNode node, float mainSiz /// What an in-flow block left for the boxes after it: where they start, the margin they /// collapse with, and if it left no floats reaching down to them. /// - private sealed record FlowResult(float CursorY, float PreviousBlockMarginBottom, bool SuppressNextBlockTopMargin, bool TextIndentConsumed, bool LeftNoFloats); + private sealed record FlowResult(float CursorY, MarginStrut PreviousBlockMarginBottom, bool SuppressNextBlockTopMargin, bool TextIndentConsumed, bool LeftNoFloats); /// A child of a flow painted after its in-flow content (positioned or z-indexed). private sealed record RaisedChild(IElement Element, int ZIndex, RenderCommand First, int Count); @@ -1040,7 +1040,7 @@ private static bool IsInSubtree(IElement root, IElement element) => // the properties that change what a box paints of its own, but not where anything is private static readonly HashSet s_decorationProperties = new(StringComparer.Ordinal) { - "background-color", "background-image", "background-position", "background-size", "background-repeat", "background-origin", + "background-color", "background-image", "background-position", "background-size", "background-repeat", "background-origin", "background-attachment", "background-blend-mode", "background-clip", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "outline-color", "outline-style", "outline-width", "outline-offset", "box-shadow", }; @@ -3061,7 +3061,8 @@ private bool TryLayOutAgain(IWindow window, IElement root, out bool escalates) // would in a full layout if it is no stacking context or clip (a new one, as the root // of one there was not laid out on its own) if (!IsRaisedInFlow(styleMap) && !IsStickyPositioned(styleMap) && - _context.HoistCandidates.Any(candidate => ReferenceEquals(candidate.DisplayList, displayList) && root.Contains(candidate.Element) && + // (inline content lifted above a float leaves no entry to start from, see PaintOrder) + _context.HoistCandidates.Any(candidate => candidate.Z != InlineContentLayer && ReferenceEquals(candidate.DisplayList, displayList) && root.Contains(candidate.Element) && displayList.Commands.IndexOf(candidate.First) is >= 0 and var position && !HasOpenScopeBefore(displayList, position))) { _context.HoistCandidates.Clear(); diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs b/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs index f3d11aa..d7594f2 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs @@ -34,7 +34,7 @@ private static void LayoutFlowChildren( float contentY, float contentWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -53,7 +53,7 @@ private static void LayoutFlowChildren( var runHasInlineContent = false; var paintOrder = new PaintOrder(); - void FlushRun(ref float cursorY, ref float previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed) + void FlushRun(ref float cursorY, ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed) { if (run.Count == 0) { @@ -903,7 +903,7 @@ private static void LayoutInlineFormattingContext( float contentX, float contentWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -929,7 +929,9 @@ private static void LayoutInlineFormattingContext( } var pieces = collector.Pieces; - var pendingBlockMargin = 0f; + // the bottom margin of the block before is still to come: the first line box (or a float + // or a block before it) is below it + var pendingBlockMargin = previousBlockMarginBottom; if (pieces.Count == 0) { @@ -991,7 +993,7 @@ float MeasureFloatWidth(InlinePiece piece) void PlaceFloat(InlinePiece piece) { var floatCursorY = lineTop + pendingBlockMargin; - var floatPreviousMarginBottom = 0f; + var floatPreviousMarginBottom = MarginStrut.Zero; var floatSuppressTopMargin = false; var floatTextIndentConsumed = false; var rangeStart = displayList.Commands.Count; @@ -1127,12 +1129,12 @@ void PlaceFloat(InlinePiece piece) if (!hasLineBox) { - LayoutOutOfFlowPieces(linePieces, false, 0f, contentX, lineTop, contentWidth, context, displayList, maxY, containingHeight, positionedContainingX, positionedContainingY, positionedContainingWidth, positionedContainingHeight, paintOrder); + LayoutOutOfFlowPieces(linePieces, false, 0f, contentX, lineTop + pendingBlockMargin, contentWidth, context, displayList, maxY, containingHeight, positionedContainingX, positionedContainingY, positionedContainingWidth, positionedContainingHeight, paintOrder); continue; } lineTop += pendingBlockMargin; - pendingBlockMargin = 0f; + pendingBlockMargin = MarginStrut.Zero; var lineHeight = EmitLine( linePieces, @@ -1986,7 +1988,7 @@ visualOrder[runEnd].Kind is InlinePieceKind.Text or InlinePieceKind.Space && } + (piece.Box?.RelativeY ?? 0f); var atomicCursorY = marginBoxTop; - var atomicPreviousMarginBottom = 0f; + var atomicPreviousMarginBottom = MarginStrut.Zero; var atomicSuppressTopMargin = false; var atomicFloats = new FloatArea(); var atomicTextIndentConsumed = false; @@ -2018,6 +2020,12 @@ visualOrder[runEnd].Kind is InlinePieceKind.Text or InlinePieceKind.Space && { negativeZIndexRanges.Add((rangeStart, displayList.Commands.Count - rangeStart)); } + else if (displayList.Commands.Count > rangeStart) + { + // painted above the floats of the flow it is in, where it overlaps one of them + context.HoistCandidates.Add(new HoistCandidate(displayList, InlineContentLayer, displayList.Commands[rangeStart], displayList.Commands.Count - rangeStart, piece.Element!.Ref, + new RenderRect(piece.X, marginBoxTop, measurement.BorderBoxWidth, measurement.OuterHeight))); + } } index++; @@ -2590,7 +2598,7 @@ private static void LayoutOutOfFlowPieces( var rangeStart = displayList.Commands.Count; var staticCursorY = lineTop; - var previousMarginBottom = 0f; + var previousMarginBottom = MarginStrut.Zero; var suppressTopMargin = false; var localFloats = new FloatArea(); var textIndentConsumed = false; @@ -2922,7 +2930,7 @@ private static (ElementLayoutMetrics? Metrics, float? LastBaselineY, float? Firs try { var cursorY = 0f; - var previousMarginBottom = 0f; + var previousMarginBottom = MarginStrut.Zero; var suppressTopMargin = false; var localFloats = new FloatArea(); var textIndentConsumed = false; @@ -3135,9 +3143,10 @@ private static bool TryResolveReplacedContentWidth(ElementRenderNode element, Di /// private static float ClampToMinMaxHeight(Dictionary styleMap, float contentHeight, float heightReference, float verticalExtras) { - contentHeight = Math.Max(contentHeight, ResolveAuthoredDimension(styleMap, "min-height", heightReference, 0f, verticalExtras)); + // max-height first, then min-height, which wins over it (CSS 2.1, 10.7) var maxHeight = ResolveAuthoredDimension(styleMap, "max-height", heightReference, float.NaN, verticalExtras); - return float.IsNaN(maxHeight) ? contentHeight : Math.Min(contentHeight, maxHeight); + contentHeight = float.IsNaN(maxHeight) ? contentHeight : Math.Min(contentHeight, maxHeight); + return Math.Max(contentHeight, ResolveAuthoredDimension(styleMap, "min-height", heightReference, 0f, verticalExtras)); } private static float ClampToMinMaxWidth(Dictionary styleMap, float contentWidth, float containingWidth, float horizontalExtras) diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Sticky.cs b/src/AngleSharp.Renderer/HtmlRenderer.Sticky.cs index db86f9e..f0acf4b 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Sticky.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Sticky.cs @@ -122,7 +122,7 @@ private static void LayoutStickyAwareElement( float containingY, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Tables.cs b/src/AngleSharp.Renderer/HtmlRenderer.Tables.cs index d2fcf3f..41729a7 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Tables.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Tables.cs @@ -959,7 +959,7 @@ private static void LayoutTable( float containingX, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, RenderTextStyle inheritedTextStyle, @@ -1353,7 +1353,7 @@ float SpanHeight(TableCellInfo cell) box = box with { BorderRadius = ResolveBorderRadii(styleMap, borderBoxWidth, borderBoxHeight) }; var decorations = textStyle.IsHidden ? new DisplayList() : displayList; var effects = OpenElementEffectScopes(displayList, decorations, styleMap, tableNode.Ref, borderBoxX, borderBoxY, borderBoxWidth, borderBoxHeight, border, padding, box.BorderRadius, textStyle.FontSize); - PaintBoxBackground(decorations, styleMap, box, borderBoxX, borderBoxY, borderBoxWidth, borderBoxHeight, border, padding); + PaintBoxBackground(decorations, styleMap, box, borderBoxX, borderBoxY, borderBoxWidth, borderBoxHeight, border, padding, GetViewportArea(context)); PaintBoxShadows(decorations, box.BoxShadows, borderBoxX, borderBoxY, borderBoxWidth, borderBoxHeight, box.BorderRadius); PaintBoxBorder(decorations, styleMap, tableNode.Ref, box, borderBoxX, borderBoxY, borderBoxWidth, borderBoxHeight); PaintOutline(decorations, styleMap, borderBoxX, borderBoxY, borderBoxWidth, borderBoxHeight); @@ -1406,7 +1406,7 @@ float SpanHeight(TableCellInfo cell) }; var cellCursorY = cellY; - var cellPreviousMarginBottom = 0f; + var cellPreviousMarginBottom = MarginStrut.Zero; var cellSuppressTopMargin = false; var cellTextIndentConsumed = false; @@ -1529,7 +1529,7 @@ private static void LayoutPositionedTable(ElementRenderNode node, Dictionary @@ -158,7 +158,7 @@ private static float ResolveOrthogonalInlineSize(ElementRenderNode node, Diction private static float LayoutOrthogonalFlowContent(IReadOnlyList children, RenderTextStyle flowStyle, float inlineSize, LayoutContext context, DisplayList displayList, out List stickyBoxes) { var cursorY = 0f; - var previousMarginBottom = 0f; + var previousMarginBottom = MarginStrut.Zero; var suppressTopMargin = false; var textIndentConsumed = false; var floats = new FloatArea(); @@ -225,7 +225,7 @@ private static float LayoutContainerInOwnSystem(ElementRenderNode node, RenderTe try { var cursorY = 0f; - var previousMarginBottom = 0f; + var previousMarginBottom = MarginStrut.Zero; var suppressTopMargin = false; var textIndentConsumed = false; diff --git a/src/AngleSharp.Renderer/HtmlRenderer.cs b/src/AngleSharp.Renderer/HtmlRenderer.cs index ac7e90a..b24da4a 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.cs @@ -270,7 +270,11 @@ private sealed record class LayoutContext( public List HoistCandidates { get; } = []; } - private readonly record struct HoistCandidate(DisplayList DisplayList, int Z, RenderCommand First, int Count, IElement Element); + private readonly record struct HoistCandidate(DisplayList DisplayList, int Z, RenderCommand First, int Count, IElement Element, RenderRect? Bounds = null); + + // the "z-index" of the atomic inlines a flow paints above its floats (see PaintOrder), as all + // inline content paints above the floats (CSS 2.2 Appendix E), which matters where they overlap + private const int InlineContentLayer = int.MinValue + 1; /// /// The lines a box with `-webkit-line-clamp` has left for its content. Every line laid out @@ -735,7 +739,7 @@ private static void LayoutHeldBackBoxes(List boxes, float foreach (var deferred in boxes) { var deferredCursorY = deferred.CursorY; - var deferredPreviousBlockMarginBottom = 0f; + var deferredPreviousBlockMarginBottom = MarginStrut.Zero; var deferredSuppressNextBlockTopMargin = false; var deferredTextIndentConsumed = true; @@ -1019,7 +1023,7 @@ private static DisplayList BuildDisplayListCore(IDocument document, RenderViewpo var rootLineHeight = isNormalLineHeight ? ResolveNormalLineHeight(new RenderFont(context.FontFamily, context.FontSize, 400f, false, 0f, context.Fonts), context) : context.LineHeightMultiplier; var textStyle = new RenderTextStyle(context.FontSize, context.TextColor, context.FontFamily, rootLineHeight, 400f, false, false, false, context.TextColor, global::AngleSharp.Renderer.Rendering.RenderTextDecorationStyle.Solid, TextAlign.Left, 0f, 0f, 0f, [], WhiteSpaceMode.Normal, WordBreakMode.Normal, OverflowWrapMode.Normal, TextOverflowMode.Clip, 0, TextDirection.Ltr) with { IsNormalLineHeight = isNormalLineHeight }; var cursorY = contentY; - var previousBlockMarginBottom = 0f; + var previousBlockMarginBottom = MarginStrut.Zero; var suppressNextBlockTopMargin = false; var floats = new FloatArea(); var textIndentConsumed = false; @@ -1107,7 +1111,7 @@ private static DisplayList BuildDisplayListCore(IDocument document, RenderViewpo { var canvasBuffer = new DisplayList(); var canvasHeight = Math.Max(viewport.Height + surfaceExtraHeight + scrollOffsetY, cursorY + scrollOffsetY); - PaintBoxBackground(canvasBuffer, propagated.StyleMap, propagated.Box, 0f, -scrollOffsetY, viewport.Width, canvasHeight, default, default); + PaintBoxBackground(canvasBuffer, propagated.StyleMap, propagated.Box, 0f, -scrollOffsetY, viewport.Width, canvasHeight, default, default, GetViewportArea(context)); displayList.InsertRange(1, canvasBuffer.Commands); } @@ -1221,7 +1225,7 @@ private static void LayoutNode( float containingY, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -1278,7 +1282,7 @@ private static void LayoutElement( float containingY, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -1544,13 +1548,13 @@ private static void LayoutElement( // A box with its own formatting context never collapses margins with its children. var collapseWithFirstChild = borderTop <= 0f && paddingTop <= 0f && !establishesContext; - var effectiveMarginTop = marginTop; + var effectiveMarginTop = MarginStrut.From(marginTop); var collapsesWithFirstChild = false; if (collapseWithFirstChild && TryGetFirstCollapsibleChildTopMargin(node, flowContainingWidth, context, out var firstChildTopMargin)) { - effectiveMarginTop = topMarginAbsorbed ? 0f : CollapseMargins(marginTop, firstChildTopMargin); + effectiveMarginTop = topMarginAbsorbed ? MarginStrut.Zero : MarginStrut.From(marginTop).Append(firstChildTopMargin); collapsesWithFirstChild = true; } @@ -1684,7 +1688,9 @@ private static void LayoutElement( marginRight = authoredMarginRight; } - var collapsedMarginTop = (isAbsolute || isFixed) ? 0f : CollapseMargins(previousBlockMarginBottom, effectiveMarginTop); + // the static position of what is out of flow is below the margins before it, which still + // collapse with those after it + var collapsedMarginTop = (isAbsolute || isFixed) ? previousBlockMarginBottom.Value : previousBlockMarginBottom.Append(effectiveMarginTop).Value; var flowBorderBoxX = flowContainingX + marginLeft; @@ -1730,6 +1736,9 @@ private static void LayoutElement( topOffset = 0f; } + // a relatively positioned box moves by `left` and `top`, or else against `right` and `bottom` + var relativeOffsetX = !float.IsNaN(cssLeftOffset) ? cssLeftOffset : !float.IsNaN(cssRightOffset) ? -cssRightOffset : 0f; + var relativeOffsetY = !float.IsNaN(cssTopOffset) ? cssTopOffset : !float.IsNaN(cssBottomOffset) ? -cssBottomOffset : 0f; var absoluteContainingX = float.IsNaN(positionedContainingX) ? containingX : positionedContainingX; var absoluteContainingY = float.IsNaN(positionedContainingY) ? containingY : positionedContainingY; var absoluteContainingWidth = float.IsNaN(positionedContainingWidth) ? containingWidth : positionedContainingWidth; @@ -1743,14 +1752,14 @@ private static void LayoutElement( ? context.Padding + leftOffset + positionedMargins.Left : isAbsolute ? hasStaticX ? flowBorderBoxX + positionedMargins.Left : absoluteContainingX + leftOffset + positionedMargins.Left - : flowBorderBoxX + (isRelative ? leftOffset : 0f); + : flowBorderBoxX + (isRelative ? relativeOffsetX : 0f); // `position: sticky` is laid out at its natural position; its container shifts it once // its own box is known (see ResolveStickyBoxes). var borderBoxY = isFixed ? context.Padding + topOffset + positionedMargins.Top : isAbsolute ? hasStaticY ? flowBorderBoxY + positionedMargins.Top : absoluteContainingY + topOffset + positionedMargins.Top - : flowBorderBoxY + (isRelative ? topOffset : 0f); + : flowBorderBoxY + (isRelative ? relativeOffsetY : 0f); var contentX = borderBoxX + borderLeft + paddingLeft; var contentY = borderBoxY + borderTop + paddingTop; var verticalBorderAndPadding = borderTop + borderBottom + paddingTop + paddingBottom; @@ -1827,9 +1836,10 @@ private static void LayoutElement( var minimumContentHeightForPositioning = ResolveAuthoredDimension(styleMap, "min-height", heightReference, 0f, verticalBorderAndPadding); // an automatic height is only known once laid out (a min-height is no more than its lower bound) + var maximumContentHeightForPositioning = ResolveAuthoredDimension(styleMap, "max-height", heightReference, float.NaN, verticalBorderAndPadding); var positionedContentHeight = float.IsNaN(resolvedContentHeight) ? float.NaN - : Math.Max(resolvedContentHeight, minimumContentHeightForPositioning); + : Math.Max(float.IsNaN(maximumContentHeightForPositioning) ? resolvedContentHeight : Math.Min(resolvedContentHeight, maximumContentHeightForPositioning), minimumContentHeightForPositioning); var positionedBorderBoxWidth = borderLeft + paddingLeft + contentWidth + paddingRight + borderRight; var positionedBorderBoxHeight = float.IsNaN(positionedContentHeight) @@ -1934,12 +1944,12 @@ private static void LayoutElement( : formControlSpecifiedHeight; // limited like the box's final height below, e.g. by a `min-height` (centering the label in it) var formControlMaximumHeight = ResolveAuthoredDimension(styleMap, "max-height", heightReference, float.NaN, verticalBorderAndPadding); - formControlContentHeight = Math.Max(formControlContentHeight, minimumContentHeightForPositioning); - if (!float.IsNaN(formControlMaximumHeight) && float.IsNaN(forcedBorderBoxHeight)) { formControlContentHeight = Math.Min(formControlContentHeight, formControlMaximumHeight); } + + formControlContentHeight = Math.Max(formControlContentHeight, minimumContentHeightForPositioning); // `appearance: none` leaves a checkbox or radio as an ordinary box (e.g. one drawing // its check mark as a background image), without the native check painted over it. var hasNativeAppearance = formControlKind is not (FormControlKind.Checkbox or FormControlKind.Radio) || @@ -1953,7 +1963,7 @@ private static void LayoutElement( // A table cell's content is shifted within the cell by its `vertical-align`. var childCursorY = contentY + contentOffsetY; - var childPreviousBlockMarginBottom = 0f; + var childPreviousBlockMarginBottom = MarginStrut.Zero; var childSuppressNextBlockTopMargin = collapsesWithFirstChild; var childFloats = establishesContext ? new FloatArea() : floats; var negativeZIndexRanges = new List<(int StartIndex, int Count)>(); @@ -1987,7 +1997,7 @@ private static void LayoutElement( var marginBeforeFloat = previousBlockMarginBottom; var suppressBeforeContainer = suppressNextBlockTopMargin; - void PlaceFloatedContainer(ref float cursor, ref float previousMargin) + void PlaceFloatedContainer(ref float cursor, ref MarginStrut previousMargin) { floats.Add( flowBorderBoxX - marginLeft, @@ -2000,7 +2010,7 @@ void PlaceFloatedContainer(ref float cursor, ref float previousMargin) } // what is positioned takes no room in the flow either (as for any positioned box below) - void RestoreFlowAfterPositionedContainer(ref float cursor, ref float previousMargin, ref bool suppressTopMargin) + void RestoreFlowAfterPositionedContainer(ref float cursor, ref MarginStrut previousMargin, ref bool suppressTopMargin) { cursor = cursorBeforeFloat; previousMargin = marginBeforeFloat; @@ -2264,12 +2274,14 @@ void RestoreFlowAfterPositionedContainer(ref float cursor, ref float previousMar var contentHeight = float.IsNaN(specifiedContentHeight) ? autoContentHeight : specifiedContentHeight; var minimumContentHeight = ResolveAuthoredDimension(styleMap, "min-height", heightReference, 0f, verticalBorderAndPadding); var maximumContentHeight = ResolveAuthoredDimension(styleMap, "max-height", heightReference, float.NaN, verticalBorderAndPadding); - contentHeight = Math.Max(contentHeight, minimumContentHeight); + // max-height first, then min-height, which wins over it (CSS 2.1, 10.7) if (!float.IsNaN(maximumContentHeight) && float.IsNaN(forcedBorderBoxHeight)) { contentHeight = Math.Min(contentHeight, maximumContentHeight); } + contentHeight = Math.Max(contentHeight, minimumContentHeight); + var borderBoxWidth = borderLeft + paddingLeft + contentWidth + paddingRight + borderRight; var borderBoxHeight = borderTop + paddingTop + contentHeight + paddingBottom + borderBottom; var usedMarginLeft = marginLeft; @@ -2322,11 +2334,11 @@ void RestoreFlowAfterPositionedContainer(ref float cursor, ref float previousMar float.IsNaN(specifiedContentHeight) && !establishesContext; - var effectiveMarginBottom = marginBottom; + var effectiveMarginBottom = MarginStrut.From(marginBottom); if (canCollapseWithLastChild) { - effectiveMarginBottom = CollapseMargins(marginBottom, childPreviousBlockMarginBottom); + effectiveMarginBottom = effectiveMarginBottom.Append(childPreviousBlockMarginBottom); } RecordLayoutMetrics( @@ -2451,14 +2463,14 @@ void RestoreFlowAfterPositionedContainer(ref float cursor, ref float previousMar } else { - previousBlockMarginBottom = CollapseMargins(previousBlockMarginBottom, effectiveMarginTop, effectiveMarginBottom) + context.ParagraphSpacing; + previousBlockMarginBottom = WithParagraphSpacing(previousBlockMarginBottom.Append(effectiveMarginTop).Append(effectiveMarginBottom), context); } return; } cursorY = flowBorderBoxY + borderBoxHeight; - previousBlockMarginBottom = effectiveMarginBottom + context.ParagraphSpacing; + previousBlockMarginBottom = WithParagraphSpacing(effectiveMarginBottom, context); } /// @@ -2828,7 +2840,7 @@ private static void LayoutFlexContainer( float containingY, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -3329,7 +3341,7 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) var childContentHeight = Math.Max(0f, childHeight - childVerticalExtras); var childCursor = isRowDirection ? containingY + itemCrossPosition : containingY + itemOffset; var childBlockCursor = childCursor; - var childPreviousBottom = 0f; + var childPreviousBottom = MarginStrut.Zero; var childSuppressMargin = false; var childTextIndent = false; var itemFloats = new FloatArea(); @@ -3433,12 +3445,13 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) contentHeight = float.IsNaN(specifiedContentHeight) ? isRowDirection ? Math.Max(autoContentHeight, containerCrossSize) : autoContentHeight : specifiedContentHeight; - contentHeight = Math.Max(contentHeight, minimumContentHeight); if (!float.IsNaN(maximumContentHeight)) { contentHeight = Math.Min(contentHeight, maximumContentHeight); } + contentHeight = Math.Max(contentHeight, minimumContentHeight); + if (s_layoutCapture.Value is { Containers: { } containers }) { // what LayoutOutOfFlowChildren gives a child shown later (see FindLayoutRoot) @@ -3568,7 +3581,7 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) CloseElementEffectScopes(displayList, effects); cursorY = flowBorderBoxY + borderBoxHeight; - previousBlockMarginBottom = effectiveMarginBottom + context.ParagraphSpacing; + previousBlockMarginBottom = WithParagraphSpacing(effectiveMarginBottom, context); suppressNextBlockTopMargin = false; // laid out against the container's padding box (if it is a containing block), from where @@ -3588,7 +3601,7 @@ void LayoutOutOfFlowChildren(float usedContentHeight) childCursorY += alignItems == "center" ? freeSpace / 2f : freeSpace; } - var childPreviousBottom = 0f; + var childPreviousBottom = MarginStrut.Zero; var childSuppressMargin = false; var childTextIndent = false; var childRangeStart = displayList.Commands.Count; @@ -3686,7 +3699,7 @@ private static void LayoutGridContainer( float containingY, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -4229,7 +4242,7 @@ static float PlaceInGridArea(GridSelfAlignment alignment, float marginStart, flo } var childCursor = alignedCellY; - var childPreviousBlockMarginBottom = 0f; + var childPreviousBlockMarginBottom = MarginStrut.Zero; var childSuppressNextBlockTopMargin = false; var childFloats = new FloatArea(); var childTextIndentConsumed = false; @@ -4303,13 +4316,14 @@ EdgeSizes ResolveUsedGridMargins() // An authored height is the height; taller content overflows, as in a block. var resolvedGridContentHeight = float.IsNaN(containerHeight) ? gridContentHeight : containerHeight; - resolvedGridContentHeight = Math.Max(resolvedGridContentHeight, ResolveAuthoredDimension(styleMap, "min-height", containingWidth, 0f, gridVerticalBorderAndPadding)); var maximumGridContentHeight = ResolveAuthoredDimension(styleMap, "max-height", containingWidth, float.NaN, gridVerticalBorderAndPadding); if (!float.IsNaN(maximumGridContentHeight)) { resolvedGridContentHeight = Math.Min(resolvedGridContentHeight, maximumGridContentHeight); } + + resolvedGridContentHeight = Math.Max(resolvedGridContentHeight, ResolveAuthoredDimension(styleMap, "min-height", containingWidth, 0f, gridVerticalBorderAndPadding)); var borderBoxHeight = borderTop + paddingTop + resolvedGridContentHeight + paddingBottom + borderBottom; LayoutOutOfFlowChildren(); paintOrder.Apply(displayList); @@ -4397,7 +4411,7 @@ EdgeSizes ResolveUsedGridMargins() CloseElementEffectScopes(displayList, effects); cursorY = flowBorderBoxY + borderBoxHeight; - previousBlockMarginBottom = effectiveMarginBottom + context.ParagraphSpacing; + previousBlockMarginBottom = WithParagraphSpacing(effectiveMarginBottom, context); suppressNextBlockTopMargin = false; // Laid out against the grid area of their lines (CSS Grid 1 §9.1): a line left out (or @@ -4434,7 +4448,7 @@ void LayoutOutOfFlowChildren() var areaTop = GetLinePosition(rowStart, rowSizes, contentY + rowAlignment.Offset, resolvedRowGap + rowAlignment.Spacing) ?? paddingBoxY; var areaBottom = GetLinePosition(rowEnd, rowSizes, contentY + rowAlignment.Offset, resolvedRowGap + rowAlignment.Spacing) ?? paddingBoxY + paddingBoxHeight; var childCursorY = contentY; - var childPreviousBottom = 0f; + var childPreviousBottom = MarginStrut.Zero; var childSuppressMargin = false; var childTextIndent = false; var childRangeStart = displayList.Commands.Count; @@ -5465,7 +5479,7 @@ private static float MeasureGridItemHeight(ElementRenderNode element, float cont var displayList = new DisplayList(); var cursorY = 0f; - var previousBlockMarginBottom = 0f; + var previousBlockMarginBottom = MarginStrut.Zero; var suppressNextBlockTopMargin = false; var floats = new FloatArea(); var textIndentConsumed = false; @@ -5771,7 +5785,7 @@ private static void ResolveGridFractionTracks(List tracks, float /// clearance replaces. An empty box stays a separator wherever it ends up (as browsers do with /// floats to clear), with its own margins still collapsing through it into what follows. /// - private static void ApplyClearance(float clearance, float marginTop, bool isSelfCollapsing, ref float cursorY, ref float previousBlockMarginBottom, ref bool suppressNextBlockTopMargin) + private static void ApplyClearance(float clearance, float marginTop, bool isSelfCollapsing, ref float cursorY, ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin) { if (float.IsNaN(clearance)) { @@ -5779,7 +5793,7 @@ private static void ApplyClearance(float clearance, float marginTop, bool isSelf } var ownMargin = suppressNextBlockTopMargin ? 0f : marginTop; - var hypothetical = cursorY + CollapseMargins(previousBlockMarginBottom, ownMargin); + var hypothetical = cursorY + previousBlockMarginBottom.Append(ownMargin).Value; if (isSelfCollapsing) { @@ -5877,7 +5891,7 @@ private static void LayoutTextNode( float containingX, float containingWidth, ref float cursorY, - ref float previousBlockMarginBottom, + ref MarginStrut previousBlockMarginBottom, ref bool suppressNextBlockTopMargin, FloatArea floats, ref bool textIndentConsumed, @@ -5896,6 +5910,8 @@ private static void LayoutTextNode( return; } + // the line box is below the bottom margin of the block before it + cursorY += previousBlockMarginBottom; previousBlockMarginBottom = 0f; suppressNextBlockTopMargin = false; @@ -8037,6 +8053,7 @@ private static Dictionary CreateComputedStyleMap(ICssStyleDeclar AddIfPresent(map, "mask-origin", style.GetPropertyValue("mask-origin")); } AddIfPresent(map, "background-origin", style.GetPropertyValue("background-origin")); + AddIfPresent(map, "background-attachment", style.GetPropertyValue("background-attachment")); AddIfPresent(map, "background-blend-mode", style.GetPropertyValue("background-blend-mode")); AddIfPresent(map, "mix-blend-mode", style.GetPropertyValue("mix-blend-mode")); AddIfPresent(map, "isolation", style.GetPropertyValue("isolation")); @@ -8524,12 +8541,12 @@ private static List GetAuthoredRules(IDocument document, string pr return rules; } - private static bool TryGetFirstCollapsibleChildTopMargin(ElementRenderNode node, float containingWidth, LayoutContext context, out float marginTop) + private static bool TryGetFirstCollapsibleChildTopMargin(ElementRenderNode node, float containingWidth, LayoutContext context, out MarginStrut marginTop) { // a deep subtree is left out once the stack runs low (see LayoutNode) if (!RuntimeHelpers.TryEnsureSufficientExecutionStack()) { - marginTop = 0f; + marginTop = MarginStrut.Zero; return false; } @@ -8543,7 +8560,7 @@ private static bool TryGetFirstCollapsibleChildTopMargin(ElementRenderNode node, { if (NormalizeWhitespace(textNode.Ref.Data).Length > 0) { - marginTop = throughPositive + throughNegative; + marginTop = new MarginStrut(throughPositive, throughNegative); return hasThrough; } @@ -8573,7 +8590,7 @@ private static bool TryGetFirstCollapsibleChildTopMargin(ElementRenderNode node, // Inline-level content (atomic inlines included) starts a line, which separates the margins. if (ClassifyFlowChild(childElement, context) != FlowChildKind.Block) { - marginTop = throughPositive + throughNegative; + marginTop = new MarginStrut(throughPositive, throughNegative); return hasThrough; } @@ -8585,7 +8602,7 @@ private static bool TryGetFirstCollapsibleChildTopMargin(ElementRenderNode node, continue; } - marginTop = ParseLength(childStyle, "margin-top", containingWidth, 0f, allowAuto: false); + var childMarginTop = MarginStrut.From(ParseLength(childStyle, "margin-top", containingWidth, 0f, allowAuto: false)); // The child's margin itself collapses through to its own first child when nothing // separates them, so a whole chain of first children shares one margin. @@ -8597,14 +8614,14 @@ private static bool TryGetFirstCollapsibleChildTopMargin(ElementRenderNode node, !StartsWritingModeSystem(childElement.Ref, context) && TryGetFirstCollapsibleChildTopMargin(childElement, containingWidth, context, out var grandchildMarginTop)) { - marginTop = CollapseMargins(marginTop, grandchildMarginTop); + childMarginTop = childMarginTop.Append(grandchildMarginTop); } - marginTop = Math.Max(throughPositive, Math.Max(0f, marginTop)) + Math.Min(throughNegative, Math.Min(0f, marginTop)); + marginTop = new MarginStrut(throughPositive, throughNegative).Append(childMarginTop); return true; } - marginTop = throughPositive + throughNegative; + marginTop = new MarginStrut(throughPositive, throughNegative); return hasThrough; } @@ -8835,6 +8852,10 @@ private sealed class PaintOrder private const int FloatLayer = int.MinValue; private readonly List<(int Z, int Order, RenderCommand First, int Count, IElement Element)> _raised = []; + // the bounds of the floats moved (null if not known), and the atomic inlines of the children + // that paint above them where they overlap one + private List? _floatBounds; + private List<(HoistCandidate Candidate, IElement Box)>? _inlineContent; private LayoutContext? _context; // if boxes were taken out of the children, whose ranges then hold theirs (see Hoist) private bool _hasHoisted; @@ -8861,6 +8882,9 @@ public void Track(IRenderNode child, DisplayList displayList, int start, LayoutC if (isBlockFlow && IsFloated(styleMap) && !IsOutOfFlowPositioned(styleMap) && !IsRelativePositioned(styleMap)) { _raised.Add((FloatLayer, _raised.Count, displayList.Commands[start], count, element.Ref)); + (_floatBounds ??= []).Add(s_layoutCapture.Value is { } capture && capture.TryGet(element.Ref, out var floatMetrics) + ? new RenderRect(floatMetrics.BorderBoxX, floatMetrics.BorderBoxY, floatMetrics.BorderBoxWidth, floatMetrics.BorderBoxHeight) + : null); } // the positioned boxes in it paint with those of this flow (e.g. a tooltip in a @@ -8919,6 +8943,13 @@ private void Hoist(IElement box, DisplayList? displayList, int start, int count, if (IndexOf(commands, candidate.First, start, count) is >= 0 and var position && position + candidate.Count <= start + count && !HasOpenScope(commands, start, position)) { + // raised once it is known to overlap a float of this flow (see Apply) + if (candidate.Z == InlineContentLayer) + { + (_inlineContent ??= []).Add((candidate, box)); + continue; + } + _raised.Add((candidate.Z, _raised.Count, candidate.First, candidate.Count, candidate.Element)); _hasHoisted = true; ForgetRanges(candidate.Element.ParentElement, box); @@ -8947,6 +8978,9 @@ private static void ForgetRanges(IElement? from, IElement to) } } + private static bool Intersects(RenderRect a, RenderRect b) => + a.X < b.X + b.Width && b.X < a.X + a.Width && a.Y < b.Y + b.Height && b.Y < a.Y + a.Height; + private static bool HasOpenScope(IReadOnlyList commands, int start, int end) { var depth = 0; @@ -8983,6 +9017,19 @@ private static int IndexOf(IReadOnlyList commands, RenderCommand public void Apply(DisplayList displayList) { + if (_inlineContent is not null && _floatBounds is not null) + { + foreach (var (candidate, box) in _inlineContent) + { + if (_floatBounds.Exists(bounds => bounds is not { } rect || candidate.Bounds is not { } inline || Intersects(rect, inline))) + { + _raised.Add((candidate.Z, _raised.Count, candidate.First, candidate.Count, candidate.Element)); + _hasHoisted = true; + ForgetRanges(candidate.Element.ParentElement, box); + } + } + } + if (_raised.Count == 0) { return; @@ -9079,7 +9126,7 @@ void AddRange((int StartIndex, int Count) range) { foreach (var (z, _, first, count, element) in ordered) { - if (z != FloatLayer) + if (z is not FloatLayer and not InlineContentLayer) { context.HoistCandidates.Add(new HoistCandidate(displayList, z, first, count, element)); } @@ -9635,8 +9682,27 @@ private static bool IsReplacedElement(IElement element) => element is IPseudoEle : string.Equals(element.LocalName, "img", StringComparison.OrdinalIgnoreCase) || string.Equals(element.LocalName, "svg", StringComparison.OrdinalIgnoreCase) || IsCanvas(element) || + IsImageObject(element) || (IsImageInput(element) && HasLoadableImageSource(element)); + /// + /// An object showing an image, which replaces its content (the fallback for when + /// the data cannot be shown, e.g. as it failed to load or is of an unknown type, HTML 4.8.6). + /// + private static bool IsImageObject(IElement element) => + element is not IPseudoElement && + string.Equals(element.LocalName, "object", StringComparison.OrdinalIgnoreCase) && + TryGetObjectImage(element, out _); + + // the image of an object once its data is there (a layout does not wait for it, e.g. for a + // page of another type that is slow to answer, whose fallback shows meanwhile) + private static bool TryGetObjectImage(IElement element, out CachedImageResource? imageResource) + { + imageResource = null; + return element is not ILoadableElement { CurrentDownload.Task.IsCompleted: false } && + TryGetOrLoadImageResource(element, element.GetAttribute("data"), out imageResource) && imageResource is not null; + } + private static bool HasLoadableImageSource(IElement element) => TryGetOrLoadImageResource(element, element.GetAttribute("src"), out var imageResource) && imageResource is not null; @@ -9669,6 +9735,13 @@ private static bool TryResolveImage(ElementRenderNode node, Dictionary - private static void PaintBoxBackground(DisplayList displayList, Dictionary styleMap, BoxStyle box, float x, float y, float width, float height, EdgeSizes border, EdgeSizes padding) + private static void PaintBoxBackground(DisplayList displayList, Dictionary styleMap, BoxStyle box, float x, float y, float width, float height, EdgeSizes border, EdgeSizes padding, RenderRect? viewportArea = null) { var layers = box.BackgroundLayers ?? []; @@ -12721,7 +12795,20 @@ private static void PaintBoxBackground(DisplayList displayList, Dictionary 0f, Height: > 0f } viewport) + { + // `background-attachment: fixed`: positioned in the viewport, which it stays in + // while the page (and the box clipping it) scrolls + displayList.PushClip(clipRect, clipRadii.ClampToBox(clipRect.Width, clipRect.Height)); + displayList.Add(new PushViewportAnchorCommand()); + PaintBackground(displayList, layer.Paint, viewport.X, viewport.Y, viewport.Width, viewport.Height, default, viewport); + displayList.Add(new PopViewportAnchorCommand()); + displayList.PopClip(); + } + else + { + PaintBackground(displayList, layer.Paint, clipRect.X, clipRect.Y, clipRect.Width, clipRect.Height, clipRadii, originRect); + } if (layer.BlendMode != RenderBlendMode.Normal) { @@ -12735,6 +12822,12 @@ private static void PaintBoxBackground(DisplayList displayList, Dictionary + /// The viewport, which fixed boxes and backgrounds are positioned in (see LayoutElement). + /// + private static RenderRect GetViewportArea(LayoutContext context) => + new(context.Padding, context.Padding, Math.Max(0f, context.Width - (2f * context.Padding)), Math.Max(0f, context.Height - (2f * context.Padding))); + /// /// The border box, padding box or content box (`border-box`, `padding-box`, `content-box`; /// when unset) with its corner radii. @@ -13140,6 +13233,8 @@ bool IsSameAsNext(int i) return; } + var groups = new List<(int From, int Length)>(4); + for (var count = 0; count < 4;) { var from = (first + count) % 4; @@ -13151,12 +13246,33 @@ bool IsSameAsNext(int i) } count += length; + groups.Add((from, length)); + } + + // a solid side reaching under an opaque solid neighbor painted after it, so that their + // diagonal is anti-aliased once, against its color rather than what is behind the border + // (like Blink; else the background showed through the seam) + bool CoversSeam(int side) => + isSquare && IsPainted(side) && sides[side].Style == BorderStyleKind.Solid && sides[side].Color.A == 255; + + (float X, float Y) WedgeCorner(int side, int corner) => side % 2 == 0 + ? (inner[corner].X, outer[corner].Y) + : (outer[corner].X, inner[corner].Y); + + for (var group = 0; group < groups.Count; group++) + { + var (from, length) = groups[group]; if (!IsPainted(from)) { continue; } + var end = (from + length) % 4; + var previousSide = (from + 3) % 4; + var extendsAtEnd = group < groups.Count - 1 && CoversSeam(from) && CoversSeam(end); + var extendsAtStart = group == 0 && groups.Count > 1 && CoversSeam(from) && CoversSeam(previousSide); + if (sides[from].Style is BorderStyleKind.Dashed or BorderStyleKind.Dotted) { PaintBrokenRoundedSide(displayList, from, sides[from].Style, sides[from].Color, x, y, width, height, border, radii); @@ -13171,11 +13287,21 @@ bool IsSameAsNext(int i) region.Add(outer[(from + i) % 4]); } + if (extendsAtEnd) + { + region.Add(WedgeCorner(end, end)); + } + for (var i = length; i >= 0; i--) { region.Add(inner[(from + i) % 4]); } + if (extendsAtStart) + { + region.Add(WedgeCorner(previousSide, from)); + } + displayList.PushClipShape(new RenderClipPolygon([.. region])); PaintBorderBands(displayList, sides[from].Style, sides[from].Color, sides[from].IsTopOrLeft, x, y, width, height, border, radii); displayList.PopClip(); @@ -13497,8 +13623,9 @@ private static void PaintBorderEdge(DisplayList displayList, RenderColor color, } } - private static float CollapseMargins(float first, float second, float third) => - Math.Max(0f, Math.Max(first, Math.Max(second, third))) + Math.Min(0f, Math.Min(first, Math.Min(second, third))); + // the paragraph spacing of RenderOptions, added to the margins below a block + private static MarginStrut WithParagraphSpacing(MarginStrut margins, LayoutContext context) => + context.ParagraphSpacing == 0f ? margins : MarginStrut.From(margins.Value + context.ParagraphSpacing); private static float CollapseMargins(float previousMarginBottom, float currentMarginTop) { @@ -13819,7 +13946,7 @@ private static bool TryParsePixelValue(string value, out float pixels) /// /// One `background-image` layer with the companion properties that apply to it. /// - private readonly record struct BackgroundLayer(RenderPaint Paint, string Clip, string Origin, RenderBlendMode BlendMode, int Index); + private readonly record struct BackgroundLayer(RenderPaint Paint, string Clip, string Origin, RenderBlendMode BlendMode, int Index, bool IsFixed = false); /// /// The value of a comma-separated layer property for layer ; a list @@ -13914,7 +14041,8 @@ private static List ParseImageLayers(Dictionary (GetLayerValue(styleMap, names.Clip, index) ?? string.Empty).ToLowerInvariant(), (GetLayerValue(styleMap, names.Origin, index) ?? string.Empty).ToLowerInvariant(), ParseBlendModeKeyword(GetLayerValue(styleMap, names.BlendMode, index)), - index)); + index, + prefix == "background" && string.Equals(GetLayerValue(styleMap, "background-attachment", index)?.Trim(), "fixed", StringComparison.OrdinalIgnoreCase))); } return layers; diff --git a/src/AngleSharp.Renderer/MarginStrut.cs b/src/AngleSharp.Renderer/MarginStrut.cs new file mode 100644 index 0000000..a6f1dd8 --- /dev/null +++ b/src/AngleSharp.Renderer/MarginStrut.cs @@ -0,0 +1,33 @@ +namespace AngleSharp.Renderer; + +/// +/// Adjoining vertical margins that have not been placed yet (a "margin strut"): they collapse +/// into the largest positive one plus the most negative one (CSS 2.1 §8.3.1). Keeping both +/// parts, rather than their sum, collapses a chain of margins correctly, e.g. those of an empty +/// block between others (75px and -72px collapse through it to 3px, which joins 48px before it +/// to 3px again, not to 48px). +/// +internal readonly record struct MarginStrut(float Positive, float Negative) +{ + public static readonly MarginStrut Zero = default; + + /// + /// The space the margins take: the largest positive one plus the most negative one. + /// + public float Value => Positive + Negative; + + public static MarginStrut From(float margin) => + float.IsNaN(margin) ? Zero : margin >= 0f ? new MarginStrut(margin, 0f) : new MarginStrut(0f, margin); + + /// + /// The margins collapsed with another one. + /// + public MarginStrut Append(MarginStrut other) => + new(Math.Max(Positive, other.Positive), Math.Min(Negative, other.Negative)); + + public MarginStrut Append(float margin) => Append(From(margin)); + + public static implicit operator float(MarginStrut strut) => strut.Value; + + public static implicit operator MarginStrut(float margin) => From(margin); +} diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 36fc2cd..60670d6 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ Adds rendering functionality to the core AngleSharp library. AngleSharp.Renderer - 0.12.0 + 0.12.1 enable latest true From 617013789d88d7f5d47dd0c9312ffe791284d8c6 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 11:03:52 +0100 Subject: [PATCH 02/23] Added Acid1 test for conformance --- .../Acid1ConformanceTests.cs | 109 +++++++++++ .../cases/test15-acid1.html | 177 ++++++++++++++++++ .../verification-assets/acid1.linux.png | Bin 0 -> 31135 bytes 3 files changed, 286 insertions(+) create mode 100644 src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs create mode 100644 src/AngleSharp.Renderer.Tests/cases/test15-acid1.html create mode 100644 src/AngleSharp.Renderer.Tests/verification-assets/acid1.linux.png diff --git a/src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs b/src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs new file mode 100644 index 0000000..5cc5ea1 --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs @@ -0,0 +1,109 @@ +namespace AngleSharp.Renderer.Tests; + +using AngleSharp; +using AngleSharp.Css; +using AngleSharp.Dom; +using AngleSharp.Renderer.Rendering; + +/// +/// The Acid1 test (cases/test15-acid1.html, the CSS1 test "display/box/float/clear"): +/// every box above the paragraph has a size fixed in ems, so the reference rendering +/// (sec5526c.gif) pins each of them to the pixel. +/// +[Trait("Category", "Visual")] +public sealed class Acid1ConformanceTests +{ + private const int ViewportWidth = 960; + private const int ViewportHeight = 1420; + + [Fact] + public async Task Acid1_LaysOutTheBoxesOfTheReferenceRendering() + { + var document = await OpenAsync(); + + // html at 10px: body has a 15px margin and a 5px border, the dl a 5px padding + var body = Box(document, "body"); + Assert.Equal(15f, body.X, precision: 1); + Assert.Equal(15f, body.Y, precision: 1); + Assert.Equal(490f, body.Width, precision: 1); + AssertBox(document, "dt", 25f, 25f, 80f, 310f); + AssertBox(document, "dd", 115f, 25f, 380f, 310f); + AssertBox(document, "li:nth-child(1)", 135f, 45f, 80f, 120f); + AssertBox(document, "#bar", 225f, 45f, 160f, 110f); + AssertBox(document, "li:nth-child(3)", 395f, 45f, 80f, 120f); + // below "i grow old" (CSS 1 float rule 2), not beside it under #bar + AssertBox(document, "#baz", 135f, 175f, 120f, 120f); + AssertBox(document, "blockquote", 275f, 175f, 70f, 140f); + AssertBox(document, "h1", 355f, 175f, 120f, 120f); + + // the paragraph clears both floats + var paragraph = Box(document, "body > p"); + Assert.Equal(20f, paragraph.X, precision: 1); + Assert.Equal(335f, paragraph.Y, precision: 1); + Assert.Equal(480f, paragraph.Width, precision: 1); + } + + [Fact] + public async Task Acid1_MatchesTheSnapshot() + { + var document = await OpenAsync(); + var image = new HtmlRenderer().RenderToPng(document, CreateDevice()); + + VisualSnapshotVerifier.VerifyOrCreate( + snapshotName: "acid1.png", + actualPng: image.Data, + perChannelTolerance: 12, + maxDifferentPixels: 20); + } + + private static void AssertBox(IDocument document, string selector, float x, float y, float width, float height) + { + var box = Box(document, selector); + Assert.Equal(x, box.X, precision: 1); + Assert.Equal(y, box.Y, precision: 1); + Assert.Equal(width, box.Width, precision: 1); + Assert.Equal(height, box.Height, precision: 1); + } + + private static RenderRect Box(IDocument document, string selector) + { + var rect = document.QuerySelector(selector)!.GetBoundingClientRect(); + return new RenderRect((float)rect.Left, (float)rect.Top, (float)rect.Width, (float)rect.Height); + } + + private static DefaultRenderDevice CreateDevice() => new() + { + ViewPortWidth = ViewportWidth, + ViewPortHeight = ViewportHeight, + FontSize = 16f, + }; + + private static async Task OpenAsync() + { + var html = await File.ReadAllTextAsync(Path.Combine(FindProjectRoot(), "cases", "test15-acid1.html")); + // Verdana is installed on some hosts only; snapshots use the bundled fonts + html = html.Replace("Verdana, sans-serif", "sans-serif", StringComparison.Ordinal); + + var context = BrowsingContext.New(Configuration.Default.WithCss().WithRenderDevice(CreateDevice())); + var document = await context.OpenAsync(request => request.Content(html)); + context.GetDomHarness(); + return document; + } + + private static string FindProjectRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + + while (directory is not null) + { + if (File.Exists(Path.Combine(directory.FullName, "AngleSharp.Renderer.Tests.csproj"))) + { + return directory.FullName; + } + + directory = directory.Parent; + } + + throw new InvalidOperationException("Could not locate AngleSharp.Renderer.Tests project root."); + } +} diff --git a/src/AngleSharp.Renderer.Tests/cases/test15-acid1.html b/src/AngleSharp.Renderer.Tests/cases/test15-acid1.html new file mode 100644 index 0000000..3fffecd --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/cases/test15-acid1.html @@ -0,0 +1,177 @@ + + + + + display/box/float/clear test + + + + +
+
+ toggle +
+
+
    +
  • + the way +
  • +
  • +

    + the world ends +

    +
    +

    + bang + +

    +

    + whimper + +

    +
    +
  • +
  • + i grow old +
  • +
  • + pluot? +
  • +
+
+
+ bar maids, +
+
+

+ sing to me, erbarme dich +

+
+
+

+ This is a nonsensical document, but syntactically valid HTML 4.0. All 100%-conformant CSS1 agents should be able to render the document elements above this paragraph indistinguishably (to the pixel) from this + reference rendering, + (except font rasterization and form widgets). All discrepancies should be traceable to CSS1 implementation shortcomings. Once you have finished evaluating this test, you can return to the parent page. +

+ + diff --git a/src/AngleSharp.Renderer.Tests/verification-assets/acid1.linux.png b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.linux.png new file mode 100644 index 0000000000000000000000000000000000000000..6ee19e49cd5ba87bc4a89ac2a825d04ed894b259 GIT binary patch literal 31135 zcmeFZcUY78+9w{z867L*C?ZH1MN~jQq<1?40@9TdRHQd4p@k3~M^qG0icxwCy@>Q0 zl_nrP5FkL5NDW0=0)(>npK+cr)NKJgP(kfnJtDdKYEkMaP*u~C^VNRL{c4*B-3}&Q+S%n85xA#^YjIwUM$R995_7;ggUU0eP zRF+axVYY?_ccse3^jPK8q-`44Q~%I8`tjUPeF@n#fn#pH*a8KYn^ke4+e2?p7v(OM z`}L9Y5YgzTOl1 zU-yFcN}K4zMMm3EsB}y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sMr7i literal 0 HcmV?d00001 From e5bd6e604f4227f1fca8f2cef51b567e69225ac8 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 12:28:14 +0100 Subject: [PATCH 03/23] Fixes for improving Acid3 --- CHANGELOG.md | 4 + .../Acid3RegressionTests.cs | 101 ++++++++++++++++++ .../HtmlRenderer.Frames.cs | 22 ++-- src/AngleSharp.Renderer/HtmlRenderer.cs | 42 +++++++- .../InteractiveHtmlRendererStateExtensions.cs | 7 +- .../Rendering/ObjectDocumentService.cs | 47 ++++++++ .../RenderingConfigurationExtensions.cs | 7 +- 7 files changed, 219 insertions(+), 11 deletions(-) create mode 100644 src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs create mode 100644 src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 927b03b..fdd644b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ Released on tbd. - Fixed the background showing through where two border sides of different colors meet on a diagonal - Fixed `data:` images whose base64 is percent-encoded (e.g. `%2F` for `/`) not being shown - Added `object` elements showing an image instead of their fallback content +- Fixed an `object` with data that failed to load (e.g. a 404) showing it instead of its fallback content +- Fixed an `object` showing a page (e.g. `text/html`) showing its fallback content; it is an empty box of the size of an iframe +- Fixed the document of an empty iframe (e.g. 0 by 0) keeping the viewport of 300 by 150 +- Updated the document of an iframe to keep the render device of its browsing context, if it has one of its own # 0.12.0 diff --git a/src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs b/src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs new file mode 100644 index 0000000..c67e8cb --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs @@ -0,0 +1,101 @@ +namespace AngleSharp.Renderer.Tests; + +using System.Net; +using AngleSharp; +using AngleSharp.Css; +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Renderer; +using AngleSharp.Renderer.Rendering; + +/// +/// Reduced versions of what the Acid3 test (acid3.acidtests.org) showed to differ from browsers. +/// +public sealed class Acid3RegressionTests +{ + private static readonly DefaultRenderDevice Device = new() { ViewPortWidth = 800, ViewPortHeight = 600, FontSize = 16 }; + + // a 1x1 yellow PNG + private static readonly byte[] YellowPixel = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4/58BAAT/Af9jgNErAAAAAElFTkSuQmCC"); + + [Fact] + public async Task ObjectWithADocument_HidesItsFallback() + { + // test 16: a 404 (even of an image) shows the fallback, a page is shown instead of it + var document = await OpenAsync(""" + FAIL + """); + + Assert.Equal(300f, Rect(document, "b").Width, precision: 1); + Assert.Equal(150f, Rect(document, "b").Height, precision: 1); + Assert.DoesNotContain(new HtmlRenderer().BuildDisplayList(document, Device).Commands, command => command.GetType().Name.Contains("Text")); + } + + [Fact] + public async Task ObjectWithAMissingImage_ShowsItsFallback() + { + var document = await OpenAsync(""" + fallback + """); + + Assert.True(Rect(document, "fallback").Width > 0f); + } + + private static RenderRect Rect(IDocument document, string id) + { + var rect = document.GetElementById(id)!.GetBoundingClientRect(); + return new RenderRect((float)rect.Left, (float)rect.Top, (float)rect.Width, (float)rect.Height); + } + + private static async Task OpenAsync(string body) + { + var context = BrowsingContext.New(Configuration.Default + .WithCss() + .WithRenderDevice(Device) + .WithRendering() + .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }) + .With(new SiteRequester())); + var document = await context.OpenAsync(request => request.Address("http://localhost/").Content($$""" + + {{body}} + """)); + + // the objects show what they show once their data is there + foreach (var element in document.QuerySelectorAll("object").OfType()) + { + if (element.CurrentDownload?.Task is { } task) + { + await task; + } + } + + await Task.Delay(50); + context.GetDomHarness(); + return document; + } + + // what Acid3's server answers + private sealed class SiteRequester : BaseRequester + { + public override bool SupportsProtocol(string protocol) => + string.Equals(protocol, "http", StringComparison.OrdinalIgnoreCase); + + protected override Task PerformRequestAsync(Request request, CancellationToken cancel) + { + var (status, type, content) = request.Address.Path switch + { + "missing.png" => (HttpStatusCode.NotFound, "image/png", YellowPixel), + "page.png" => (HttpStatusCode.OK, "text/html; charset=utf-8", "FAIL

"u8.ToArray()), + _ => (HttpStatusCode.OK, "image/png", YellowPixel), + }; + var response = new DefaultResponse + { + Address = request.Address, + StatusCode = status, + Content = new MemoryStream(content), + }; + response.Headers[HeaderNames.ContentType] = type; + return Task.FromResult(response); + } + } +} diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs b/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs index 781df15..7c84609 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs @@ -39,22 +39,28 @@ internal sealed class SubframeEntry ///

private static void PaintSubframe(DisplayList displayList, IElement element, LayoutContext context, float x, float y, float width, float height) { - if (s_trialDepth > 0 || width <= 0f || height <= 0f) + if (s_trialDepth > 0) { return; } - var viewport = new RenderRect(x, y, width, height); - var command = new DrawSubframeCommand(viewport); - displayList.Add(command); + var viewport = new RenderRect(x, y, Math.Max(0f, width), Math.Max(0f, height)); if (!context.Subframes.TryGetValue(element, out var entry)) { context.Subframes[element] = entry = new SubframeEntry(); } - entry.Commands.Add(command); entry.Viewport = viewport; + + // an empty iframe shows nothing, but its document still has that viewport (e.g. for + // its media queries) + if (width > 0f && height > 0f) + { + var command = new DrawSubframeCommand(viewport); + displayList.Add(command); + entry.Commands.Add(command); + } } private static void ResolveSubframes(IDocument document, LayoutContext context) @@ -83,7 +89,11 @@ private static void ResolveSubframes(IDocument document, LayoutContext context) { parent?.AttachSubframe(state); state.SetViewport((int)Math.Round(entry.Viewport.Width), (int)Math.Round(entry.Viewport.Height)); - entry.Frame = state.PrepareFrame(); + + if (entry.Commands.Count > 0) + { + entry.Frame = state.PrepareFrame(); + } } foreach (var command in entry.Commands) diff --git a/src/AngleSharp.Renderer/HtmlRenderer.cs b/src/AngleSharp.Renderer/HtmlRenderer.cs index b24da4a..e198070 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.cs @@ -9699,10 +9699,48 @@ element is not IPseudoElement && private static bool TryGetObjectImage(IElement element, out CachedImageResource? imageResource) { imageResource = null; + // an error (e.g. a 404 with an image) shows the fallback (HTML 4.8.6) return element is not ILoadableElement { CurrentDownload.Task.IsCompleted: false } && + (GetObjectResponse(element) is not { } response || IsSuccessful(response)) && TryGetOrLoadImageResource(element, element.GetAttribute("data"), out imageResource) && imageResource is not null; } + /// + /// An object showing a document (e.g. a page of HTML) rather than an image, which + /// hides its fallback like an iframe. The document itself isn't shown (Acid3 has a + /// transparent one), so the object is an empty box of the size of an iframe. + /// + private static bool ShowsObjectDocument(IElement element) + { + if (element is IPseudoElement || !string.Equals(element.LocalName, "object", StringComparison.OrdinalIgnoreCase) || + GetObjectResponse(element) is not { } response || !IsSuccessful(response)) + { + return false; + } + + return ObjectDocumentService.IsDocument(response); + } + + // the completed response of the data of an object, if any (one a request failed for is none) + private static IResponse? GetObjectResponse(IElement element) + { + if (element is not ILoadableElement { CurrentDownload.Task: { IsCompleted: true } task }) + { + return null; + } + + try + { + return task.Status == TaskStatus.RanToCompletion ? task.Result : null; + } + catch + { + return null; + } + } + + private static bool IsSuccessful(IResponse response) => (int)response.StatusCode is >= 200 and < 300; + private static bool HasLoadableImageSource(IElement element) => TryGetOrLoadImageResource(element, element.GetAttribute("src"), out var imageResource) && imageResource is not null; @@ -10699,7 +10737,7 @@ private static FormControlKind ResolveFormControlKind(ElementRenderNode node) return FormControlKind.Progress; } - if (string.Equals(tagName, "iframe", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(tagName, "iframe", StringComparison.OrdinalIgnoreCase) || ShowsObjectDocument(element)) { return FormControlKind.Frame; } @@ -11557,7 +11595,7 @@ private static void PaintFormControl( PaintListBox(displayList, element, textStyle, context, contentX, contentY, contentWidth, contentHeight); break; - case FormControlKind.Frame: + case FormControlKind.Frame when string.Equals(element.LocalName, "iframe", StringComparison.OrdinalIgnoreCase): PaintSubframe(displayList, element, context, contentX, contentY, contentWidth, contentHeight); break; diff --git a/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs b/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs index be87b75..1d18963 100644 --- a/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs +++ b/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs @@ -30,13 +30,16 @@ public static IDomHarness GetDomHarness(this IBrowsingContext context) throw new InvalidOperationException("No IRenderDevice service is registered in the browsing context. Register a render device service in IConfiguration before creating the context."); } - // the document of an iframe has a viewport of its own - if (browsingContext.Parent is not null) + // the document of an iframe has a viewport of its own, which is the device of its + // context if the host registered one per context (so its media queries see it too) + if (browsingContext.Parent is { } parentContext && + (renderDevice is not DefaultRenderDevice || ReferenceEquals(renderDevice, parentContext.GetServices().FirstOrDefault()))) { renderDevice = new DefaultRenderDevice { Category = renderDevice.Category, ColorBits = renderDevice.ColorBits, + MonochromeBits = renderDevice.MonochromeBits, Frequency = renderDevice.Frequency, IsInterlaced = renderDevice.IsInterlaced, IsScripting = renderDevice.IsScripting, diff --git a/src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs b/src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs new file mode 100644 index 0000000..06a7714 --- /dev/null +++ b/src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs @@ -0,0 +1,47 @@ +namespace AngleSharp.Renderer.Rendering; + +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Media; + +/// +/// Notes the responses of object data that are documents (e.g. a page of HTML), which +/// an object shows instead of its fallback. AngleSharp clears the headers of a response once +/// it has been processed, so the type has to be noted while it is. +/// +internal sealed class ObjectDocumentService : IResourceService +{ + private static readonly ConditionalWeakTable s_documents = new(); + private static readonly object s_marker = new(); + + public static ObjectDocumentService Instance { get; } = new(); + + private ObjectDocumentService() + { + } + + public bool SupportsType(string mimeType) => IsDocumentType(mimeType); + + public Task CreateAsync(IResponse response, CancellationToken cancel) + { + s_documents.AddOrUpdate(response, s_marker); + return Task.FromResult(new ObjectInfo { Source = response.Address }); + } + + public static bool IsDocument(IResponse response) => s_documents.TryGetValue(response, out _); + + private static bool IsDocumentType(string? mimeType) => + mimeType?.Split(';')[0].Trim().ToLowerInvariant() is "text/html" or "application/xhtml+xml" or "text/plain" or "text/xml" or "application/xml"; + + private sealed class ObjectInfo : IObjectInfo + { + public required Url Source { get; set; } + + public int Width => 0; + + public int Height => 0; + } +} diff --git a/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs b/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs index 2e235a7..444ca5e 100644 --- a/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs +++ b/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs @@ -28,8 +28,13 @@ public static IConfiguration WithRendering(this IConfiguration configuration, Fu ArgumentNullException.ThrowIfNull(factory); configuration = configuration.WithOnly(factory); - return configuration.Services.OfType().Any() + configuration = configuration.Services.OfType().Any() ? configuration : configuration.With(ImageResourceService.Instance); + + // an object showing a document hides its fallback + return configuration.Services.OfType().Any() + ? configuration + : configuration.With(ObjectDocumentService.Instance); } } From a62b56088a403377cfceed38bc95f55b982a1956 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:55:33 +0000 Subject: [PATCH 04/23] Regenerate visual snapshot baselines for all platforms --- .../verification-assets/acid1.macos.png | Bin 0 -> 36425 bytes .../verification-assets/acid1.windows.png | Bin 0 -> 23110 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/AngleSharp.Renderer.Tests/verification-assets/acid1.macos.png create mode 100644 src/AngleSharp.Renderer.Tests/verification-assets/acid1.windows.png diff --git a/src/AngleSharp.Renderer.Tests/verification-assets/acid1.macos.png b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.macos.png new file mode 100644 index 0000000000000000000000000000000000000000..2a6694ba3a35afdd0d0d758dc9fc46fa5cac3af3 GIT binary patch literal 36425 zcmeFZXIN9+)-{a1VHZVIupkNusDL0yQ91}nuK^XMMSAa++lB%H(!2C79TFfG1nDI} zXd!B(gg}rIN+9sf?S0O7p3{H4&#(7-xx55IviI6+uQlfwV~)9B-qKLoy^~`n3k%C` z6=ivC7M4vPSXj2a-o6!H`5r%A4&OGr+)&Zo4qv|8@4aAQImx0Te_huzev;_pduW8X zzV7k$sPf6p2j3`fSJ=b5^YkZy7bn^F@#?0YKGYG*{=zUvpmf11_o?>Y8KusJ`hzb% z$~x?PA!fLRW}@NT`&ew>_6?{0czAO2_EX2gTJ7Cy11{wKG077*cgL)~;mqFR5`yVm zm8BKWilwEMANS{dFdh~bb<+}t;P0OvVq{s6p|V78+`x`}zrAzwZRGny-hB@@AU|aM z@4ex%Io)zGJ6nQ0~NbpH_k%U@6ayN}zh@)*(_ErKUz7V7WjS+QK)W-q>jMYhLr z>wme-8wo?3n-hrivTs`p9Q=;_9)$WKtN%6`-Gl1yZw0V^&YC{J!eYO)wAAgfgM~%J zCVsA6Uw?O9CGz{ zV(7iblw-(WJKl>du?&rbYyKpUWlHPk`umQ*;m+2v&0+LCz?7uPqr~i2Q>J1?k)J&d z9U5<-P$o*PwW{zAhv@akCM?P(G@i>9+1SkPV9iU_+K3#|*5t|F4@%@8_xh$7JQr_m z^O=7W@O;nCByp{Noy-YC)A$=(_v(-T`o42w7?scIDcevV+%vP|;Gyms?CR;$*EDdU zFvP(4OLFIUGxsw&z}`jOm}j5O{FeDl1dT`VgWl~4ZBEg`7!tS9G}O88r02eX8r z-M^3M!+~O1u)`|`zdKE^c>d)y?)}C7_QZ(edkC(nY4Tw|$c<#g{q$5~aba-hi(vh) z9Vxa~J>PGX^l&dQAK?L}JC%Bss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*?)0 literal 0 HcmV?d00001 diff --git a/src/AngleSharp.Renderer.Tests/verification-assets/acid1.windows.png b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.windows.png new file mode 100644 index 0000000000000000000000000000000000000000..69d338c13dd55c48102c81963b6c08cdcbff91f9 GIT binary patch literal 23110 zcmeHvc{r49-@jIs%H2j;?~0VQl#QcEd<- z*A9^#e0+Sn^sipJ$;Y>;nU8Nv^tP?wlW%EM1o*Yt=YqcJHt-7BcJ~iHzTf%uFP%3H zOq;{QJxo_asoWvQ!!VrG>`MH*KNYv!jrT%mzKY56Oz^~9aBq6)FP3AT=)LRBfhA8H zJLvqCI}--mi$*6Av%{`RO=dZ+L--PnP51)cBk#}HC|`V5^X$luB@x(T@5h_=A0emA zJ*w8FlsT#sb-UEl)OAQ*DT~qV4ASbKSB715NVFih4k;v-)J^J&mLB0x<_Jm^YMjm zi8yeZH%R!NtKl1XZ?62lfw!o92On-e$oqZ!iF(+!K@UVXzbCj9qI{I#+s%AgV&?zJ zw>R&-%{wZ5j~nN(<@uG{vGvc`@9spO=6m%}Fby22QSz@Q*VP$$dy6`*;Hhw3Den@& zE9v;Z98QFB*wR%DhY%It$oG4=vsKLQ4SeC!G5>0En{)SlO~m7azfW~viTpADSNsAx z8;q>{*m#|c@{)$$>b|n54^!tQMn%lkqcU_lA6hWu?JEK;r)EPJ61)Q7mSIX z&aJoo?vJSm{&B7-A~?QWm;REF`np%Wvv-9>XXSCi@IzxIK1q3k8 zssY~e^y7RO$J+?a8#+ACF(`LaLBEpcNKSx~{YxqIS*?=VNI`e!fPfBv{ovWT5vxfw zZk@pV`nUm(*8o=$fcr%81YfglC&+swIjd+qx!lc2Gc-Bqa^}6$USLA1#~J#ZVok;SO@X@E~$neluS>~Jf=UQ|MHM6qLC-2+8j zu5}M)emW4aWhKq|Q2N?NaEZ+~tHFKoA~qH(AW8$uZNGr&1>bJp9gxSM=juu8>(0;0 zjc_Q5at+$*hZ^wI{LoNVtAdSzd3aByGCyyUh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Kg`ad8Mfm#3n literal 0 HcmV?d00001 From 8c059750a7fda43a7ace211f1cd4394de18b40c6 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sat, 21 Nov 2026 18:19:27 +0100 Subject: [PATCH 05/23] Fixed height computation and hit resolution --- CHANGELOG.md | 6 +- .../InteractiveFrameTests.cs | 20 ++ .../SiteRegressionTests.cs | 67 ++++++- src/AngleSharp.Renderer/HitTesting.cs | 11 +- .../HtmlRenderer.Incremental.cs | 2 +- src/AngleSharp.Renderer/HtmlRenderer.cs | 175 +++++++++++++++++- .../Rendering/HitTestMap.cs | 9 +- 7 files changed, 271 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fdd644b..bec35a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,15 @@ Released on tbd. - Fixed atomic inlines (e.g. an image overflowing a block of no height) being painted below the floats they overlap, as all inline content paints above the floats - Fixed the background showing through where two border sides of different colors meet on a diagonal - Fixed `data:` images whose base64 is percent-encoded (e.g. `%2F` for `/`) not being shown -- Added `object` elements showing an image instead of their fallback content - Fixed an `object` with data that failed to load (e.g. a 404) showing it instead of its fallback content - Fixed an `object` showing a page (e.g. `text/html`) showing its fallback content; it is an empty box of the size of an iframe - Fixed the document of an empty iframe (e.g. 0 by 0) keeping the viewport of 300 by 150 +- Fixed generated content being hit as the pseudo-element (in the hit-test map, `elementFromPoint` and for `:hover`) instead of its element, e.g. a link's `::after` stretched over a whole card did not act as the link +- Fixed grid items with a percentage `height` (e.g. `height: 100%` cards) in an auto row being as tall as the grid is wide; such a height contributes as `auto` to the row and then fills it +- Fixed text right in a grid container (e.g. the label of an icon with `display: grid; place-items: center`) not being an anonymous grid item: it stayed at the top left instead of being placed in a cell and aligned - Updated the document of an iframe to keep the render device of its browsing context, if it has one of its own +- Added `align-items: baseline` (and `align-self`) for flex items in a row: an item without text sits on the baseline with the bottom of its border box (e.g. a rule after a heading's text), where it was at the top of the line +- Added `object` elements showing an image instead of their fallback content # 0.12.0 diff --git a/src/AngleSharp.Renderer.Tests/InteractiveFrameTests.cs b/src/AngleSharp.Renderer.Tests/InteractiveFrameTests.cs index 85889ca..8e8896f 100644 --- a/src/AngleSharp.Renderer.Tests/InteractiveFrameTests.cs +++ b/src/AngleSharp.Renderer.Tests/InteractiveFrameTests.cs @@ -341,6 +341,26 @@ private static async Task CountTrialLayoutsAsync(string open, string close, return trials; } + [Fact] + public async Task HitTestMap_HitsGeneratedContentAsItsElement() + { + // a card link: the `::after` of the link is stretched over the whole card + var (document, harness) = await OpenAsync(""" + +

+ """); + + var map = harness.PrepareFrame().HitTestMap; + + Assert.Same(document.GetElementById("link"), map.HitTest(150, 80)?.Element); + Assert.Equal("pointer", map.HitTest(150, 80)?.Cursor); + Assert.Contains(document.GetElementById("link")!, map.Elements); + Assert.DoesNotContain(map.Elements, element => element is IPseudoElement); + Assert.Same(document.GetElementById("link"), document.ElementFromPoint(150, 80)); + } + private static async Task<(IDocument Document, IDomHarness Harness)> OpenAsync(string body) { var configuration = Configuration.Default.WithCss().WithRenderDevice(Device); diff --git a/src/AngleSharp.Renderer.Tests/SiteRegressionTests.cs b/src/AngleSharp.Renderer.Tests/SiteRegressionTests.cs index 7239c4a..d85420b 100644 --- a/src/AngleSharp.Renderer.Tests/SiteRegressionTests.cs +++ b/src/AngleSharp.Renderer.Tests/SiteRegressionTests.cs @@ -1602,10 +1602,73 @@ public async Task PositionedBox_WithMaxHeightAndAutoMargins_IsCentered() Assert.Equal(300d, dialog.Height, 1); } - private static async Task OpenAsync(string body) + [Fact] + public async Task GridItem_WithPercentageHeight_FillsItsRow() + { + // anglesharp-tests renderer index: `height: 100%` cards in an auto row are as tall as the + // row, not as tall as the grid is wide + var document = await OpenAsync(""" +
    +
  • one line
  • +
  • +
  • x
  • +
+ """, isStandardsMode: true); + + var tall = document.GetElementById("tall")!.GetBoundingClientRect(); + var shorter = document.GetElementById("short")!.GetBoundingClientRect(); + var third = document.GetElementById("third")!.GetBoundingClientRect(); + + Assert.Equal(200d, tall.Width, 1); + Assert.Equal(400d, third.Left, 1); + Assert.Equal(80d, tall.Height, 1); + Assert.Equal(80d, shorter.Height, 1); + Assert.Equal(0d, shorter.Top, 1); + } + + [Fact] + public async Task GridText_IsAnAnonymousItemAlignedByTheContainer() + { + // an icon badge: text right in a grid container is centered in its cell + var document = await OpenAsync(""" + A1 + """, isStandardsMode: true); + + var range = document.CreateRange(); + range.SelectContent(document.GetElementById("icon")!); + var text = range.GetBoundingClientRect(); + + Assert.True(text.Width is > 0 and < 30, $"width {text.Width}"); + Assert.Equal(20d, text.Left + (text.Width / 2), 1); + Assert.Equal(20d, text.Top + (text.Height / 2), 1); + } + + [Fact] + public async Task FlexItem_WithoutText_SitsOnTheBaselineWithItsBottomEdge() + { + // a heading with a rule after its text: `align-items: baseline` and an empty `::after` + var document = await OpenAsync(""" +
+ AcidTests +
+ """, isStandardsMode: true); + + var heading = document.GetElementById("heading")!.GetBoundingClientRect(); + var label = document.GetElementById("label")!.GetBoundingClientRect(); + var rule = document.GetElementById("rule")!.GetBoundingClientRect(); + + // the larger text's baseline is well below the top of the line and the smaller one's + Assert.Equal(30d, heading.Height, 1); + Assert.True(label.Top > 5, $"label at {label.Top}"); + Assert.True(rule.Bottom > 15 && rule.Bottom < 30, $"rule ends at {rule.Bottom}"); + // the label's baseline (its text's bottom minus its descent) is where the rule ends + Assert.True(Math.Abs(label.Bottom - rule.Bottom) < 4, $"label {label.Bottom} rule {rule.Bottom}"); + } + + private static async Task OpenAsync(string body, bool isStandardsMode = false) { var context = BrowsingContext.New(Configuration.Default.WithCss().WithRenderDevice(Device)); - var document = await context.OpenAsync(request => request.Content($$""" + var document = await context.OpenAsync(request => request.Content((isStandardsMode ? "" : "") + $$""" {{body}} """)); diff --git a/src/AngleSharp.Renderer/HitTesting.cs b/src/AngleSharp.Renderer/HitTesting.cs index c4a353b..f88f361 100644 --- a/src/AngleSharp.Renderer/HitTesting.cs +++ b/src/AngleSharp.Renderer/HitTesting.cs @@ -33,9 +33,18 @@ internal static class HitTesting } } - return best; + // generated content is hit as the element it belongs to (CSSOM View: pseudo-elements are + // never the result), e.g. a link's `::after` stretched over a whole card is the link + return best is null ? null : GetOriginatingElement(best); } + /// + /// The element itself, or the one a pseudo-element belongs to (its ParentElement is + /// the parent of that element). + /// + internal static IElement GetOriginatingElement(IElement element) => + element is IPseudoElement pseudo && CssAnimationTracker.GetHost(pseudo) is { } host ? host : element; + // an inline box on several lines is hit on them, not in the box around them private static bool Contains(HtmlRenderer.ElementLayoutMetrics metrics, double x, double y) => x >= metrics.BorderBoxX && x <= metrics.BorderBoxX + metrics.BorderBoxWidth && diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs b/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs index 34583ef..d96bde1 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs @@ -1014,7 +1014,7 @@ private static bool IsSameValue(ICssProperty property, ICssProperty? other) => private static bool IsInSubtree(IElement root, IElement element) => ReferenceEquals(root, element) || root.Contains(element) || - (element is IPseudoElement && element.ParentElement is { } host && (ReferenceEquals(root, host) || root.Contains(host))); + (element is IPseudoElement && HitTesting.GetOriginatingElement(element) is var host && (ReferenceEquals(root, host) || root.Contains(host))); // how far the boxes around one were moved since the layout, which its own layout does not know of private (float X, float Y) GetMovedOffset(IElement element) diff --git a/src/AngleSharp.Renderer/HtmlRenderer.cs b/src/AngleSharp.Renderer/HtmlRenderer.cs index e198070..a75bfcf 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.cs @@ -3095,6 +3095,36 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) return estimate; } + // The baselines of a line's items aligned by them (without auto margins on the cross + // axis), from the top of their margin boxes, with the outer cross size of each; null if none is. + Dictionary? ResolveFlexLineBaselines(List<(FlexItemLayoutInfo Item, float FinalMainSize)> lineItems) + { + Dictionary? baselines = null; + + for (var index = 0; index < lineItems.Count; index++) + { + var (item, mainSize) = lineItems[index]; + var alignment = string.Equals(item.AlignSelf, "auto", StringComparison.OrdinalIgnoreCase) ? alignItems : item.AlignSelf; + + if (!alignment.Contains("baseline", StringComparison.OrdinalIgnoreCase) || float.IsNaN(item.CrossMarginStart) || float.IsNaN(item.CrossMarginEnd)) + { + continue; + } + + var crossSize = item.HasDefiniteCrossSize ? item.CrossSize : Math.Max(item.CrossSize, EstimateCrossSize(item, mainSize)); + var baseline = item.Node switch + { + TextRenderNode => ResolveLineHeightBox(inheritedTextStyle, context).Above, + ElementRenderNode element => ResolveFlexItemBaseline(element, mainSize, crossSize, inheritedTextStyle, context, containingWidth), + _ => crossSize, + }; + baselines ??= []; + baselines[index] = (item.CrossMarginStart + baseline, item.CrossMargins + crossSize); + } + + return baselines; + } + // a line's cross size follows from its items' final main sizes (CSS Flexbox §9.4): text // that wraps once shrunk is taller than at the hypothetical size, leaving less free space; // a container without a cross size has none to share, so the lines are only sized as they @@ -3223,6 +3253,25 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) ? entry.Item.CrossSize : Math.Max(entry.Item.CrossSize, EstimateCrossSize(entry.Item, entry.FinalMainSize)))) : 0f; + + // Items aligned by their baselines (CSS Flexbox §8.3, rows only) share the line's: + // where each one's is below the top of its margin box, the line as tall as needed. + var itemBaselines = isRowDirection ? ResolveFlexLineBaselines(lineItems) : null; + var lineBaseline = 0f; + + if (itemBaselines is not null) + { + var below = 0f; + + foreach (var (_, (baseline, outerSize)) in itemBaselines) + { + lineBaseline = Math.Max(lineBaseline, baseline); + below = Math.Max(below, outerSize - baseline); + } + + lineCrossSize = Math.Max(lineCrossSize, lineBaseline + below); + } + finalLineCrossSizes.Add(lineCrossSize); var lineCrossPosition = currentCrossOffset; // a line takes its share of the free space, the only line of a container that can't wrap all of it @@ -3279,6 +3328,10 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) : float.IsNaN(item.CrossMarginEnd) ? freeForMargins / 2f : freeForMargins; } + else if (itemBaselines is not null && itemBaselines.TryGetValue(itemIndex, out var itemBaseline)) + { + itemCrossInLine = lineBaseline - itemBaseline.Baseline + crossMarginStart; + } else if (effectiveAlignment.Equals("center", StringComparison.OrdinalIgnoreCase)) { itemCrossInLine = (crossFreeSpace / 2f) + crossMarginStart; @@ -3746,8 +3799,9 @@ private static void LayoutGridContainer( var rowGap = ResolveRowGap(styleMap, ResolveGapHeightReference(styleMap, containingWidth, paddingTop + paddingBottom + borderTop + borderBottom)); var resolvedColumnGap = columnGap ?? 0f; var resolvedRowGap = rowGap ?? 0f; + // a run of text is an anonymous grid item (e.g. the "A1" of an icon centered by place-items) var gridItems = FlattenDisplayContents(node.Children, context) - .Where(child => child is ElementRenderNode || (child is TextRenderNode textNode && NormalizeWhitespace(textNode.Ref.Data).Length > 0)) + .Where(child => child is ElementRenderNode || (child is TextRenderNode textNode && !ContinuesTextRun(textNode.Ref) && NormalizeWhitespace(GetTextRunData(textNode.Ref)).Length > 0)) .ToList(); CreateStyleMapsInParallel(gridItems.OfType().ToList(), context); // absolutely positioned children take no cell; they are laid out once the grid's size is known @@ -3807,6 +3861,7 @@ private static void LayoutGridContainer( // time around), collect the intrinsic width contributions of items in Auto columns and // grow Auto rows to their items' authored heights (content heights are measured below). var itemPlacements = new List<(ElementRenderNode Element, GridPlacement Column, GridPlacement Row)>(); + var textPlacements = new Dictionary(); var columnContributions = new List<(GridPlacement Column, IntrinsicWidths Widths)>(); // items spanning several rows grow them once all single-span items did, by increasing span // (CSS Grid 1, 11.5.3), or a tall item spread itself over rows a later item fills anyway @@ -3915,6 +3970,51 @@ void MarkPlaced(GridPlacement column, GridPlacement row) foreach (var child in placementItems) { + if (child is TextRenderNode textChild) + { + // an anonymous item has no placement of its own: the next free cell takes it + var textColumn = 0; + var textRow = styleMap.TryGetValue("grid-auto-flow", out var textFlow) && textFlow.Contains("dense", StringComparison.OrdinalIgnoreCase) ? 0 : currentRow; + + while (!CanPlace(textColumn, textRow, 1, 1)) + { + textColumn++; + + if (textColumn + 1 > columns.Count) + { + textColumn = 0; + textRow++; + } + } + + var text = PrepareFlexItemText(textChild, inheritedTextStyle, context); + var textPlacementColumn = new GridPlacement(textColumn, 1); + var textPlacementRow = new GridPlacement(textRow, 1); + textPlacements[textChild] = (text, textPlacementColumn, textPlacementRow); + MarkPlaced(textPlacementColumn, textPlacementRow); + + while (rows.Count < textRow + 1) + { + rows.Add(autoRowDefinitions.Count > 0 ? CloneGridTrackSize(autoRowDefinitions[rows.Count % autoRowDefinitions.Count]) : GridTrackSize.Auto()); + } + + if (columns[textColumn].Kind == GridTrackSizeKind.Auto) + { + columnContributions.Add((textPlacementColumn, ComputeTextIntrinsicWidths(text, inheritedTextStyle, context, out _))); + } + + currentRow = textRow; + currentColumn = textColumn + 1; + + if (currentColumn >= columns.Count) + { + currentColumn = 0; + currentRow++; + } + + continue; + } + if (child is not ElementRenderNode elementChild) { continue; @@ -4086,7 +4186,7 @@ void MarkPlaced(GridPlacement column, GridPlacement row) } var itemStyle = GetOrCreateStyleMap(context, element.Ref, element.ComputedStyle); - if (!isFractionRow && !float.IsNaN(ParseLength(itemStyle, "height", containingWidth, float.NaN, allowAuto: true))) + if (!isFractionRow && !IsPercentageValue(itemStyle.GetValueOrDefault("height")) && !float.IsNaN(ParseLength(itemStyle, "height", containingWidth, float.NaN, allowAuto: true))) { continue; } @@ -4109,6 +4209,28 @@ void MarkPlaced(GridPlacement column, GridPlacement row) } } + foreach (var (text, placementColumn, placementRow) in textPlacements.Values) + { + var rowKind = rows[placementRow.LineIndex].Kind; + + if (rowKind == GridTrackSizeKind.Fixed || (rowKind == GridTrackSizeKind.Fraction && !float.IsNaN(containerHeight))) + { + continue; + } + + var cellWidth = GetGridTrackSpanSize(resolvedColumnSizes, placementColumn.LineIndex, placementColumn.Span, resolvedColumnGap, containingWidth); + var measuredHeight = MeasureFlexItemTextHeight(text, cellWidth, inheritedTextStyle, context); + + if (rowKind == GridTrackSizeKind.Fraction) + { + fractionRowContent[placementRow.LineIndex] = Math.Max(fractionRowContent.GetValueOrDefault(placementRow.LineIndex), measuredHeight); + } + else + { + GrowGridRowsOrDefer(rows, spanningRowGrowths, placementRow, measuredHeight, resolvedRowGap); + } + } + GrowGridRowsBySpan(rows, spanningRowGrowths, resolvedRowGap); if (!float.IsNaN(containerHeight)) @@ -4141,20 +4263,35 @@ void MarkPlaced(GridPlacement column, GridPlacement row) // Pass 2: lay out every item for real, against the now-fully-resolved track sizes. foreach (var child in gridItems) { - if (child is TextRenderNode textNode) + // only the height of the grid is asked for, which is its rows': the items would be laid + // out (with all the grids and flex containers in them) for nothing + if (s_measuringHeightOnly) { - LayoutTextNode(textNode.Ref, containingX, containingWidth, ref cursorY, ref previousBlockMarginBottom, ref suppressNextBlockTopMargin, floats, ref textIndentConsumed, inheritedTextStyle, context, displayList, maxY); continue; } - if (child is not ElementRenderNode elementChild) + if (child is TextRenderNode textNode) { + // an anonymous item is aligned by the container's justify-items and align-items + var (text, textColumn, textRow) = textPlacements[textNode]; + var textCellX = borderBoxX + borderLeft + paddingLeft + columnAlignment.Offset + GetGridTrackOffset(columnSizes, textColumn.LineIndex, resolvedColumnGap + columnAlignment.Spacing); + var textCellY = borderBoxY + borderTop + paddingTop + rowAlignment.Offset + GetGridTrackOffset(rowSizes, textRow.LineIndex, resolvedRowGap + rowAlignment.Spacing); + var textCellWidth = GetGridTrackSpanSize(columnSizes, textColumn.LineIndex, textColumn.Span, resolvedColumnGap + columnAlignment.Spacing, containingWidth); + var textCellHeight = GetGridTrackSpanSize(rowSizes, textRow.LineIndex, textRow.Span, resolvedRowGap + rowAlignment.Spacing, containingWidth); + var anonymousStyle = new Dictionary(StringComparer.Ordinal); + var textJustify = ResolveGridSelfAlignment(anonymousStyle, "justify-self", styleMap, "justify-items"); + var textAlign = ResolveGridSelfAlignment(anonymousStyle, "align-self", styleMap, "align-items"); + var textWidth = textJustify == GridSelfAlignment.Stretch + ? textCellWidth + : Math.Min(textCellWidth, ComputeTextIntrinsicWidths(text, inheritedTextStyle, context, out _).Max); + var textHeight = MeasureFlexItemTextHeight(text, textWidth, inheritedTextStyle, context); + var textX = textCellX + PlaceInGridArea(textJustify, 0f, 0f, textCellWidth, textWidth); + var textCursorY = textCellY + (textAlign == GridSelfAlignment.Stretch ? 0f : PlaceInGridArea(textAlign, 0f, 0f, textCellHeight, textHeight)); + LayoutWrappedText(text, textX, textWidth, ref textCursorY, inheritedTextStyle, context, displayList, maxY, 0f, textSource: textNode.Ref, isTextRun: true); continue; } - // only the height of the grid is asked for, which is its rows': the items would be laid - // out (with all the grids and flex containers in them) for nothing - if (s_measuringHeightOnly) + if (child is not ElementRenderNode elementChild) { continue; } @@ -5455,7 +5592,9 @@ private static float ResolveDefiniteContentHeight(Dictionary sty ///
private static float ResolveGridItemAuthoredHeight(Dictionary styleMap, float fallbackSize) { - var height = styleMap.TryGetValue("height", out var value) && !string.IsNullOrWhiteSpace(value) + // A percentage refers to the grid area, which is what is being sized: it contributes like + // `auto` (the content, measured later), e.g. `height: 100%` cards fill their row. + var height = styleMap.TryGetValue("height", out var value) && !string.IsNullOrWhiteSpace(value) && !IsPercentageValue(value) ? ParseLengthValue(value, fallbackSize, allowAuto: false) : float.NaN; var authored = float.IsNaN(height) ? 0f : Math.Max(0f, height); @@ -5463,7 +5602,8 @@ private static float ResolveGridItemAuthoredHeight(Dictionary st var margins = ZeroIfNaN(ParseLength(styleMap, "margin-top", fallbackSize, 0f, allowAuto: true)) + ZeroIfNaN(ParseLength(styleMap, "margin-bottom", fallbackSize, 0f, allowAuto: true)); - return Math.Max(authored, ParseLength(styleMap, "min-height", fallbackSize, 0f, allowAuto: false)) + margins; + var minimum = IsPercentageValue(styleMap.GetValueOrDefault("min-height")) ? 0f : ParseLength(styleMap, "min-height", fallbackSize, 0f, allowAuto: false); + return Math.Max(authored, minimum) + margins; } private static float MeasureGridItemHeight(ElementRenderNode element, float containingWidth, RenderTextStyle inheritedTextStyle, LayoutContext context, float maxY) @@ -6259,6 +6399,21 @@ private static string GetJustifyContent(Dictionary styleMap) : "flex-start"; } + /// + /// The baseline of a flex item in a row, from the top of its border box: that of its first + /// line of text, else the bottom edge of its border box (CSS Flexbox §8.5). + /// + private static float ResolveFlexItemBaseline(ElementRenderNode element, float borderBoxWidth, float borderBoxHeight, RenderTextStyle inheritedTextStyle, LayoutContext context, float containingWidth) + { + if (IsReplacedElement(element.Ref) || !HoldsLineContent(element, context)) + { + return borderBoxHeight; + } + + var trial = TrialLayout(element, borderBoxWidth, inheritedTextStyle, context, borderBoxWidth, isAtomicInline: false, isFlexOrGridItem: true, percentageBasisWidth: containingWidth); + return trial is { FirstBaselineY: { } baseline, Metrics: { } metrics } ? baseline - metrics.BorderBoxY : borderBoxHeight; + } + private static string GetAlignItems(Dictionary styleMap) { return styleMap.TryGetValue("align-items", out var value) && !string.IsNullOrWhiteSpace(value) diff --git a/src/AngleSharp.Renderer/Rendering/HitTestMap.cs b/src/AngleSharp.Renderer/Rendering/HitTestMap.cs index 5966337..ee571fd 100644 --- a/src/AngleSharp.Renderer/Rendering/HitTestMap.cs +++ b/src/AngleSharp.Renderer/Rendering/HitTestMap.cs @@ -167,7 +167,7 @@ private HitTestMap(Entry[] entries, float offsetY = 0f) /// /// Gets the elements that can be hit, top-most first. /// - public IEnumerable Elements => _entries.SelectMany(static m => m.Subframe is { } frame ? frame.HitTestMap.Elements.Prepend(m.Element) : [m.Element]); + public IEnumerable Elements => _entries.SelectMany(static m => m.Subframe is { } frame ? frame.HitTestMap.Elements.Prepend(m.Element) : [HitTesting.GetOriginatingElement(m.Element)]); /// /// Finds the element painted top-most at the given point. @@ -191,7 +191,8 @@ private HitTestMap(Entry[] entries, float offsetY = 0f) return inner with { FrameOrigin = (inner.FrameOrigin.X + entry.Viewport.X, inner.FrameOrigin.Y + entry.Viewport.Y + (y - entryY)), IsInScrollContainer = true }; } - return new HitTestResult(entry.Element, entry.Cursor, entry.IsInScrollContainer); + // generated content is hit as the element it belongs to (its cursor is its own) + return new HitTestResult(HitTesting.GetOriginatingElement(entry.Element), entry.Cursor, entry.IsInScrollContainer); } } @@ -302,7 +303,7 @@ internal static HitTestMap Create(IDocument document, IReadOnlyDictionary roots, IElement element) { - var host = element is IPseudoElement ? element.ParentElement : element; + var host = HitTesting.GetOriginatingElement(element); foreach (var root in roots) { @@ -466,7 +467,7 @@ private double GetOrder(IElement element) // generated content paints with its originating element: ::before ahead of the // element's children, ::after (and anything else) behind them - if (element is IPseudoElement pseudo && element.ParentElement is { } host && order.TryGetValue(host, out var hostIndex)) + if (element is IPseudoElement pseudo && CssAnimationTracker.GetHost(pseudo) is { } host && order.TryGetValue(host, out var hostIndex)) { return pseudo.PseudoName.Contains("before", StringComparison.OrdinalIgnoreCase) || pseudo.PseudoName.Contains("marker", StringComparison.OrdinalIgnoreCase) ? hostIndex.Start + 0.5 From b99dd8e0e9398290ab63632722ba0c8bc4b6bed2 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 16:05:53 +0100 Subject: [PATCH 06/23] Updated version --- CHANGELOG.md | 15 +++++++++++++-- src/AngleSharp.Renderer.Docs/package.json | 2 +- .../AngleSharp.Renderer.csproj | 2 +- src/Directory.Build.props | 2 +- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bec35a1..58df16f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# 0.12.1 +# 0.13.0 Released on tbd. @@ -16,9 +16,20 @@ Released on tbd. - Fixed generated content being hit as the pseudo-element (in the hit-test map, `elementFromPoint` and for `:hover`) instead of its element, e.g. a link's `::after` stretched over a whole card did not act as the link - Fixed grid items with a percentage `height` (e.g. `height: 100%` cards) in an auto row being as tall as the grid is wide; such a height contributes as `auto` to the row and then fills it - Fixed text right in a grid container (e.g. the label of an icon with `display: grid; place-items: center`) not being an anonymous grid item: it stayed at the top left instead of being placed in a cell and aligned +- Fixed `row-reverse` and `column-reverse` packing the items at the end without reversing their order +- Fixed `grid-auto-columns` being ignored for implicit columns +- Added `subgrid` for `grid-template-columns` and `grid-template-rows` (tracks, gaps and line names of the parent grid, row sizes from the subgrid's items) +- Fixed the edges of a gradient `border-image` of a box with a fractional size being drawn with seams and a washed out side +- Fixed `::marker` and `::first-line` colors being ignored +- Fixed an absolutely positioned box with `height: fit-content` (e.g. a popover) being stretched between `top` and `bottom`, and centering one of an automatic height with `margin: auto` +- Fixed `scrollWidth` and `scrollHeight` leaving out text extending beyond its box (e.g. cut off by an ellipsis) - Updated the document of an iframe to keep the render device of its browsing context, if it has one of its own -- Added `align-items: baseline` (and `align-self`) for flex items in a row: an item without text sits on the baseline with the bottom of its border box (e.g. a rule after a heading's text), where it was at the top of the line +- Added color hints and color interpolation methods (e.g. `in oklch`, `in hsl longer hue`) of gradients +- Added `background-clip: text` - Added `object` elements showing an image instead of their fallback content +- Added `align-items: baseline` (and `align-self`) for flex items in a row: an item without text sits on the baseline with the bottom of its border box (e.g. a rule after a heading's text), where it was at the top of the line +- Added `getImageData()`, `putImageData()` and `createImageData()` of the canvas (`ImageData`) +- Added `paint()` background images of the CSS Painting API (painted by AngleSharp.Css's paint worklets); requires AngleSharp.Css 1.5.0 # 0.12.0 diff --git a/src/AngleSharp.Renderer.Docs/package.json b/src/AngleSharp.Renderer.Docs/package.json index ff7ac87..f55a5c3 100644 --- a/src/AngleSharp.Renderer.Docs/package.json +++ b/src/AngleSharp.Renderer.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/renderer", - "version": "0.12.1", + "version": "0.13.0", "preview": true, "description": "The doclet for the AngleSharp.Renderer documentation.", "keywords": [ diff --git a/src/AngleSharp.Renderer/AngleSharp.Renderer.csproj b/src/AngleSharp.Renderer/AngleSharp.Renderer.csproj index 50cbaf1..6b0d6b6 100644 --- a/src/AngleSharp.Renderer/AngleSharp.Renderer.csproj +++ b/src/AngleSharp.Renderer/AngleSharp.Renderer.csproj @@ -21,7 +21,7 @@ true snupkg 1.10.0 - 1.4.1 + 1.5.0 diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 60670d6..230b010 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ Adds rendering functionality to the core AngleSharp library. AngleSharp.Renderer - 0.12.1 + 0.13.0 enable latest true From a5c6ed93815eda5229e703d038b7728b99041376 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 16:06:22 +0100 Subject: [PATCH 07/23] Rendering fixes for Houdini and some test pages --- .../RendererTestsPageTests.cs | 162 +++++ .../ElementCssomViewExtensions.cs | 14 + .../HtmlRenderer.Incremental.cs | 3 +- .../HtmlRenderer.Inline.cs | 32 +- .../HtmlRenderer.PaintWorklets.cs | 177 +++++ src/AngleSharp.Renderer/HtmlRenderer.cs | 632 ++++++++++++++++-- .../Rendering/Canvas2DRenderingContext.cs | 83 +++ .../CanvasRenderingContext2DExtensions.cs | 29 + .../Rendering/ImageData.cs | 57 ++ .../Rendering/RenderPaint.cs | 30 +- .../Skia/GradientInterpolation.cs | 463 +++++++++++++ .../Skia/SkiaRenderBackend.Paint.cs | 22 +- .../Skia/SkiaRenderBackend.cs | 33 +- 13 files changed, 1673 insertions(+), 64 deletions(-) create mode 100644 src/AngleSharp.Renderer.Tests/RendererTestsPageTests.cs create mode 100644 src/AngleSharp.Renderer/HtmlRenderer.PaintWorklets.cs create mode 100644 src/AngleSharp.Renderer/Rendering/ImageData.cs create mode 100644 src/AngleSharp.Renderer/Skia/GradientInterpolation.cs diff --git a/src/AngleSharp.Renderer.Tests/RendererTestsPageTests.cs b/src/AngleSharp.Renderer.Tests/RendererTestsPageTests.cs new file mode 100644 index 0000000..aa8001a --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/RendererTestsPageTests.cs @@ -0,0 +1,162 @@ +using AngleSharp.Css; +using AngleSharp.Dom; + +namespace AngleSharp.Renderer.Tests; + +/// +/// Layouts of the renderer test pages (anglesharp-tests.anglevisions.com/renderer/): reversed +/// flex lines, implicit grid tracks, subgrids and boxes sized by their content between offsets. +/// +public sealed class RendererTestsPageTests +{ + [Fact] + public async Task RowReverse_PlacesTheFirstItemAtTheEnd_AfterOrdering() + { + var document = await ParseAsync(""" +
+
A
+
B
+
first
+
+ """); + + Assert.Equal(320d, Left(document, "#first")); + Assert.Equal(240d, Left(document, "#a")); + Assert.Equal(160d, Left(document, "#b")); + } + + [Fact] + public async Task ImplicitColumns_AreSizedByGridAutoColumns() + { + var document = await ParseAsync(""" +
+
near
+
far
+
+ """); + + var far = document.QuerySelector("#far")!.GetBoundingClientRect(); + Assert.Equal(250d, far.Left); + Assert.Equal(25d, far.Top); + Assert.Equal(50d, far.Width); + } + + [Fact] + public async Task SubgridColumns_AdoptTheTracksOfTheParent() + { + var document = await ParseAsync(""" +
+
0
+
+
a
b
c
+
+
+ """); + + Assert.Equal(100d, document.QuerySelector("#a")!.GetBoundingClientRect().Width); + Assert.Equal(150d, document.QuerySelector("#b")!.GetBoundingClientRect().Width); + Assert.Equal(300d, Left(document, "#c")); + } + + [Fact] + public async Task SubgridColumns_KeepTheirLinesWithAGapOfTheirOwn() + { + var document = await ParseAsync(""" +
+
+
a
b
c
+
+
+ """); + + var b = document.QuerySelector("#b")!.GetBoundingClientRect(); + Assert.Equal(110d, b.Left); + Assert.Equal(120d, b.Width); + } + + [Fact] + public async Task SubgridRows_AreSizedByTheItemsOfAllSubgrids() + { + var document = await ParseAsync(""" +
+
+

Short

One

footer
+
+
+

Tall

One

footer
+
+
+ """); + + Assert.Equal(Top(document, "#f2"), Top(document, "#f1")); + Assert.Equal(80d, Top(document, "#f1")); + } + + [Fact] + public async Task FixedBoxOfFitContentHeight_IsCenteredBetweenItsOffsets() + { + var document = await ParseAsync(""" +
+
+
+ """); + + var rect = document.QuerySelector("#pop")!.GetBoundingClientRect(); + Assert.Equal(40d, rect.Height); + Assert.Equal(60d, rect.Top); + Assert.Equal(70d, rect.Left); + } + + [Fact] + public async Task ScrollWidth_IncludesTextCutOffByAnEllipsis() + { + var document = await ParseAsync("
A very long label that does not fit into its box
"); + + var box = document.QuerySelector("#box")!; + Assert.Equal(100, box.GetClientWidth()); + Assert.True(box.GetScrollWidth() > 200, $"scrollWidth {box.GetScrollWidth()}"); + } + + [Fact] + public async Task GetImageData_ReadsWhatWasDrawn() + { + var document = await ParseAsync(""); + var canvas = (AngleSharp.Html.Dom.IHtmlCanvasElement)document.QuerySelector("#c")!; + var context = new Canvas2DRenderingContext(canvas); + var gradient = context.CreateLinearGradient(0, 0, 100, 0); + gradient.AddColorStop(0, "rgb(255, 0, 0)"); + gradient.AddColorStop(1, "rgb(0, 0, 255)"); + context.FillStyle = gradient; + context.FillRect(0, 0, 101, 1); + + var data = context.GetImageData(50, 0, 1, 1).Data; + + Assert.InRange((int)data[0], 125, 131); + Assert.InRange((int)data[2], 125, 131); + Assert.Equal(255, data[3]); + + context.PutImageData(new AngleSharp.Media.Dom.ImageData(1, 1), 50, 0); + Assert.Equal(0, context.GetImageData(50, 0, 1, 1).Data[3]); + } + + private static double Left(IDocument document, string selector) => + document.QuerySelector(selector)!.GetBoundingClientRect().Left; + + private static double Top(IDocument document, string selector) => + document.QuerySelector(selector)!.GetBoundingClientRect().Top; + + private static async Task ParseAsync(string body) + { + var context = BrowsingContext.New(Configuration.Default + .WithCss() + .WithRenderDevice(new DefaultRenderDevice + { + ViewPortWidth = 240, + ViewPortHeight = 160, + DeviceWidth = 240, + DeviceHeight = 160, + FontSize = 16, + })); + return await context.OpenAsync(request => request.Content("" + body + "")); + } +} diff --git a/src/AngleSharp.Renderer/ElementCssomViewExtensions.cs b/src/AngleSharp.Renderer/ElementCssomViewExtensions.cs index e8ccf70..71e7a40 100644 --- a/src/AngleSharp.Renderer/ElementCssomViewExtensions.cs +++ b/src/AngleSharp.Renderer/ElementCssomViewExtensions.cs @@ -660,6 +660,13 @@ internal static (int Width, int Height) GetScrollExtents( bottomExtent = Math.Max(bottomExtent, own.Y + own.Height + elementMetrics.MarginBottom); } + // lines of text extending beyond the box (e.g. not wrapped) + if (!float.IsNaN(elementMetrics.TextRight)) + { + rightExtent = Math.Max(rightExtent, elementMetrics.BorderBoxX + elementMetrics.TextRight + scrollLeft); + bottomExtent = Math.Max(bottomExtent, elementMetrics.BorderBoxY + elementMetrics.TextBottom + scrollTop); + } + foreach (var (candidate, candidateMetrics) in metricsMap) { // content clipped by a scroll container (or any clipping box) inside is no overflow of @@ -671,6 +678,13 @@ internal static (int Width, int Height) GetScrollExtents( rightExtent = Math.Max(rightExtent, candidateMetrics.BorderBoxX + candidateMetrics.BorderBoxWidth + scrollLeft); bottomExtent = Math.Max(bottomExtent, candidateMetrics.BorderBoxY + candidateMetrics.BorderBoxHeight + scrollTop); + + // as well as text of it beyond its box (unless it clips that) + if (!float.IsNaN(candidateMetrics.TextRight) && !(styleMaps.TryGetValue(candidate, out var candidateStyle) && HtmlRenderer.ClipsOverflow(candidateStyle))) + { + rightExtent = Math.Max(rightExtent, candidateMetrics.BorderBoxX + candidateMetrics.TextRight + scrollLeft); + bottomExtent = Math.Max(bottomExtent, candidateMetrics.BorderBoxY + candidateMetrics.TextBottom + scrollTop); + } } var scrollWidth = (int)Math.Round(Math.Max(clientWidth, rightExtent - paddingBoxLeft)); diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs b/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs index d96bde1..96da97c 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Incremental.cs @@ -3161,8 +3161,9 @@ private bool LooksTheSameToContainer(ElementRenderNode node, LayoutEntry entry, (float.IsNaN(flex.EstimatedCrossSize) || EstimateFlexItemCrossSize(node, flex.FinalMainSize, item.IsRowDirection, entry.TextStyle, _context, flex.CrossAvailable, flex.RelativeTo) == flex.EstimatedCrossSize); } + // (what its text extends to is in it, as its box is laid out again) private static bool HasSameBox(ElementLayoutMetrics first, ElementLayoutMetrics second) => - first with { Layer = default, Sticky = null } == second with { Layer = default, Sticky = null }; + first with { Layer = default, Sticky = null, TextRight = 0f, TextBottom = 0f } == second with { Layer = default, Sticky = null, TextRight = 0f, TextBottom = 0f }; // The nearest sticky ancestor, which is what the metrics of a box in it name. private IElement? FindStickyAncestor(IElement element) diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs b/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs index d7594f2..f7fe556 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Inline.cs @@ -412,7 +412,8 @@ private sealed class InlinePiece public string Text { get; init; } = string.Empty; - public RenderTextStyle Style { get; init; } + // set again for the first line, which ::first-line styles + public RenderTextStyle Style { get; set; } /// Identifies pieces that share one resolved text style, so they can be painted as one run. public int StyleId { get; init; } @@ -1124,6 +1125,8 @@ void PlaceFloat(InlinePiece piece) if (clamped || (hasLineBox && textStyle.TextOverflow == TextOverflowMode.Ellipsis && MeasureLinePieces(linePieces) > available + 0.01f)) { + // what the ellipsis cuts off still overflows the box (scrollWidth) + NoteTextExtent(lineLeft + indent + MeasureLinePieces(linePieces), lineTop + pendingBlockMargin); TruncateLineWithEllipsis(linePieces, available, textStyle, context, forceEllipsis: clamped); } @@ -1136,6 +1139,11 @@ void PlaceFloat(InlinePiece piece) lineTop += pendingBlockMargin; pendingBlockMargin = MarginStrut.Zero; + if (lineCount == 0 && textStyle.FirstLineColor is { } firstLineColor) + { + ApplyFirstLineColor(linePieces, textStyle.Color, firstLineColor); + } + var lineHeight = EmitLine( linePieces, lineLeft + indent, @@ -1722,6 +1730,25 @@ private static bool HasContentBeforeNextBlock(List pieces, int star /// /// Positions and paints one line box and returns its height. /// + /// + /// The color of `::first-line` for the text of the first line, which inherits it (CSS + /// Pseudo-Elements 4 §2.1); what has a color of its own keeps it. + /// + private static void ApplyFirstLineColor(List linePieces, RenderColor blockColor, RenderColor color) + { + foreach (var piece in linePieces) + { + if (piece.Style.Color == blockColor) + { + piece.Style = piece.Style with + { + Color = color, + DecorationColor = piece.Style.DecorationColor == blockColor ? color : piece.Style.DecorationColor, + }; + } + } + } + private static float EmitLine( List linePieces, float lineLeft, @@ -1767,6 +1794,8 @@ private static float EmitLine( } } + var lineRight = x; + // Vertical metrics: the block's own strut, the line-height box of every inline box and of // its text, and every atomic inline's margin box, all aligned on one baseline, each shifted // by its `vertical-align`. Boxes at the top or bottom edge of the line are aligned among @@ -2034,6 +2063,7 @@ visualOrder[runEnd].Kind is InlinePieceKind.Text or InlinePieceKind.Space && // Recorded after the atomic children so it is this line's baseline - not one they recorded // while being laid out - that an enclosing inline-block aligns with. RecordTextBaseline(baselineY); + NoteTextExtent(lineRight, lineTop + lineHeight); return lineHeight; } diff --git a/src/AngleSharp.Renderer/HtmlRenderer.PaintWorklets.cs b/src/AngleSharp.Renderer/HtmlRenderer.PaintWorklets.cs new file mode 100644 index 0000000..0038852 --- /dev/null +++ b/src/AngleSharp.Renderer/HtmlRenderer.PaintWorklets.cs @@ -0,0 +1,177 @@ +namespace AngleSharp.Renderer; + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using AngleSharp.Css.Painting; +using AngleSharp.Css.RenderTree; +using AngleSharp.Dom; +using AngleSharp.Html.Dom; +using AngleSharp.Html.Parser; +using AngleSharp.Renderer.Rendering; + +/// +/// The `paint()` images of the CSS Painting API: a paint worklet (registered with +/// AngleSharp.Css's ) draws them for the size of the box when it is +/// painted, recording what it draws, which is replayed on a canvas here. +/// +public partial class HtmlRenderer +{ + /// + /// A `paint()` layer of a background, drawn once the size of the box is known. + /// + private sealed record PaintWorkletLayer(int Index) : RenderPaint; + + /// + /// The box whose decorations are painted, which the paint worklets get the style of. + /// + [ThreadStatic] + private static ElementRenderNode? s_paintedNode; + + // a document of its own for the canvases the images are drawn on, which no page shows + [ThreadStatic] + private static IDocument? s_paintDocument; + + /// + /// Draws the paint() image of the layer (the given one of the property's paint() images) for + /// an area of the given size, or returns null if there is none (e.g. no worklet registered + /// the name yet, or it failed). + /// + private static RenderImagePaint? ResolvePaintWorkletLayer(PaintWorkletLayer layer, string property, float width, float height) + { + if (s_paintedNode is not { } node || width <= 0f || height <= 0f) + { + return null; + } + + IReadOnlyList images; + + try + { + images = node.DrawPaintImages(property, new PaintSize(width, height)); + } + catch (Exception) + { + return null; + } + + if (layer.Index >= images.Count || images[layer.Index] is not { Context: RecordingPaintRenderingContext2D recording } image) + { + return null; + } + + var rendered = RasterizePaintImage(recording.Commands, width, height, image.DevicePixelRatio); + return rendered is null + ? null + : new RenderImagePaint(rendered, false, false, RenderBackgroundPositionComponent.Zero, RenderBackgroundPositionComponent.Zero, RenderBackgroundSize.Auto); + } + + private static RenderedImage? RasterizePaintImage(IReadOnlyList commands, float width, float height, double ratio) + { + var pixelWidth = Math.Max(1, (int)Math.Ceiling(width * ratio)); + var pixelHeight = Math.Max(1, (int)Math.Ceiling(height * ratio)); + var document = s_paintDocument ??= new HtmlParser().ParseDocument(string.Empty); + + if (document.CreateElement(TagNames.Canvas) is not IHtmlCanvasElement canvas) + { + return null; + } + + canvas.Width = pixelWidth; + canvas.Height = pixelHeight; + var context = new Canvas2DRenderingContext(canvas); + context.Scale(ratio, ratio); + + foreach (var command in commands) + { + try + { + Replay(context, command); + } + catch (Exception) + { + // what can't be replayed is left out, as an invalid call of a script would be + } + } + + // the image is as large as the area, its pixels as many as the device has there + return new RenderedImage(context.ToImage("image/png"), (int)Math.Ceiling(width), (int)Math.Ceiling(height), "image/png"); + } + + private static void Replay(Canvas2DRenderingContext context, PaintCommand command) + { + var args = command.Arguments; + double D(int index) => Convert.ToDouble(args[index], CultureInfo.InvariantCulture); + string S(int index) => Convert.ToString(args[index], CultureInfo.InvariantCulture) ?? string.Empty; + string Rule(int index) => args.Count > index && args[index] is CanvasFillRule rule && rule == CanvasFillRule.EvenOdd ? "evenodd" : "nonzero"; + + switch (command.Name) + { + case "save": context.Save(); break; + case "restore": context.Restore(); break; + case "reset": context.Reset(); break; + case "scale": context.Scale(D(0), D(1)); break; + case "rotate": context.Rotate(D(0)); break; + case "translate": context.Translate(D(0), D(1)); break; + case "transform": context.Transform(D(0), D(1), D(2), D(3), D(4), D(5)); break; + case "setTransform": context.SetTransform(D(0), D(1), D(2), D(3), D(4), D(5)); break; + case "resetTransform": context.ResetTransform(); break; + case "globalAlpha": context.GlobalAlpha = D(0); break; + case "globalCompositeOperation": context.GlobalCompositeOperation = S(0); break; + case "imageSmoothingEnabled": context.ImageSmoothingEnabled = Convert.ToBoolean(args[0], CultureInfo.InvariantCulture); break; + case "fillStyle": context.FillStyle = ToCanvasStyle(context, args[0]); break; + case "strokeStyle": context.StrokeStyle = ToCanvasStyle(context, args[0]); break; + case "shadowOffsetX": context.ShadowOffsetX = D(0); break; + case "shadowOffsetY": context.ShadowOffsetY = D(0); break; + case "shadowBlur": context.ShadowBlur = D(0); break; + case "shadowColor": context.ShadowColor = S(0); break; + case "clearRect": context.ClearRect(D(0), D(1), D(2), D(3)); break; + case "fillRect": context.FillRect(D(0), D(1), D(2), D(3)); break; + case "strokeRect": context.StrokeRect(D(0), D(1), D(2), D(3)); break; + case "beginPath": context.BeginPath(); break; + case "fill" when args.Count <= 1: context.Fill(Rule(0)); break; + case "stroke" when args.Count == 0: context.Stroke(); break; + case "clip" when args.Count <= 1: context.Clip(Rule(0)); break; + case "lineWidth": context.LineWidth = D(0); break; + case "lineCap": context.LineCap = S(0); break; + case "lineJoin": context.LineJoin = S(0); break; + case "miterLimit": context.MiterLimit = D(0); break; + case "setLineDash": context.SetLineDash(args[0] as IEnumerable); break; + case "lineDashOffset": context.LineDashOffset = D(0); break; + case "closePath": context.ClosePath(); break; + case "moveTo": context.MoveTo(D(0), D(1)); break; + case "lineTo": context.LineTo(D(0), D(1)); break; + case "quadraticCurveTo": context.QuadraticCurveTo(D(0), D(1), D(2), D(3)); break; + case "bezierCurveTo": context.BezierCurveTo(D(0), D(1), D(2), D(3), D(4), D(5)); break; + case "arcTo": context.ArcTo(D(0), D(1), D(2), D(3), D(4)); break; + case "rect": context.Rect(D(0), D(1), D(2), D(3)); break; + case "roundRect": context.RoundRect(D(0), D(1), D(2), D(3), args[4] is double[] { Length: > 0 } radii ? radii[0] : 0d); break; + case "arc": context.Arc(D(0), D(1), D(2), D(3), D(4), Convert.ToBoolean(args[5], CultureInfo.InvariantCulture)); break; + case "ellipse": context.Ellipse(D(0), D(1), D(2), D(3), D(4), D(5), D(6), Convert.ToBoolean(args[7], CultureInfo.InvariantCulture)); break; + } + } + + private static object ToCanvasStyle(Canvas2DRenderingContext context, object style) + { + if (style is not AngleSharp.Css.Painting.CanvasGradient gradient) + { + return Convert.ToString(style, CultureInfo.InvariantCulture) ?? string.Empty; + } + + var p = gradient.Parameters; + var result = gradient.Kind switch + { + CanvasGradientKind.Radial => context.CreateRadialGradient(p[0], p[1], p[2], p[3], p[4], p[5]), + CanvasGradientKind.Conic => context.CreateConicGradient(p[0], p[1], p[2]), + _ => context.CreateLinearGradient(p[0], p[1], p[2], p[3]), + }; + + foreach (var stop in gradient.ColorStops) + { + result.AddColorStop(stop.Offset, stop.Color); + } + + return result; + } +} diff --git a/src/AngleSharp.Renderer/HtmlRenderer.cs b/src/AngleSharp.Renderer/HtmlRenderer.cs index a75bfcf..3a0f1a4 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.cs @@ -192,7 +192,9 @@ internal readonly record struct ElementLayoutMetrics( float InsetLeft = float.NaN, float InsetRight = float.NaN, float InsetTop = float.NaN, - float InsetBottom = float.NaN) + float InsetBottom = float.NaN, + float TextRight = float.NaN, + float TextBottom = float.NaN) { /// The box scripts see, relative to the border box here: the root element's own one (see LayoutDocument). public RenderRect ReportedBox => OwnBox is { } own @@ -404,6 +406,23 @@ private static HitTestLayer ResolveHitTestLayer(IElement element, Dictionary + /// How far the lines of text laid out for the element being laid out extend, which its + /// scrollable overflow includes (e.g. text that does not wrap in a narrower box). + ///
+ [ThreadStatic] + private static (float Right, float Bottom)? s_textExtent; + + private static void NoteTextExtent(float right, float bottom) + { + if (s_trialDepth == 0 && !s_measuringHeightOnly && !float.IsNaN(right) && !float.IsNaN(bottom)) + { + s_textExtent = s_textExtent is { } current + ? (Math.Max(current.Right, right), Math.Max(current.Bottom, bottom)) + : (right, bottom); + } + } + private static void RecordLayoutMetrics( IElement element, float borderBoxX, @@ -443,6 +462,9 @@ private static void RecordLayoutMetrics( paddingBottom, IsViewportAnchored: s_viewportAnchorDepth > 0, Sticky: s_stickyElement, + // relative to the box, which is moved (e.g. by the scroll position of its container) + TextRight: s_textExtent is { } text ? text.Right - borderBoxX : float.NaN, + TextBottom: s_textExtent is { } textBox ? textBox.Bottom - borderBoxY : float.NaN, MarginLeft: marginLeft, MarginRight: marginRight, MarginTop: marginTop, @@ -1269,7 +1291,20 @@ private static void LayoutNode( return; } - LayoutStickyAwareElement(element, containingX, containingY, containingWidth, ref cursorY, ref previousBlockMarginBottom, ref suppressNextBlockTopMargin, floats, ref textIndentConsumed, textStyle, context, displayList, maxY, isFlexItem, isRowDirection, flexMainSize, flexCrossSize, containingHeight, positionedContainingX, positionedContainingY, positionedContainingWidth, positionedContainingHeight, forcedBorderBoxWidth, isAtomicInline, forcedBorderBoxHeight, contentOffsetY, mainAxisMarginsPlaced, crossAxisMarginsPlaced, percentageBasisWidth); + // the text of its content is noted for this element only (see NoteTextExtent) + var outerTextExtent = s_textExtent; + s_textExtent = null; + + try + { + LayoutStickyAwareElement(element, containingX, containingY, containingWidth, ref cursorY, ref previousBlockMarginBottom, ref suppressNextBlockTopMargin, floats, ref textIndentConsumed, textStyle, context, displayList, maxY, isFlexItem, isRowDirection, flexMainSize, flexCrossSize, containingHeight, positionedContainingX, positionedContainingY, positionedContainingWidth, positionedContainingHeight, forcedBorderBoxWidth, isAtomicInline, forcedBorderBoxHeight, contentOffsetY, mainAxisMarginsPlaced, crossAxisMarginsPlaced, percentageBasisWidth); + } + finally + { + // the boxes around it take its text from its metrics (see GetScrollExtents) + s_textExtent = outerTextExtent; + } + return; default: return; @@ -1360,6 +1395,12 @@ private static void LayoutElement( var isInlineBlock = IsInlineBlock(computedStyle); var currentTextStyle = ResolveTextStyle(styleMap, inheritedTextStyle, context); + // the first line of a block is its own (::first-line), the inline boxes in it inherit it + if (renderAsBlock || isInlineBlock) + { + currentTextStyle = currentTextStyle with { FirstLineColor = ResolvePseudoElementColor(element, context, "first-line") }; + } + if (formControlKind != FormControlKind.None) { ApplyFormControlDefaults(formControlKind, element, styleMap, currentTextStyle, context); @@ -1804,7 +1845,9 @@ private static void LayoutElement( // between them in its containing block (CSS 2.1 §10.6.4); a replaced one keeps its own height. var stretchContainingHeight = isFixed ? context.Height : isAbsolute ? positionedContainingHeight : float.NaN; - if (float.IsNaN(resolvedContentHeight) && !float.IsNaN(stretchContainingHeight) && !IsReplacedElement(element)) + // (one sized by its content, e.g. a popover's height: fit-content, is not stretched) + if (float.IsNaN(resolvedContentHeight) && !float.IsNaN(stretchContainingHeight) && !IsReplacedElement(element) && + GetContentSizeKeyword(styleMap, "height") is null) { var stretchTop = ParseLength(styleMap, "top", stretchContainingHeight, float.NaN, allowAuto: true); var stretchBottom = ParseLength(styleMap, "bottom", stretchContainingHeight, float.NaN, allowAuto: true); @@ -1851,10 +1894,12 @@ private static void LayoutElement( borderBoxX = absoluteContainingX + absoluteContainingWidth - rightOffset - positionedMargins.Right - positionedBorderBoxWidth; } - // a box placed by its bottom needs its height first, which an auto one only has once laid out + // a box placed by its bottom needs its height first, which an auto one only has once laid + // out, as does one centered by auto margins between its offsets (e.g. a popover) var placementHeight = positionedBorderBoxHeight; + var centersVertically = (autoTopMargin || autoBottomMargin) && !IsAutoOffset(styleMap, "top") && !float.IsNaN(bottomOffset); - if ((isAbsolute || isFixed) && float.IsNaN(placementHeight) && IsAutoOffset(styleMap, "top") && !float.IsNaN(bottomOffset) && + if ((isAbsolute || isFixed) && float.IsNaN(placementHeight) && (IsAutoOffset(styleMap, "top") || centersVertically) && !float.IsNaN(bottomOffset) && (isFixed || !float.IsNaN(positionedContainingHeight)) && (s_measuringPositioned ??= new(ReferenceEqualityComparer.Instance)).Add(element)) { // its own scope, so the trial is not held back for the height of the container @@ -1896,10 +1941,9 @@ private static void LayoutElement( var verticalContainingHeight = isFixed ? context.Height - (2f * context.Padding) : positionedContainingHeight; - if ((isAbsolute || isFixed) && (autoTopMargin || autoBottomMargin) && !IsAutoOffset(styleMap, "top") && !float.IsNaN(bottomOffset) && - !float.IsNaN(verticalContainingHeight) && !float.IsNaN(positionedBorderBoxHeight)) + if ((isAbsolute || isFixed) && centersVertically && !float.IsNaN(verticalContainingHeight) && !float.IsNaN(placementHeight)) { - var freeHeight = verticalContainingHeight - topOffset - bottomOffset - positionedMargins.Top - positionedMargins.Bottom - positionedBorderBoxHeight; + var freeHeight = verticalContainingHeight - topOffset - bottomOffset - positionedMargins.Top - positionedMargins.Bottom - placementHeight; borderBoxY += !autoTopMargin ? 0f : autoBottomMargin ? freeHeight / 2f : freeHeight; } @@ -2525,7 +2569,20 @@ private static (ElementEffectScopes Effects, (float X, float Y) ContentScroll) P BlendsInside(displayList, boxPaintInsertIndex)); var createsStackingContext = HasExplicitZIndex(styleMap) || effects.CreatesStackingContext; - PaintBoxDecorations(decorationBuffer, context, styleMap, node, box, borderBox, border, padding, fillsTransparentBackground: false); + // `background-clip: text` clips to the text of its content, which is laid out by now + var outerClipTexts = s_backgroundClipTexts; + s_backgroundClipTexts = HasTextBackgroundClip(box, styleMap) + ? displayList.Commands.Skip(boxPaintInsertIndex).OfType().ToList() + : null; + + try + { + PaintBoxDecorations(decorationBuffer, context, styleMap, node, box, borderBox, border, padding, fillsTransparentBackground: false); + } + finally + { + s_backgroundClipTexts = outerClipTexts; + } // Per spec, overflow clips at the padding edge - content can extend into the padding but // not past it - so the clip rect is the padding box, not the border box. Border and outline @@ -3279,7 +3336,6 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) ? containerCrossSize : lineCrossSize + stretchedLineSpace; - var mainOffset = isReverseDirection ? containerMainSize - lineMainStart - lineMainSize : lineMainStart; var currentMainOffset = 0f; for (var itemIndex = 0; itemIndex < lineItems.Count; itemIndex++) @@ -3363,9 +3419,10 @@ float EstimateCrossSize(FlexItemLayoutInfo item, float mainSize) var marginStart = float.IsNaN(item.MainMarginStart) ? autoMarginSize : item.MainMarginStart; var marginEnd = float.IsNaN(item.MainMarginEnd) ? autoMarginSize : item.MainMarginEnd; - var itemOffset = (isReverseDirection - ? mainOffset + currentMainOffset - : lineMainStart + currentMainOffset) + marginStart; + // a reversed line runs from the main-end edge: the first item is placed there + var itemOffset = isReverseDirection + ? containerMainSize - lineMainStart - currentMainOffset - marginEnd - finalMainSize + : lineMainStart + currentMainOffset + marginStart; var childX = isRowDirection ? containingX + itemOffset : containingX + itemCrossPosition; var childY = isRowDirection ? containingY + itemCrossPosition : containingY + itemOffset; var childWidth = isRowDirection ? finalMainSize : resolvedCrossSize; @@ -3816,8 +3873,30 @@ private static void LayoutGridContainer( var columnLineNames = new Dictionary>(StringComparer.Ordinal); var rowLineNames = new Dictionary>(StringComparer.Ordinal); var columns = ParseGridTrackListStructured(explicitGridTemplateColumns, containingWidth, resolvedColumnGap, CountSpannedGridColumns(gridItems, context), columnLineNames); + // a subgrid takes the tracks it spans in its parent grid (CSS Grid 2 §9) + s_subgridTracks.TryGetValue(node.Ref, out var parentTracks); - if (columns.Count == 0) + if (IsSubgridValue(explicitGridTemplateColumns) && parentTracks?.Columns is { } parentColumns) + { + resolvedColumnGap = columnGap ?? parentColumns.Gap; + columns = CreateSubgridTracks(parentColumns, resolvedColumnGap, box.Margin.Left + borderLeft + paddingLeft, box.Margin.Right + borderRight + paddingRight, explicitGridTemplateColumns, columnLineNames); + } + + // implicit columns after the explicit ones repeat grid-auto-columns (CSS Grid 1 §7.6) + var explicitColumnCount = columns.Count; + var autoColumnDefinitions = styleMap.TryGetValue("grid-auto-columns", out var autoColumnsValue) + ? ParseGridTrackListStructured(autoColumnsValue, containingWidth) + : []; + + GridTrackSize CreateImplicitColumn() => autoColumnDefinitions.Count > 0 + ? CloneGridTrackSize(autoColumnDefinitions[Math.Max(0, columns.Count - explicitColumnCount) % autoColumnDefinitions.Count]) + : GridTrackSize.Auto(); + + if (columns.Count == 0 && autoColumnDefinitions.Count > 0) + { + columns.Add(CreateImplicitColumn()); + } + else if (columns.Count == 0) { // the implicit column is auto; stretched (justify-content: normal) it fills the // container, which needs no measuring, otherwise it fits its items, which @@ -3835,6 +3914,13 @@ private static void LayoutGridContainer( var containerHeight = usedContentHeight ?? authoredContainerHeight; var explicitGridTemplateRows = styleMap.GetValueOrDefault("grid-template-rows") ?? string.Empty; var rows = ParseGridTrackListStructured(explicitGridTemplateRows, authoredContainerHeight, lineNames: rowLineNames); + + if (IsSubgridValue(explicitGridTemplateRows) && parentTracks?.Rows is { } parentRows) + { + resolvedRowGap = rowGap ?? parentRows.Gap; + rows = CreateSubgridTracks(parentRows, resolvedRowGap, box.Margin.Top + borderTop + paddingTop, box.Margin.Bottom + borderBottom + paddingBottom, explicitGridTemplateRows, rowLineNames); + } + var hasExplicitRowTracks = rows.Count > 0; var explicitRowCount = rows.Count; var autoRowDefinitions = styleMap.TryGetValue("grid-auto-rows", out var autoRowsValue) @@ -4026,7 +4112,7 @@ void MarkPlaced(GridPlacement column, GridPlacement row) itemPlacements.Add((elementChild, new GridPlacement(area.Column, area.ColumnSpan), new GridPlacement(area.Row, area.RowSpan))); while (columns.Count < area.Column + area.ColumnSpan) { - columns.Add(GridTrackSize.Auto()); + columns.Add(CreateImplicitColumn()); } while (rows.Count < area.Row + area.RowSpan) @@ -4132,7 +4218,7 @@ void MarkPlaced(GridPlacement column, GridPlacement row) while (columns.Count < effectiveColumnCount) { - columns.Add(GridTrackSize.Auto()); + columns.Add(CreateImplicitColumn()); } while (rows.Count < effectiveRowCount) @@ -4170,9 +4256,36 @@ void MarkPlaced(GridPlacement column, GridPlacement row) var resolvedColumnSizes = columns.Select(track => track.Pixels).ToList(); var fractionRowContent = new Dictionary(); + var subgridItems = new List<(ElementRenderNode Element, GridPlacement Column, GridPlacement Row, bool Columns, bool Rows)>(); + + foreach (var (element, placementColumn, placementRow) in itemPlacements) + { + var itemMap = GetOrCreateStyleMap(context, element.Ref, element.ComputedStyle); + var subgridsColumns = IsSubgridValue(itemMap.GetValueOrDefault("grid-template-columns")); + var subgridsRows = IsSubgridValue(itemMap.GetValueOrDefault("grid-template-rows")); + + if (subgridsColumns || subgridsRows) + { + subgridItems.Add((element, placementColumn, placementRow, subgridsColumns, subgridsRows)); + var tracks = s_subgridTracks.GetValue(element.Ref, static _ => new SubgridTracks()); + tracks.Columns = subgridsColumns ? CreateSubgridAxis(resolvedColumnSizes, placementColumn, resolvedColumnGap, columnLineNames) : null; + tracks.Rows = null; + } + else + { + s_subgridTracks.Remove(element.Ref); + } + } foreach (var (element, placementColumn, placementRow) in itemPlacements) { + if (subgridItems.Exists(item => item.Rows && ReferenceEquals(item.Element, element))) + { + // its items size the rows it spans, as if they were items of this grid + GrowRowsBySubgridItems(element, placementColumn, placementRow); + continue; + } + if (placementRow.LineIndex >= rows.Count || rows[placementRow.LineIndex].Kind == GridTrackSizeKind.Fixed) { continue; @@ -4257,6 +4370,60 @@ void MarkPlaced(GridPlacement column, GridPlacement row) var columnSizes = columns.Select(t => t.Pixels).ToList(); var rowSizes = rows.Select(t => t.Pixels).ToList(); + + foreach (var subgridItem in subgridItems) + { + if (subgridItem.Rows && s_subgridTracks.TryGetValue(subgridItem.Element.Ref, out var tracks)) + { + tracks.Rows = CreateSubgridAxis(rowSizes, subgridItem.Row, resolvedRowGap, rowLineNames); + } + } + + void GrowRowsBySubgridItems(ElementRenderNode subgrid, GridPlacement placementColumn, GridPlacement placementRow) + { + var subgridStyle = GetOrCreateStyleMap(context, subgrid.Ref, subgrid.ComputedStyle); + var areaWidth = GetGridTrackSpanSize(resolvedColumnSizes, placementColumn.LineIndex, placementColumn.Span, resolvedColumnGap, containingWidth); + var subgridBox = WithPercentagePadding(ResolveBoxStyle(subgridStyle, subgrid.Ref), subgridStyle, areaWidth); + var subgridsColumns = IsSubgridValue(subgridStyle.GetValueOrDefault("grid-template-columns")); + var contentWidth = Math.Max(0f, areaWidth - subgridBox.Margin.Left - subgridBox.Margin.Right - subgridBox.BorderWidth.Left - subgridBox.BorderWidth.Right - subgridBox.Padding.Left - subgridBox.Padding.Right); + var columnCount = subgridsColumns + ? placementColumn.Span + : Math.Max(1, ParseGridTrackListStructured(subgridStyle.GetValueOrDefault("grid-template-columns") ?? string.Empty, contentWidth).Count); + var startEdge = subgridBox.Margin.Top + subgridBox.BorderWidth.Top + subgridBox.Padding.Top; + var endEdge = subgridBox.Margin.Bottom + subgridBox.BorderWidth.Bottom + subgridBox.Padding.Bottom; + var index = 0; + + // its items are placed in turn (line-based placement in a subgrid is not looked at here) + foreach (var item in FlattenDisplayContents(subgrid.Children, context).OfType()) + { + if (IsOutOfFlowPositioned(GetOrCreateStyleMap(context, item.Ref, item.ComputedStyle))) + { + continue; + } + + var row = index / columnCount; + var column = index % columnCount; + index++; + + if (row >= placementRow.Span) + { + break; + } + + if (rows[placementRow.LineIndex + row].Kind == GridTrackSizeKind.Fixed) + { + continue; + } + + var itemWidth = subgridsColumns + ? resolvedColumnSizes[placementColumn.LineIndex + column] + : contentWidth / columnCount; + var height = MeasureGridItemHeight(item, itemWidth, inheritedTextStyle, context, maxY) + + (row == 0 ? startEdge : 0f) + + (row == placementRow.Span - 1 ? endEdge : 0f); + GrowGridRowsOrDefer(rows, spanningRowGrowths, new GridPlacement(placementRow.LineIndex + row, 1), height, resolvedRowGap); + } + } var columnAlignment = ResolveGridContentAlignment(justifyContent, columnSizes, resolvedColumnGap, containingWidth); var rowAlignment = ResolveGridContentAlignment(styleMap.GetValueOrDefault("align-content")?.Trim().ToLowerInvariant(), rowSizes, resolvedRowGap, containerHeight); @@ -5606,6 +5773,102 @@ private static float ResolveGridItemAuthoredHeight(Dictionary st return Math.Max(authored, minimum) + margins; } + /// + /// The tracks of its parent grid a subgrid spans, with the parent's gap and line names, given + /// to the subgrid by the parent's layout (kept for a subgrid laid out again on its own). + /// + private sealed class SubgridTracks + { + public SubgridAxis? Columns { get; set; } + + public SubgridAxis? Rows { get; set; } + } + + private sealed record class SubgridAxis(List Sizes, float Gap, Dictionary> LineNames); + + private static readonly ConditionalWeakTable s_subgridTracks = new(); + + private static bool IsSubgridValue(string? value) => + value is not null && value.TrimStart().StartsWith("subgrid", StringComparison.OrdinalIgnoreCase); + + private static SubgridAxis CreateSubgridAxis(List sizes, GridPlacement placement, float gap, Dictionary> lineNames) + { + var start = Math.Clamp(placement.LineIndex, 0, sizes.Count); + var count = Math.Clamp(placement.Span, 0, sizes.Count - start); + var names = new Dictionary>(StringComparer.Ordinal); + + foreach (var (name, lines) in lineNames) + { + var inside = lines.Where(line => line >= start && line <= start + count).Select(line => line - start).ToList(); + + if (inside.Count > 0) + { + names[name] = inside; + } + } + + return new SubgridAxis(sizes.GetRange(start, count), gap, names); + } + + /// + /// The tracks of a subgrid: those of its parent, the first and the last shrunk by the + /// subgrid's own margin, border and padding, and its lines kept in the middle of the + /// parent's gaps when it has a gap of its own (CSS Grid 2 §9). The parent's line names + /// come first, then those given after `subgrid`. + /// + private static List CreateSubgridTracks(SubgridAxis axis, float gap, float startEdge, float endEdge, string value, Dictionary> lineNames) + { + var tracks = new List(axis.Sizes.Count); + var shift = (axis.Gap - gap) / 2f; + var count = axis.Sizes.Count; + + for (var i = 0; i < count; i++) + { + var size = axis.Sizes[i] + (i > 0 ? shift : 0f) + (i < count - 1 ? shift : 0f) - + (i == 0 ? startEdge : 0f) - (i == count - 1 ? endEdge : 0f); + tracks.Add(GridTrackSize.Fixed(Math.Max(0f, size))); + } + + lineNames.Clear(); + + foreach (var (name, lines) in axis.LineNames) + { + lineNames[name] = [.. lines]; + } + + var line = 0; + var position = value.IndexOf('['); + + while (position >= 0 && line <= count) + { + var end = value.IndexOf(']', position); + + if (end < 0) + { + break; + } + + foreach (var name in value[(position + 1)..end].Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (!lineNames.TryGetValue(name, out var lines)) + { + lineNames[name] = lines = []; + } + + if (!lines.Contains(line)) + { + lines.Add(line); + lines.Sort(); + } + } + + line++; + position = value.IndexOf('[', end); + } + + return tracks; + } + private static float MeasureGridItemHeight(ElementRenderNode element, float containingWidth, RenderTextStyle inheritedTextStyle, LayoutContext context, float maxY) { // cached for the render: a grid in a grid item would otherwise measure its items again @@ -6056,7 +6319,7 @@ private static void LayoutTextNode( suppressNextBlockTopMargin = false; var (bandLeft, bandRight) = floats.GetBand(cursorY, textStyle.FontSize * textStyle.LineHeightMultiplier, containingX, containingX + containingWidth); - LayoutWrappedText(text, bandLeft, bandRight - bandLeft, ref cursorY, textStyle, context, displayList, maxY, textIndentConsumed ? 0f : textStyle.TextIndent + textStyle.MarkerIndent, textNode, isTextRun: asTextRun); + LayoutWrappedText(text, bandLeft, bandRight - bandLeft, ref cursorY, textStyle, context, displayList, maxY, textIndentConsumed ? 0f : textStyle.TextIndent + textStyle.MarkerIndent, textNode, isTextRun: asTextRun, firstLineColor: textIndentConsumed ? null : textStyle.FirstLineColor); textIndentConsumed = true; } @@ -6072,7 +6335,8 @@ private static void LayoutWrappedText( float firstLineIndent, INode? source = null, IText? textSource = null, - bool isTextRun = false) + bool isTextRun = false, + RenderColor? firstLineColor = null) { textSource ??= source as IText; var sourcePosition = 0; @@ -6117,6 +6381,10 @@ private static void LayoutWrappedText( { var line = lines[index]; var lineSourceStart = sourcePosition; + // ::first-line colors the first line (see ApplyFirstLineColor) + var paintStyle = index == 0 && firstLineColor is { } lineColor + ? textStyle with { Color = lineColor, DecorationColor = textStyle.DecorationColor == textStyle.Color ? lineColor : textStyle.DecorationColor } + : textStyle; var lineTop = cursorY; // the lines below the viewport are not laid out, the one reaching into it is @@ -6152,6 +6420,8 @@ TextSegment[] CreateSegments(string text, int rawStart) => } var lineWidth = MeasureTextWidth(context, line, textStyle) + (CountSpaces(line) * textStyle.WordSpacing); + // what an ellipsis cuts off still overflows the box (scrollWidth) + var naturalLineWidth = lineWidth; var lineMaxWidth = index == 0 ? Math.Max(0f, maxWidth - firstLineIndent) : maxWidth; var isLastLine = index == lines.Count - 1; @@ -6179,6 +6449,7 @@ TextSegment[] CreateSegments(string text, int rawStart) => var lineX = x + (index == 0 ? firstLineIndent : 0f) + (justifyExtra > 0f ? 0f : ResolveTextAlignmentOffset(ResolveStartIfJustify(lineAlign, textStyle.Direction), lineMaxWidth, lineWidth)); var baselineY = cursorY - lineHeight + ResolveLineHeightBox(textStyle with { LineHeightMultiplier = lineHeight / Math.Max(textStyle.FontSize, 0.01f) }, context).Above; RecordTextBaseline(baselineY); + NoteTextExtent(lineX + Math.Max(lineWidth, naturalLineWidth), cursorY); // Lines with right-to-left text are painted as runs in visual order (UAX #9). if (needsReordering) @@ -6188,7 +6459,7 @@ TextSegment[] CreateSegments(string text, int rawStart) => foreach (var (run, isRightToLeft) in BidiAlgorithm.GetVisualRuns(line, textStyle.Direction == TextDirection.Rtl)) { - var runStyle = textStyle with { IsRightToLeftRun = isRightToLeft }; + var runStyle = paintStyle with { IsRightToLeftRun = isRightToLeft }; var runWidth = MeasureTextWidth(context, run, runStyle) + (CountSpaces(run) * textStyle.WordSpacing); var fragment = RecordsTextFragments(context) ? CreateFragment(run, FindUnusedRun(line, run, usedRuns), runX, runStyle, string.IsNullOrWhiteSpace(run) ? runWidth : null) : null; @@ -6217,7 +6488,7 @@ TextSegment[] CreateSegments(string text, int rawStart) => if (word.Length > 0) { - DrawTextFragment(context, displayList, word, wordX, baselineY, textStyle, CreateFragment(word, wordStart, wordX, textStyle)); + DrawTextFragment(context, displayList, word, wordX, baselineY, paintStyle, CreateFragment(word, wordStart, wordX, textStyle)); wordX += MeasureTextWidth(context, word, textStyle); } @@ -6228,7 +6499,7 @@ TextSegment[] CreateSegments(string text, int rawStart) => if (wordIndex + 1 < words.Length && CreateFragment(" ", wordStart, wordX, textStyle, gap) is { } spaceFragment) { - DrawTextFragment(context, displayList, " ", wordX, baselineY, textStyle, spaceFragment); + DrawTextFragment(context, displayList, " ", wordX, baselineY, paintStyle, spaceFragment); } wordX += gap; @@ -6238,7 +6509,7 @@ TextSegment[] CreateSegments(string text, int rawStart) => continue; } - DrawTextFragment(context, displayList, line, lineX, baselineY, textStyle, CreateFragment(line, 0, lineX, textStyle)); + DrawTextFragment(context, displayList, line, lineX, baselineY, paintStyle, CreateFragment(line, 0, lineX, textStyle)); } } @@ -8115,6 +8386,8 @@ private static Dictionary CreateComputedStyleMap(ICssStyleDeclar AddIfPresent(map, "align-content", explicitDeclarations is not null ? ReadExplicitOrComputed(explicitDeclarations, style, "align-content") : ResolveExplicitPropertyValue(element, style, "align-content")); var explicitGridAutoRows = explicitDeclarations is not null ? ReadExplicitOrComputed(explicitDeclarations, style, "grid-auto-rows") : ResolveExplicitPropertyValue(element, style, "grid-auto-rows"); AddIfPresent(map, "grid-auto-rows", ResolveLengthsOfAuthoredValue(style, "grid-auto-rows", string.IsNullOrWhiteSpace(explicitGridAutoRows) ? ParseStyleAttributeValue(inlineStyle, "grid-auto-rows") : explicitGridAutoRows)); + var explicitGridAutoColumns = explicitDeclarations is not null ? ReadExplicitOrComputed(explicitDeclarations, style, "grid-auto-columns") : ResolveExplicitPropertyValue(element, style, "grid-auto-columns"); + AddIfPresent(map, "grid-auto-columns", ResolveLengthsOfAuthoredValue(style, "grid-auto-columns", string.IsNullOrWhiteSpace(explicitGridAutoColumns) ? ParseStyleAttributeValue(inlineStyle, "grid-auto-columns") : explicitGridAutoColumns)); var explicitGridAutoFlow = explicitDeclarations is not null ? ReadExplicitOrComputed(explicitDeclarations, style, "grid-auto-flow") : ResolveExplicitPropertyValue(element, style, "grid-auto-flow"); AddIfPresent(map, "grid-auto-flow", string.IsNullOrWhiteSpace(explicitGridAutoFlow) ? ParseStyleAttributeValue(inlineStyle, "grid-auto-flow") : explicitGridAutoFlow); var explicitJustifyItems = explicitDeclarations is not null ? ReadExplicitOrComputed(explicitDeclarations, style, "justify-items") : ResolveExplicitPropertyValue(element, style, "justify-items"); @@ -12086,6 +12359,7 @@ private static RenderTextStyle PaintListItemMarker( // Not derived from any spec metric - a small, fixed visual gap between the marker and the // content that follows it, matching the general proportions browsers use. const float MarkerGap = 6f; + var markerColor = ResolvePseudoElementColor(element, context, "marker") ?? textStyle.Color; if (IsShapeListStyleType(listStyleType)) { @@ -12100,13 +12374,13 @@ private static RenderTextStyle PaintListItemMarker( switch (listStyleType) { case "circle": - displayList.StrokeRoundedRect(markerRect, textStyle.Color, Math.Max(1f, textStyle.FontSize * 0.08f), circularRadii); + displayList.StrokeRoundedRect(markerRect, markerColor, Math.Max(1f, textStyle.FontSize * 0.08f), circularRadii); break; case "square": - displayList.FillRect(markerRect, textStyle.Color); + displayList.FillRect(markerRect, markerColor); break; default: // disc - displayList.FillRect(markerRect, textStyle.Color, circularRadii); + displayList.FillRect(markerRect, markerColor, circularRadii); break; } @@ -12117,7 +12391,7 @@ private static RenderTextStyle PaintListItemMarker( var markerWidth = MeasureTextWidth(context, markerText, textStyle); var markerX = isInside ? contentX : borderBoxX - MarkerGap - markerWidth; - DrawStyledText(context, displayList, markerText, markerX, markerBaselineY, textStyle, decorate: false); + DrawStyledText(context, displayList, markerText, markerX, markerBaselineY, textStyle with { Color = markerColor }, decorate: false); return isInside ? textStyle with { MarkerIndent = markerWidth + MarkerGap } : textStyle; } @@ -12127,6 +12401,8 @@ private static RenderTextStyle PaintListItemMarker( /// same as `hidden`: a rendered PNG has no scrollbars or interactivity, so anything a browser /// would let the user scroll to reveal is, here, simply clipped away like `hidden`. /// + internal static bool ClipsOverflow(Dictionary styleMap) => ShouldClipOverflow(styleMap); + private static bool ShouldClipOverflow(Dictionary styleMap) => IsClippingOverflowValue(ResolveOverflowAxis(styleMap, "overflow-x")) || IsClippingOverflowValue(ResolveOverflowAxis(styleMap, "overflow-y")); @@ -12889,8 +13165,21 @@ private static void PaintTextShadows(DisplayList displayList, IReadOnlyList - private static void PaintBoxDecorations(DisplayList displayList, LayoutContext context, Dictionary styleMap, ElementRenderNode node, BoxStyle box, RenderRect borderBox, EdgeSizes border, EdgeSizes padding, bool fillsTransparentBackground) => - PaintBoxDecorations(displayList, context, styleMap, node.Ref, GetPaintKey(node), box, borderBox, border, padding, fillsTransparentBackground); + private static void PaintBoxDecorations(DisplayList displayList, LayoutContext context, Dictionary styleMap, ElementRenderNode node, BoxStyle box, RenderRect borderBox, EdgeSizes border, EdgeSizes padding, bool fillsTransparentBackground) + { + // whose style the paint() images of its background are drawn with + var outerPaintedNode = s_paintedNode; + s_paintedNode = node; + + try + { + PaintBoxDecorations(displayList, context, styleMap, node.Ref, GetPaintKey(node), box, borderBox, border, padding, fillsTransparentBackground); + } + finally + { + s_paintedNode = outerPaintedNode; + } + } /// /// What identifies a box from layout to layout (see ): its @@ -12945,22 +13234,48 @@ private static void PaintBoxShadows(DisplayList displayList, IReadOnlyList + /// The text runs of the box whose decorations are painted, for `background-clip: text`. + /// + [ThreadStatic] + private static List? s_backgroundClipTexts; + + private static bool HasTextBackgroundClip(BoxStyle box, Dictionary styleMap) => + box.BackgroundLayers is { Count: > 0 } layers + ? layers.Any(static layer => layer.Clip == "text") + : string.Equals(GetLayerValue(styleMap, "background-clip", 0)?.Trim(), "text", StringComparison.OrdinalIgnoreCase); + /// /// Paints a box's background: the color first, clipped like the bottom image layer, then the /// image layers from the bottom up. Each layer is clipped to its `background-clip` box (border /// box by default) and sized and positioned in its `background-origin` box (padding box by /// default); radii shrink with the inset, like the inner edge of a rounded border. Layers with /// a `background-blend-mode` blend only with the layers and color below them, so the whole - /// background is then painted as an isolated group. `background-clip: text` is not supported - /// and paints like `border-box`. + /// background is then painted as an isolated group. `background-clip: text` masks a layer by + /// the glyphs of the box's content (see ); where they are + /// not known (a box painted again on its own), it paints like `border-box`. /// private static void PaintBoxBackground(DisplayList displayList, Dictionary styleMap, BoxStyle box, float x, float y, float width, float height, EdgeSizes border, EdgeSizes padding, RenderRect? viewportArea = null) { var layers = box.BackgroundLayers ?? []; + var clipTexts = s_backgroundClipTexts; (RenderRect Rect, RenderCornerRadii Radii) ResolveArea(string? keyword, string fallback) => ResolveBoxArea(keyword, fallback, x, y, width, height, border, padding, box.BorderRadius); + // `background-clip: text`: painted in the border box, masked by the glyphs of the content + bool PushTextClip(string? clip) + { + if (clip != "text" || clipTexts is null) + { + return false; + } + + var area = new RenderRect(x, y, width, height); + displayList.PushMask([new RenderMaskLayer(new RenderTextMaskPaint(clipTexts), area, area, false)]); + return true; + } + var colorClip = layers.Count > 0 ? layers[^1].Clip : (GetLayerValue(styleMap, "background-clip", 0) ?? string.Empty).ToLowerInvariant(); @@ -12974,7 +13289,13 @@ private static void PaintBoxBackground(DisplayList displayList, Dictionary 0) { var (colorRect, colorRadii) = ResolveArea(colorClip, "border-box"); + var clipsColorToText = PushTextClip(colorClip); PaintBackground(displayList, new RenderColorPaint(box.BackgroundColor), colorRect.X, colorRect.Y, colorRect.Width, colorRect.Height, colorRadii); + + if (clipsColorToText) + { + displayList.PopMask(); + } } for (var index = layers.Count - 1; index >= 0; index--) @@ -12983,11 +13304,24 @@ private static void PaintBoxBackground(DisplayList displayList, Dictionary 0f, Height: > 0f } viewport) { // `background-attachment: fixed`: positioned in the viewport, which it stays in @@ -13003,6 +13337,11 @@ private static void PaintBoxBackground(DisplayList displayList, Dictionary ParseImageLayers(Dictionary } var items = SplitTopLevelCommaList(images); + var paintIndex = 0; for (var index = 0; index < items.Length; index++) { @@ -14212,6 +14552,12 @@ private static List ParseImageLayers(Dictionary repeatY is RenderBackgroundRepeat.Space or RenderBackgroundRepeat.Round ? repeatY : null); } } + else if (item.StartsWith("paint(", StringComparison.OrdinalIgnoreCase)) + { + // drawn by a paint worklet once the size of the box is known (see PaintBoxBackground) + paint = prefix == "background" ? new PaintWorkletLayer(paintIndex) : null; + paintIndex++; + } else if (ParseGradientPaint(item, RenderColor.Transparent, ParseLength(styleMap, "font-size", 16f, 16f, allowAuto: false)) is RenderGradientPaint gradient) { // A gradient fills the whole area unless it is explicitly sized, positioned or @@ -15219,15 +15565,128 @@ private static RenderBackgroundSizeAxis ParseSizeAxisToken(string token) // (including a plain color), so no name-prefix pre-check is needed before calling it. private static RenderPaint ParseGradientPaint(string rawValue, RenderColor fallbackColor, float emBase = 16f) { - var source = new StringSource(rawValue.Trim()); + var text = rawValue.Trim(); + var interpolation = ExtractGradientExtensions(ref text, out var hints); + var source = new StringSource(text); - return source.ParseGradient() switch + var gradient = source.ParseGradient() switch { - CssLinearGradientValue linear => new RenderGradientPaint(ConvertLinearGradient(linear, fallbackColor, emBase)), - CssRadialGradientValue radial => new RenderGradientPaint(ConvertRadialGradient(radial, fallbackColor, emBase)), - CssConicGradientValue conic => new RenderGradientPaint(ConvertConicGradient(conic, fallbackColor)), - _ => new RenderColorPaint(fallbackColor), + CssLinearGradientValue linear => ConvertLinearGradient(linear, fallbackColor, emBase), + CssRadialGradientValue radial => ConvertRadialGradient(radial, fallbackColor, emBase), + CssConicGradientValue conic => ConvertConicGradient(conic, fallbackColor), + _ => null, }; + + if (gradient is null) + { + return new RenderColorPaint(fallbackColor); + } + + if (hints is not null) + { + var stops = gradient.Stops.ToList(); + var isConic = gradient.Kind == RenderGradientKind.Conic; + + // from the last, so the indices of the earlier ones stay + for (var i = hints.Count - 1; i >= 0; i--) + { + var (index, position) = hints[i]; + + if (index > 0 && index < stops.Count) + { + stops.Insert(index, ConvertStopPosition(position, RenderColor.Transparent, isConic, emBase, stops[index - 1].Position) with { IsHint = true }); + } + } + + gradient = gradient with { Stops = stops }; + } + + if (interpolation is { } method) + { + gradient = gradient with { ColorSpace = method.Space, HueInterpolation = method.Hue }; + } + + return new RenderGradientPaint(gradient); + } + + private static readonly System.Text.RegularExpressions.Regex GradientInterpolationPattern = new( + @"\bin\s+(?srgb-linear|srgb|display-p3|a98-rgb|prophoto-rgb|rec2020|oklab|oklch|lab|lch|xyz-d50|xyz-d65|xyz|hsl|hwb)\b(\s+(?shorter|longer|increasing|decreasing)\s+hue\b)?", + System.Text.RegularExpressions.RegexOptions.CultureInvariant | System.Text.RegularExpressions.RegexOptions.IgnoreCase); + + private static readonly System.Text.RegularExpressions.Regex GradientHintPattern = new( + @"^(-?[0-9]*\.?[0-9]+(e[+-]?[0-9]+)?(%|px|r?em|deg|rad|grad|turn)?|calc\([^,]*\))$", + System.Text.RegularExpressions.RegexOptions.CultureInvariant | System.Text.RegularExpressions.RegexOptions.IgnoreCase); + + /// + /// Takes what CSS Images 4 added to gradients out of their text, which is then parsed as + /// before: the color interpolation method ("in oklch", "in hsl longer hue") and the color + /// hints, a position alone between two color stops ("red, 20%, blue"), returned with the + /// number of stops before each. + /// + private static (string Space, string? Hue)? ExtractGradientExtensions(ref string text, out List<(int Index, string Position)>? hints) + { + hints = null; + var open = text.IndexOf('('); + + if (open < 0 || !text.EndsWith(')')) + { + return null; + } + + var name = text[..open]; + var arguments = SplitTopLevelCommaList(text[(open + 1)..^1]).ToList(); + + if (arguments.Count == 0 || + !GradientInterpolationPattern.IsMatch(arguments[0]) && !arguments.Skip(1).Any(GradientHintPattern.IsMatch)) + { + return null; + } + + (string Space, string? Hue)? interpolation = null; + var match = GradientInterpolationPattern.Match(arguments[0]); + + if (match.Success) + { + interpolation = (match.Groups["space"].Value.ToLowerInvariant(), match.Groups["hue"].Success ? match.Groups["hue"].Value.ToLowerInvariant() : null); + arguments[0] = (arguments[0][..match.Index] + arguments[0][(match.Index + match.Length)..]).Trim(); + + if (arguments[0].Length == 0) + { + arguments.RemoveAt(0); + } + } + + var kept = new List(arguments.Count); + var stopCount = 0; + + for (var i = 0; i < arguments.Count; i++) + { + var argument = arguments[i]; + + // a hint follows a color stop (never the first argument, which may be a size) + if (i > 0 && stopCount > 0 && GradientHintPattern.IsMatch(argument)) + { + hints ??= []; + hints.Add((stopCount, argument)); + continue; + } + + kept.Add(argument); + + if (i > 0 || IsColorStopArgument(argument)) + { + // a stop with two positions ("red 0 50%") is two stops + var single = new StringSource("linear-gradient(" + argument + ")").ParseGradient() as CssLinearGradientValue; + stopCount += single?.Stops.Length ?? 1; + } + } + + text = name + "(" + string.Join(", ", kept) + ")"; + return interpolation; + + static bool IsColorStopArgument(string argument) => + new StringSource("linear-gradient(" + argument + ")").ParseGradient() is CssLinearGradientValue { Stops.Length: > 0 } single && + !argument.StartsWith("to ", StringComparison.OrdinalIgnoreCase); } private static RenderGradient ConvertLinearGradient(CssLinearGradientValue gradient, RenderColor fallbackColor, float emBase) @@ -15455,28 +15914,28 @@ private static IReadOnlyList ConvertGradientStops(ICssValue[ continue; } - var positionText = stop.Location.CssText; + result.Add(ConvertStopPosition(stop.Location.CssText, color, isConic, emBase, autoPosition)); + } - if (!isConic && TryParsePercentagePlusLength(positionText, emBase, out var fraction, out var offsetPixels)) - { - result.Add(new RenderGradientStop(fraction, color, OffsetPixels: offsetPixels)); - continue; - } + return result; + } - if (!isConic && TryParseStopLength(positionText, emBase, out var pixels)) - { - // An absolute-length stop position ("red 10px") cannot become a fraction until - // the gradient's own rendered geometry (line length/radius) is known, so the raw - // pixel value is carried through and resolved by the backend at paint time. - result.Add(new RenderGradientStop(autoPosition, color, pixels)); - } - else - { - result.Add(new RenderGradientStop(ParseStopPosition(positionText, isConic), color)); - } + private static RenderGradientStop ConvertStopPosition(string positionText, RenderColor color, bool isConic, float emBase, float autoPosition) + { + if (!isConic && TryParsePercentagePlusLength(positionText, emBase, out var fraction, out var offsetPixels)) + { + return new RenderGradientStop(fraction, color, OffsetPixels: offsetPixels); } - return result; + if (!isConic && TryParseStopLength(positionText, emBase, out var pixels)) + { + // An absolute-length stop position ("red 10px") cannot become a fraction until + // the gradient's own rendered geometry (line length/radius) is known, so the raw + // pixel value is carried through and resolved by the backend at paint time. + return new RenderGradientStop(autoPosition, color, pixels); + } + + return new RenderGradientStop(ParseStopPosition(positionText, isConic), color); } /// @@ -16557,7 +17016,70 @@ private readonly record struct RenderTextStyle( string? WebkitAlignLeftBehind = null, bool Overline = false, float DecorationThickness = float.NaN, - float DecorationFontSize = float.NaN); + float DecorationFontSize = float.NaN, + RenderColor? FirstLineColor = null); + + /// + /// The rules of a style collection that style `::marker` or `::first-line`, which most + /// documents have none of: only for an element one of them matches is its style computed. + /// + private sealed class PseudoElementRules + { + public readonly List Marker = []; + public readonly List FirstLine = []; + } + + private static readonly ConditionalWeakTable s_pseudoElementRules = new(); + + private static PseudoElementRules GetPseudoElementRules(IStyleCollection collection) => + s_pseudoElementRules.GetValue(collection, static styles => + { + var rules = new PseudoElementRules(); + + foreach (var rule in styles) + { + var text = rule.SelectorText; + + if (text is null || !text.Contains("::", StringComparison.Ordinal)) + { + continue; + } + + if (text.Contains("::marker", StringComparison.OrdinalIgnoreCase)) + { + rules.Marker.Add(rule); + } + + if (text.Contains("::first-line", StringComparison.OrdinalIgnoreCase)) + { + rules.FirstLine.Add(rule); + } + } + + return rules; + }); + + /// + /// The color a rule gives the pseudo-element (`marker` or `first-line`) of the element, if any. + /// + private static RenderColor? ResolvePseudoElementColor(IElement element, LayoutContext context, string name) + { + if (element is IPseudoElement || context.StyleCollection is not { } collection) + { + return null; + } + + var rules = GetPseudoElementRules(collection); + var candidates = name == "marker" ? rules.Marker : rules.FirstLine; + + if (candidates.Count == 0 || element.Pseudo(name) is not { } pseudo || !candidates.Exists(rule => rule.Selector?.Match(pseudo, null) == true)) + { + return null; + } + + var color = collection.ComputeDeclarations(element, "::" + name).GetPropertyValue("color"); + return string.IsNullOrWhiteSpace(color) ? null : ParseColor(color, RenderColor.Transparent); + } private enum TextAlign { diff --git a/src/AngleSharp.Renderer/Rendering/Canvas2DRenderingContext.cs b/src/AngleSharp.Renderer/Rendering/Canvas2DRenderingContext.cs index 94f4d46..16be557 100644 --- a/src/AngleSharp.Renderer/Rendering/Canvas2DRenderingContext.cs +++ b/src/AngleSharp.Renderer/Rendering/Canvas2DRenderingContext.cs @@ -1024,6 +1024,89 @@ public CanvasGradient CreateConicGradient(double startAngle, double x, double y) return TryGetImage(image, out var source, out _, out _) ? new CanvasPattern(source!, mode) : null; } + /// + /// Reads the pixels of a rectangle of the bitmap (not premultiplied); outside of the + /// canvas they are transparent black. + /// + public ImageData GetImageData(int x, int y, int width, int height) + { + if (width == 0 || height == 0) + { + throw new DomException(DomError.IndexSizeError); + } + + // a negative size takes the rectangle on the other side + if (width < 0) + { + x += width; + width = -width; + } + + if (height < 0) + { + y += height; + height = -height; + } + + var data = new byte[checked(width * height * 4)]; + var info = new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Unpremul); + + lock (_sync) + { + EnsureBitmapSizeLocked(); + using var surface = SKSurface.Create(info); + + if (surface is not null) + { + using var paint = new SKPaint { BlendMode = SKBlendMode.Src }; + surface.Canvas.Clear(SKColors.Transparent); + using var source = SKImage.FromBitmap(_bitmap); + surface.Canvas.DrawImage(source, -x, -y, new SKSamplingOptions(SKFilterMode.Nearest), paint); + var handle = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); + + try + { + surface.ReadPixels(info, handle.AddrOfPinnedObject(), info.RowBytes, 0, 0); + } + finally + { + handle.Free(); + } + } + } + + return new ImageData(width, height, data); + } + + /// + /// Writes the pixels of image data to the bitmap at the given position, replacing what is + /// there (no compositing, transformation or clipping). + /// + public void PutImageData(ImageData imageData, int x, int y) + { + ArgumentNullException.ThrowIfNull(imageData); + var info = new SKImageInfo(imageData.Width, imageData.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul); + using var image = SKImage.FromPixelCopy(info, imageData.Data, info.RowBytes); + + if (image is null) + { + return; + } + + lock (_sync) + { + EnsureBitmapSizeLocked(); + using var paint = new SKPaint { BlendMode = SKBlendMode.Src }; + _canvas.Save(); + _canvas.ResetMatrix(); + _canvas.DrawImage(image, x, y, new SKSamplingOptions(SKFilterMode.Nearest), paint); + _canvas.Restore(); + Changed(); + } + + Invalidate(); + } + /// /// Gets a copy of the bitmap (premultiplied alpha), e.g. for a frame to paint. /// diff --git a/src/AngleSharp.Renderer/Rendering/CanvasRenderingContext2DExtensions.cs b/src/AngleSharp.Renderer/Rendering/CanvasRenderingContext2DExtensions.cs index 271950c..cb28f7f 100644 --- a/src/AngleSharp.Renderer/Rendering/CanvasRenderingContext2DExtensions.cs +++ b/src/AngleSharp.Renderer/Rendering/CanvasRenderingContext2DExtensions.cs @@ -1,5 +1,6 @@ namespace AngleSharp.Media.Dom; +using System; using AngleSharp.Attributes; using AngleSharp.Renderer; @@ -389,6 +390,34 @@ public static void SetImageSmoothingEnabled(this ICanvasRenderingContext2D conte } } + /// + /// Reads the pixels of a rectangle of the canvas. + /// + [DomName("getImageData")] + public static ImageData GetImageData(this ICanvasRenderingContext2D context, int sx, int sy, int sw, int sh) => + context is Canvas2DRenderingContext canvas + ? canvas.GetImageData(sx, sy, sw, sh) + : new ImageData(Math.Abs(sw), Math.Abs(sh)); + + /// + /// Creates transparent black image data of the given size. + /// + [DomName("createImageData")] + public static ImageData CreateImageData(this ICanvasRenderingContext2D context, int sw, int sh) => + new(Math.Abs(sw), Math.Abs(sh)); + + /// + /// Writes the pixels of image data to the canvas at the given position. + /// + [DomName("putImageData")] + public static void PutImageData(this ICanvasRenderingContext2D context, ImageData imageData, int dx, int dy) + { + if (context is Canvas2DRenderingContext canvas) + { + canvas.PutImageData(imageData, dx, dy); + } + } + /// /// Fills a rectangle with the fill style. /// diff --git a/src/AngleSharp.Renderer/Rendering/ImageData.cs b/src/AngleSharp.Renderer/Rendering/ImageData.cs new file mode 100644 index 0000000..5179def --- /dev/null +++ b/src/AngleSharp.Renderer/Rendering/ImageData.cs @@ -0,0 +1,57 @@ +namespace AngleSharp.Media.Dom; + +using System; +using AngleSharp.Attributes; +using AngleSharp.Dom; + +/// +/// The pixels of a part of a canvas (HTML 4.12.5.1.16): RGBA, not premultiplied, row by row. +/// +[DomName("ImageData")] +public sealed class ImageData +{ + /// + /// Creates transparent black image data of the given size. + /// + /// The width in pixels. + /// The height in pixels. + [DomConstructor] + public ImageData(int width, int height) + : this(width, height, new byte[checked(Math.Max(0, width) * Math.Max(0, height) * 4)]) + { + if (width <= 0 || height <= 0) + { + throw new DomException(DomError.IndexSizeError); + } + } + + internal ImageData(int width, int height, byte[] data) + { + Width = width; + Height = height; + Data = data; + } + + /// + /// Gets the width in pixels. + /// + [DomName("width")] + public int Width { get; } + + /// + /// Gets the height in pixels. + /// + [DomName("height")] + public int Height { get; } + + /// + /// Gets the pixels (for scripts a copy, as WebIDL has no clamped array here). + /// + [DomName("data")] + public ArraySegment Pixels => new(Data); + + /// + /// Gets the pixels, RGBA, four bytes per pixel. + /// + public byte[] Data { get; } +} diff --git a/src/AngleSharp.Renderer/Rendering/RenderPaint.cs b/src/AngleSharp.Renderer/Rendering/RenderPaint.cs index 30c8449..2aa72df 100644 --- a/src/AngleSharp.Renderer/Rendering/RenderPaint.cs +++ b/src/AngleSharp.Renderer/Rendering/RenderPaint.cs @@ -10,6 +10,12 @@ public abstract record RenderPaint; /// public sealed record RenderColorPaint(RenderColor Color) : RenderPaint; +/// +/// The glyphs of text runs as a mask (`background-clip: text`): what they cover is opaque. +/// +/// The text runs. +public sealed record RenderTextMaskPaint(IReadOnlyList Texts) : RenderPaint; + /// /// Represents a gradient paint. /// @@ -180,7 +186,20 @@ public sealed record RenderGradient( bool Repeating = false, RenderGradientSizeKind SizeKind = RenderGradientSizeKind.FarthestCorner, float? ExplicitRadiusX = null, - float? ExplicitRadiusY = null); + float? ExplicitRadiusY = null) +{ + /// + /// The color space the colors are interpolated in (`in oklch`), e.g. "oklch"; sRGB when + /// . + /// + public string? ColorSpace { get; init; } + + /// + /// How hues are interpolated in a polar ("shorter", "longer", + /// "increasing" or "decreasing"); the shorter way when . + /// + public string? HueInterpolation { get; init; } +} /// /// Describes a single gradient stop. @@ -206,7 +225,14 @@ public sealed record RenderGradient( /// Whether the stop has no position of its own: it is then placed halfway between its /// neighbours (CSS Images 3 §3.5.3), and only holds an estimate. /// -public sealed record RenderGradientStop(float Position, RenderColor Color, float? AbsolutePositionPixels = null, float OffsetPixels = 0f, bool IsAuto = false); +public sealed record RenderGradientStop(float Position, RenderColor Color, float? AbsolutePositionPixels = null, float OffsetPixels = 0f, bool IsAuto = false) +{ + /// + /// Whether this is a color hint ("red, 20%, blue") rather than a color stop: the position + /// where the colors of the stops around it are mixed half and half. Its color is unused. + /// + public bool IsHint { get; init; } +} /// /// Describes the available gradient kinds. diff --git a/src/AngleSharp.Renderer/Skia/GradientInterpolation.cs b/src/AngleSharp.Renderer/Skia/GradientInterpolation.cs new file mode 100644 index 0000000..af2a541 --- /dev/null +++ b/src/AngleSharp.Renderer/Skia/GradientInterpolation.cs @@ -0,0 +1,463 @@ +using System; +using System.Collections.Generic; +using AngleSharp.Renderer.Rendering; +using SkiaSharp; + +namespace AngleSharp.Renderer.Skia; + +/// +/// Interpolates the colors of a gradient where Skia's own (premultiplied sRGB, linear) mixing +/// does not: across a color hint, which moves the midpoint of a transition along an exponential +/// curve, and in another color space (`in oklch`, `in hsl longer hue`) (CSS Images 4 §3.5.3, +/// CSS Color 4 §12). Each such transition is sampled into enough stops for Skia to draw it. +/// +internal static class GradientInterpolation +{ + private const int Samples = 24; + + /// + /// Builds the colors and positions of the gradient from its color stops (in order, with their + /// positions resolved) and the hint between each stop and the next (NaN where there is none). + /// + public static (SKColor[] Colors, float[] Positions) Build(IReadOnlyList<(RenderColor Color, float Position)> stops, IReadOnlyList hints, string? colorSpace, string? hueMethod) + { + var colors = new List(stops.Count * Samples); + var positions = new List(stops.Count * Samples); + var space = Normalize(colorSpace); + var method = hueMethod?.Trim().ToLowerInvariant() ?? "shorter"; + + for (var i = 0; i < stops.Count; i++) + { + var (color, position) = stops[i]; + + if (i == stops.Count - 1) + { + colors.Add(ToSk(color)); + positions.Add(position); + break; + } + + var (next, nextPosition) = stops[i + 1]; + var hint = hints[i]; + var length = nextPosition - position; + + if (length <= 0f) + { + // a hard stop + colors.Add(ToSk(color)); + positions.Add(position); + continue; + } + + var exponent = float.NaN; + var jump = float.NaN; + + if (!float.IsNaN(hint)) + { + var h = (hint - position) / length; + + if (h <= 0f) + { + jump = 0f; + } + else if (h >= 1f) + { + jump = 1f; + } + else + { + exponent = (float)(Math.Log(0.5) / Math.Log(h)); + } + } + + var from = ToSpace(color, space); + var to = ToSpace(next, space); + + if (IsPolar(space)) + { + FixHues(ref from, ref to, method); + } + + for (var k = 0; k < Samples; k++) + { + var t = k / (float)Samples; + var weight = !float.IsNaN(jump) ? (t > jump ? 1f : 0f) + : !float.IsNaN(exponent) ? (float)Math.Pow(t, exponent) + : t; + colors.Add(ToSk(FromSpace(Mix(from, to, weight, space), space))); + positions.Add(position + (t * length)); + } + } + + return (colors.ToArray(), positions.ToArray()); + } + + private static string Normalize(string? colorSpace) => colorSpace?.Trim().ToLowerInvariant() switch + { + null or "" => "srgb", + "xyz" => "xyz-d65", + var other => other, + }; + + private static bool IsPolar(string space) => space is "hsl" or "hwb" or "lch" or "oklch"; + + private static SKColor ToSk(RenderColor color) => new(color.R, color.G, color.B, color.A); + + // the components of a color in a space, with its alpha; the hue (polar spaces) is the third + // component, NaN where it is powerless (an achromatic color) + private readonly record struct Components(double C0, double C1, double C2, double Alpha); + + private static Components Mix(Components from, Components to, float weight, string space) + { + var alpha = from.Alpha + ((to.Alpha - from.Alpha) * weight); + var polar = IsPolar(space); + + // premultiplied, except for the hue + double Premultiplied(double value, double a) => value * a; + double Lerp(double a, double b) => a + ((b - a) * weight); + + var c0 = Lerp(Premultiplied(from.C0, from.Alpha), Premultiplied(to.C0, to.Alpha)); + var c1 = Lerp(Premultiplied(from.C1, from.Alpha), Premultiplied(to.C1, to.Alpha)); + var c2 = polar ? Lerp(from.C2, to.C2) : Lerp(Premultiplied(from.C2, from.Alpha), Premultiplied(to.C2, to.Alpha)); + + if (alpha > 0) + { + c0 /= alpha; + c1 /= alpha; + + if (!polar) + { + c2 /= alpha; + } + } + + return new Components(c0, c1, c2, alpha); + } + + private static void FixHues(ref Components start, ref Components end, string method) + { + var h1 = start.C2; + var h2 = end.C2; + + // a powerless hue takes the other one + if (double.IsNaN(h1) && double.IsNaN(h2)) + { + h1 = h2 = 0; + } + else if (double.IsNaN(h1)) + { + h1 = h2; + } + else if (double.IsNaN(h2)) + { + h2 = h1; + } + + var difference = h2 - h1; + + switch (method) + { + case "longer": + if (difference > 0 && difference < 180) + { + h1 += 360; + } + else if (difference > -180 && difference <= 0) + { + h2 += 360; + } + + break; + case "increasing": + if (difference < 0) + { + h2 += 360; + } + + break; + case "decreasing": + if (difference > 0) + { + h1 += 360; + } + + break; + default: + if (difference > 180) + { + h1 += 360; + } + else if (difference < -180) + { + h2 += 360; + } + + break; + } + + start = start with { C2 = h1 }; + end = end with { C2 = h2 }; + } + + private static Components ToSpace(RenderColor color, string space) + { + var r = color.R / 255.0; + var g = color.G / 255.0; + var b = color.B / 255.0; + var alpha = color.A / 255.0; + + switch (space) + { + case "hsl": + { + var (h, s, l) = RgbToHsl(r, g, b); + return new Components(s, l, h, alpha); + } + case "hwb": + { + var (h, _, _) = RgbToHsl(r, g, b); + var white = Math.Min(r, Math.Min(g, b)); + var black = 1 - Math.Max(r, Math.Max(g, b)); + return new Components(white, black, white + black >= 1 ? double.NaN : h, alpha); + } + } + + var (lr, lg, lb) = (ToLinear(r), ToLinear(g), ToLinear(b)); + + switch (space) + { + case "srgb-linear": + return new Components(lr, lg, lb, alpha); + case "oklab": + { + var (l, a, bb) = LinearToOklab(lr, lg, lb); + return new Components(l, a, bb, alpha); + } + case "oklch": + { + var (l, a, bb) = LinearToOklab(lr, lg, lb); + return ToPolar(l, a, bb, alpha, 0.0002); + } + case "xyz-d65": + { + var (x, y, z) = LinearToXyz(lr, lg, lb); + return new Components(x, y, z, alpha); + } + case "xyz-d50": + { + var (x, y, z) = D65ToD50(LinearToXyz(lr, lg, lb)); + return new Components(x, y, z, alpha); + } + case "lab": + { + var (l, a, bb) = XyzD50ToLab(D65ToD50(LinearToXyz(lr, lg, lb))); + return new Components(l, a, bb, alpha); + } + case "lch": + { + var (l, a, bb) = XyzD50ToLab(D65ToD50(LinearToXyz(lr, lg, lb))); + return ToPolar(l, a, bb, alpha, 0.0015 * 100); + } + default: + // srgb (and the wide gamut RGB spaces, which sRGB colors are drawn in anyway) + return new Components(r, g, b, alpha); + } + } + + private static RenderColor FromSpace(Components c, string space) + { + double r, g, b; + + switch (space) + { + case "hsl": + (r, g, b) = HslToRgb(c.C2, c.C0, c.C1); + break; + case "hwb": + { + var white = c.C0; + var black = c.C1; + + if (white + black >= 1) + { + var grey = white / (white + black); + (r, g, b) = (grey, grey, grey); + } + else + { + (r, g, b) = HslToRgb(c.C2, 1, 0.5); + r = (r * (1 - white - black)) + white; + g = (g * (1 - white - black)) + white; + b = (b * (1 - white - black)) + white; + } + + break; + } + case "srgb-linear": + (r, g, b) = (FromLinear(c.C0), FromLinear(c.C1), FromLinear(c.C2)); + break; + case "oklab": + (r, g, b) = FromLinear(OklabToLinear(c.C0, c.C1, c.C2)); + break; + case "oklch": + { + var (a, bb) = FromPolar(c.C1, c.C2); + (r, g, b) = FromLinear(OklabToLinear(c.C0, a, bb)); + break; + } + case "xyz-d65": + (r, g, b) = FromLinear(XyzToLinear((c.C0, c.C1, c.C2))); + break; + case "xyz-d50": + (r, g, b) = FromLinear(XyzToLinear(D50ToD65((c.C0, c.C1, c.C2)))); + break; + case "lab": + (r, g, b) = FromLinear(XyzToLinear(D50ToD65(LabToXyzD50(c.C0, c.C1, c.C2)))); + break; + case "lch": + { + var (a, bb) = FromPolar(c.C1, c.C2); + (r, g, b) = FromLinear(XyzToLinear(D50ToD65(LabToXyzD50(c.C0, a, bb)))); + break; + } + default: + (r, g, b) = (c.C0, c.C1, c.C2); + break; + } + + return new RenderColor(ToByte(r), ToByte(g), ToByte(b), ToByte(c.Alpha)); + } + + private static byte ToByte(double value) => (byte)Math.Clamp(Math.Round(value * 255), 0, 255); + + private static Components ToPolar(double l, double a, double b, double alpha, double achromatic) + { + var chroma = Math.Sqrt((a * a) + (b * b)); + var hue = chroma <= achromatic ? double.NaN : ((Math.Atan2(b, a) * 180 / Math.PI) + 360) % 360; + return new Components(l, chroma, hue, alpha); + } + + private static (double A, double B) FromPolar(double chroma, double hue) + { + var radians = (double.IsNaN(hue) ? 0 : hue) * Math.PI / 180; + return (chroma * Math.Cos(radians), chroma * Math.Sin(radians)); + } + + private static double ToLinear(double c) => c <= 0.04045 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4); + + private static double FromLinear(double c) => c <= 0.0031308 ? c * 12.92 : (1.055 * Math.Pow(Math.Max(0, c), 1 / 2.4)) - 0.055; + + private static (double R, double G, double B) FromLinear((double R, double G, double B) c) => (FromLinear(c.R), FromLinear(c.G), FromLinear(c.B)); + + private static (double L, double A, double B) LinearToOklab(double r, double g, double b) + { + var l = Math.Cbrt((0.4122214708 * r) + (0.5363325363 * g) + (0.0514459929 * b)); + var m = Math.Cbrt((0.2119034982 * r) + (0.6806995451 * g) + (0.1073969566 * b)); + var s = Math.Cbrt((0.0883024619 * r) + (0.2817188376 * g) + (0.6299787005 * b)); + return ( + (0.2104542553 * l) + (0.7936177850 * m) - (0.0040720468 * s), + (1.9779984951 * l) - (2.4285922050 * m) + (0.4505937099 * s), + (0.0259040371 * l) + (0.7827717662 * m) - (0.8086757660 * s)); + } + + private static (double R, double G, double B) OklabToLinear(double l, double a, double b) + { + var l1 = l + (0.3963377774 * a) + (0.2158037573 * b); + var m1 = l - (0.1055613458 * a) - (0.0638541728 * b); + var s1 = l - (0.0894841775 * a) - (1.2914855480 * b); + var (l3, m3, s3) = (l1 * l1 * l1, m1 * m1 * m1, s1 * s1 * s1); + return ( + (4.0767416621 * l3) - (3.3077115913 * m3) + (0.2309699292 * s3), + (-1.2684380046 * l3) + (2.6097574011 * m3) - (0.3413193965 * s3), + (-0.0041960863 * l3) - (0.7034186147 * m3) + (1.7076147010 * s3)); + } + + private static (double X, double Y, double Z) LinearToXyz(double r, double g, double b) => ( + (0.41239079926595934 * r) + (0.357584339383878 * g) + (0.1804807884018343 * b), + (0.21263900587151027 * r) + (0.715168678767756 * g) + (0.07219231536073371 * b), + (0.01933081871559182 * r) + (0.11919477979462598 * g) + (0.9505321522496607 * b)); + + private static (double R, double G, double B) XyzToLinear((double X, double Y, double Z) c) => ( + (3.2409699419045226 * c.X) - (1.537383177570094 * c.Y) - (0.4986107602930034 * c.Z), + (-0.9692436362808796 * c.X) + (1.8759675015077202 * c.Y) + (0.04155505740717559 * c.Z), + (0.05563007969699366 * c.X) - (0.20397695888897652 * c.Y) + (1.0569715142428786 * c.Z)); + + private static (double X, double Y, double Z) D65ToD50((double X, double Y, double Z) c) => ( + (1.0479298208405488 * c.X) + (0.022946793341019088 * c.Y) - (0.05019222954313557 * c.Z), + (0.029627815688159344 * c.X) + (0.990434484573249 * c.Y) - (0.01707382502938514 * c.Z), + (-0.009243058152591178 * c.X) + (0.015055144896577895 * c.Y) + (0.7518742899580008 * c.Z)); + + private static (double X, double Y, double Z) D50ToD65((double X, double Y, double Z) c) => ( + (0.9554734527042182 * c.X) - (0.023098536874261423 * c.Y) + (0.0632593086610217 * c.Z), + (-0.028369706963208136 * c.X) + (1.0099954580058226 * c.Y) + (0.021041398966943008 * c.Z), + (0.012314001688319899 * c.X) - (0.020507696433477912 * c.Y) + (1.3303659366080753 * c.Z)); + + private const double LabEpsilon = 216.0 / 24389.0; + private const double LabKappa = 24389.0 / 27.0; + private static readonly (double X, double Y, double Z) D50White = (0.3457 / 0.3585, 1.0, (1.0 - 0.3457 - 0.3585) / 0.3585); + + private static (double L, double A, double B) XyzD50ToLab((double X, double Y, double Z) c) + { + static double F(double t) => t > LabEpsilon ? Math.Cbrt(t) : ((LabKappa * t) + 16) / 116; + var fx = F(c.X / D50White.X); + var fy = F(c.Y / D50White.Y); + var fz = F(c.Z / D50White.Z); + return ((116 * fy) - 16, 500 * (fx - fy), 200 * (fy - fz)); + } + + private static (double X, double Y, double Z) LabToXyzD50(double l, double a, double b) + { + var fy = (l + 16) / 116; + var fx = (a / 500) + fy; + var fz = fy - (b / 200); + var x = Math.Pow(fx, 3) > LabEpsilon ? Math.Pow(fx, 3) : ((116 * fx) - 16) / LabKappa; + var y = l > LabKappa * LabEpsilon ? Math.Pow(fy, 3) : l / LabKappa; + var z = Math.Pow(fz, 3) > LabEpsilon ? Math.Pow(fz, 3) : ((116 * fz) - 16) / LabKappa; + return (x * D50White.X, y * D50White.Y, z * D50White.Z); + } + + private static (double H, double S, double L) RgbToHsl(double r, double g, double b) + { + var max = Math.Max(r, Math.Max(g, b)); + var min = Math.Min(r, Math.Min(g, b)); + var l = (max + min) / 2; + var d = max - min; + + if (d <= 1e-9) + { + return (double.NaN, 0, l); + } + + var s = l is 0 or 1 ? 0 : (max - l) / Math.Min(l, 1 - l); + double h; + + if (max == r) + { + h = ((g - b) / d) + (g < b ? 6 : 0); + } + else if (max == g) + { + h = ((b - r) / d) + 2; + } + else + { + h = ((r - g) / d) + 4; + } + + return (h * 60, s, l); + } + + private static (double R, double G, double B) HslToRgb(double h, double s, double l) + { + h = double.IsNaN(h) ? 0 : ((h % 360) + 360) % 360; + + double F(double n) + { + var k = (n + (h / 30)) % 12; + var a = s * Math.Min(l, 1 - l); + return l - (a * Math.Max(-1, Math.Min(k - 3, Math.Min(9 - k, 1)))); + } + + return (F(0), F(8), F(4)); + } +} diff --git a/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.Paint.cs b/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.Paint.cs index 60653a0..c544761 100644 --- a/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.Paint.cs +++ b/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.Paint.cs @@ -240,7 +240,8 @@ private static void DrawBorderImage(SKCanvas canvas, DrawBorderImageCommand comm var scaleLeft = sliceLeft > 0f ? widthLeft / sliceLeft : 1f; var scaleRight = sliceRight > 0f ? widthRight / sliceRight : 1f; - using var paint = new SKPaint { IsAntialias = true }; + // the parts meet at fractional positions, where antialiased edges would leave seams + using var paint = new SKPaint { IsAntialias = false }; for (var row = 0; row < 3; row++) { @@ -286,6 +287,8 @@ private static float ResolveSlice(RenderBorderImageSlice slice, float imageSize) using var paint = CreateGradientPaint(gradient, new RenderRect(0f, 0f, width, height)); surface.Canvas.Clear(SKColors.Transparent); + // the gradient fills all of the image's whole pixels (a part of one would be transparent) + surface.Canvas.Scale(pixelWidth / width, pixelHeight / height); surface.Canvas.DrawRect(new SKRect(0f, 0f, width, height), paint); return surface.Snapshot(); } @@ -399,7 +402,7 @@ private static void DrawImagePart( /// Ends a mask scope: the group painted since keeps only what /// the mask layers cover, by drawing them with destination-in onto it. /// - private static void ApplyMask(SKCanvas canvas, PushMaskCommand command) + private static void ApplyMask(SKCanvas canvas, PushMaskCommand command, FontFaceSet fonts) { using var destinationIn = new SKPaint { BlendMode = SKBlendMode.DstIn }; canvas.SaveLayer(destinationIn); @@ -409,6 +412,21 @@ private static void ApplyMask(SKCanvas canvas, PushMaskCommand command) for (var index = command.Layers.Count - 1; index >= 0; index--) { var layer = command.Layers[index]; + + if (layer.Paint is RenderTextMaskPaint textMask) + { + canvas.Save(); + canvas.ClipRect(ToSkRect(layer.Area)); + + foreach (var text in textMask.Texts) + { + DrawText(canvas, text with { Color = new RenderColor(0, 0, 0), DecorationColor = new RenderColor(0, 0, 0) }, fonts); + } + + canvas.Restore(); + continue; + } + using var paint = CreateFillPaint(layer.Paint, layer.PaintArea); if (layer.UseLuminance) diff --git a/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.cs b/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.cs index 4024f4b..310ffa4 100644 --- a/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.cs +++ b/src/AngleSharp.Renderer/Skia/SkiaRenderBackend.cs @@ -333,7 +333,7 @@ private static void DrawCommand(SKCanvas canvas, RenderCommand command, FontFace state.Masks.Push(pushMask); break; case PopMaskCommand: - ApplyMask(canvas, state.Masks.Pop()); + ApplyMask(canvas, state.Masks.Pop(), fonts); break; case FillRectCommand fill: DrawFillRect(canvas, fill); @@ -1001,7 +1001,7 @@ private static SKPaint CreateGradientPaint(RenderGradient gradient, RenderRect r _ => 0f, }; - var (colors, rawPositions) = ResolveGradientStops(gradient.Stops, referenceLength); + var (colors, rawPositions) = ResolveGradientStops(gradient.Stops, referenceLength, gradient.ColorSpace, gradient.HueInterpolation); var tileMode = gradient.Repeating ? SKShaderTileMode.Repeat : SKShaderTileMode.Clamp; @@ -1055,7 +1055,7 @@ private static float ComputeGradientLineLength(RenderGradient gradient, RenderRe /// transparent stop takes the color of its neighbours on either side (fading `white` to /// `transparent` must not pass through grey, as `transparent` is transparent black). /// - private static (SKColor[] Colors, float[] Positions) ResolveGradientStops(IReadOnlyList stops, float referenceLength) + private static (SKColor[] Colors, float[] Positions) ResolveGradientStops(IReadOnlyList stops, float referenceLength, string? colorSpace = null, string? hueInterpolation = null) { var count = stops.Count; var positions = new float?[count]; @@ -1112,6 +1112,33 @@ private static (SKColor[] Colors, float[] Positions) ResolveGradientStops(IReadO } } + // hints and other color spaces are sampled into stops (see GradientInterpolation) + if (colorSpace is not null || stops.Any(static stop => stop.IsHint)) + { + var colorStops = new List<(RenderColor Color, float Position)>(count); + var hints = new List(count); + + for (var i = 0; i < count; i++) + { + var position = Math.Clamp(positions[i]!.Value, 0f, 1f); + + if (stops[i].IsHint) + { + if (hints.Count > 0) + { + hints[^1] = position; + } + + continue; + } + + colorStops.Add((stops[i].Color, position)); + hints.Add(float.NaN); + } + + return GradientInterpolation.Build(colorStops, hints, colorSpace, hueInterpolation); + } + var colors = new List(count + 2); var resolved = new List(count + 2); From d1a3f4a63f0d27864c179d0543577ff0da0f84bc Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 16:20:57 +0100 Subject: [PATCH 08/23] Declared min version --- .github/workflows/ci.yml | 2 +- .github/workflows/update-snapshots.yml | 2 +- CHANGELOG.md | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1301e75..16123b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ env: # Snapshot baselines are per-platform and committed; a missing one is a gap, never a pass. ANGLESHARP_SNAPSHOT_STRICT: 1 ANGLESHARP_VERSION: 1.10.0 - ANGLESHARP_CSS_VERSION: 1.4.1 + ANGLESHARP_CSS_VERSION: 1.5.0 jobs: can_document: diff --git a/.github/workflows/update-snapshots.yml b/.github/workflows/update-snapshots.yml index f1ebe4d..a930cc0 100644 --- a/.github/workflows/update-snapshots.yml +++ b/.github/workflows/update-snapshots.yml @@ -16,7 +16,7 @@ permissions: env: ANGLESHARP_VERSION: 1.10.0 - ANGLESHARP_CSS_VERSION: 1.4.1 + ANGLESHARP_CSS_VERSION: 1.5.0 jobs: # Keep this matrix identical to the `test` matrix in ci.yml, images included - a baseline diff --git a/CHANGELOG.md b/CHANGELOG.md index 58df16f..05dbfcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,12 +24,13 @@ Released on tbd. - Fixed an absolutely positioned box with `height: fit-content` (e.g. a popover) being stretched between `top` and `bottom`, and centering one of an automatic height with `margin: auto` - Fixed `scrollWidth` and `scrollHeight` leaving out text extending beyond its box (e.g. cut off by an ellipsis) - Updated the document of an iframe to keep the render device of its browsing context, if it has one of its own +- Updated to use a minimum of AngleSharp.Css 1.5.0 - Added color hints and color interpolation methods (e.g. `in oklch`, `in hsl longer hue`) of gradients - Added `background-clip: text` - Added `object` elements showing an image instead of their fallback content - Added `align-items: baseline` (and `align-self`) for flex items in a row: an item without text sits on the baseline with the bottom of its border box (e.g. a rule after a heading's text), where it was at the top of the line - Added `getImageData()`, `putImageData()` and `createImageData()` of the canvas (`ImageData`) -- Added `paint()` background images of the CSS Painting API (painted by AngleSharp.Css's paint worklets); requires AngleSharp.Css 1.5.0 +- Added `paint()` background images of the CSS Painting API # 0.12.0 From 8563255be46a543238811716159e0ca23699879e Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 18:11:08 +0100 Subject: [PATCH 09/23] Docs update for new input pickers API --- AGENTS.md | 5 +- CHANGELOG.md | 3 + docs/general/02-Interactivity.md | 82 ++++++++++++++ .../Controls/IInputControl.cs | 37 +++++++ .../Controls/IInputPicker.cs | 100 ++++++++++++++++++ 5 files changed, 225 insertions(+), 2 deletions(-) create mode 100644 src/AngleSharp.Renderer/Controls/IInputControl.cs create mode 100644 src/AngleSharp.Renderer/Controls/IInputPicker.cs diff --git a/AGENTS.md b/AGENTS.md index 64be7db..2652b72 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,9 +138,10 @@ Every text feature exists twice - in the paragraph path (whole lines as strings) ### Form controls - A form control's look (border, padding, background, margins, round radio, the `13.3333px Arial` font) comes from the UA stylesheet. A native select's padding is 0 there; its label inset (`FormControlSelectLabelInset`) and arrow space belong to the control. `ApplyFormControlDefaults` only fills in the element-derived intrinsic size (text fields 150px, checkbox/radio from font size, buttons/selects/file inputs from their label) when `width`/`height` are unset. - `PaintFormControl` paints values, labels, the selected option, checked fills, color swatches, range track/thumb and file inputs; `