Skip to content

Commit d8c4c00

Browse files
committed
R4: real keep-with-next, fixing a genuine pre-existing gap
Found while implementing this stage: keep-with-next never actually worked for the ordinary case. The old mechanism only ran as a side effect of RelocateIfNeeded moving a child that was ITSELF break-inside: avoid or monolithic - so it only ever fired when the box AFTER a break-after:avoid heading also happened to be avoid/monolithic. The common case (an unremarkable paragraph that simply doesn't fit after a keep-with-next-chained heading) never triggered it: the heading was left stranded alone at the bottom of its page while the paragraph moved on by itself. Confirmed via a calibrated reproduction: heading provably fit alone on page 0 in isolation, but adding the paragraph back left the heading on page 0 anyway with the paragraph alone on page 1. The existing KeepWithNext_HeadingStaysWithFollowingParagraph PDF test didn't catch this because it only asserts a page COUNT of 2, which is identical whether the pair moves together or splits - both outcomes total 2 pages either way. New tests (StageR4KeepWithNextTest) check the fragment tree directly for which page actually holds the heading, and would have failed against the old behavior. BlockFragmentation.EnforceKeepWithNext is the fix: checked unconditionally after a child finishes laying out (and after any R3 relocation), not only as R3's side effect - if a page break actually falls between a child and a preceding sibling chained to it by break-after/before:avoid, the whole chained run is pulled down to the child's page and the child is relaid out fresh. RelocateIfNeeded's own keep-with-next handling was removed as redundant: after it moves a child, the preceding sibling is exactly as stranded as in the ordinary case, and EnforceKeepWithNext (called right after in the same loop iteration) now covers both uniformly. Also corrected course on two of the plan's own framing details, both discovered only by implementing them: BlockFragmentation.cs is not being retired (margin truncation is pre-placement arithmetic with nowhere else to naturally live, same timing as the forced-break check); the "R2" stage was folded into R3 last commit since it had no distinct work of its own in this architecture. Full regression suite (40 IntegrationTest + 16 PdfSharp tests) passes.
1 parent 8903205 commit d8c4c00

3 files changed

Lines changed: 181 additions & 18 deletions

File tree

‎Source/HtmlRenderer/Core/Dom/CssBox.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,13 @@ protected virtual void PerformLayoutImp(RGraphics g)
944944
// inside a break-inside:avoid container - so check again.
945945
if (BubbleChildPendingToken(childBox, i))
946946
return;
947+
948+
BlockFragmentation.EnforceKeepWithNext(g, childBox);
949+
950+
// Same reasoning as above: EnforceKeepWithNext's own relayout of childBox can
951+
// itself surface a nested break.
952+
if (BubbleChildPendingToken(childBox, i))
953+
return;
947954
}
948955
ActualRight = CalculateActualRight();
949956

‎Source/HtmlRenderer/Core/Fragmentation/BlockFragmentation.cs‎

Lines changed: 70 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@ namespace TheArtOfDev.HtmlRenderer.Core.Fragmentation
1111
/// equivalents matching PeachPDF's architecture (see the fragmentation-engine-parity plan): forced
1212
/// breaks (<see cref="TryGetForcedBreakTarget"/>, plan R1) go through <c>CssBox</c>'s real pass loop
1313
/// across fragmentainers; <c>break-inside:avoid</c>/monolithic relocation (<see cref="RelocateIfNeeded"/>,
14-
/// plan R3) relays the child out fresh at its target position within the SAME pass, rather than
15-
/// shifting already-finished geometry - real relayout, but not yet a cross-pass token, since nothing
16-
/// downstream has been touched yet when it fires. Margin truncation (<see cref="ResolveBlockTop"/>)
17-
/// and keep-with-next (still inside <see cref="RelocateIfNeeded"/>) remain the older flat
18-
/// <c>OffsetTop</c> correction for now, until plan R4 converts them together.
14+
/// plan R3) and keep-with-next (<see cref="EnforceKeepWithNext"/>, plan R4) both relay the affected
15+
/// box out fresh at its target position within the SAME pass, rather than shifting already-finished
16+
/// geometry - real relayout, but not yet a cross-pass token, since nothing downstream has been touched
17+
/// yet when either fires. Margin truncation (<see cref="ResolveBlockTop"/>) remains the older
18+
/// pre-placement arithmetic correction, since it needs no relayout at all - it's already applied
19+
/// before a box is ever positioned, the same timing <see cref="TryGetForcedBreakTarget"/> uses.
1920
/// </summary>
2021
internal static class BlockFragmentation
2122
{
@@ -91,19 +92,18 @@ internal static bool TryGetForcedBreakTarget(CssBox box, CssBox prevSibling, dou
9192
/// subtree) has finished laying out this pass. If the child straddles a page boundary and either
9293
/// asks not to be broken (<c>break-inside: avoid</c>) or may not be broken at all (a replaced
9394
/// element, a scroll container), and it fits within a single page's height, the child is relaid
94-
/// out fresh at the next page's content top - and any preceding siblings chained to it by
95-
/// <c>break-after</c>/<c>break-before: avoid</c> (keep-with-next, css-break-3 §3.1) are shifted
96-
/// there too, via the older <c>OffsetTop</c> correction, since they already finished this pass and
97-
/// keep-with-next itself isn't converted yet.
95+
/// out fresh at the next page's content top. Does not itself consider whether this leaves a
96+
/// preceding sibling stranded - <see cref="EnforceKeepWithNext"/>, called right after this in the
97+
/// same loop iteration, catches that uniformly for every trigger (this one included).
9898
/// </summary>
9999
/// <remarks>
100100
/// The child is genuinely relaid out (<c>ResumeAt</c> + <c>PerformLayout</c>), not
101-
/// <c>OffsetTop</c>-shifted the way it used to be and the way its preceding keep-with-next run
102-
/// still is: nothing after this child in its parent's loop has been touched yet this pass, so
103-
/// re-entering its own layout at the new top is cheap, and it is also more correct than a flat
104-
/// shift - any of the child's OWN descendants that themselves have <c>break-inside:avoid</c> or a
105-
/// nested forced break get to make their own decision relative to the real page boundaries at the
106-
/// new position, rather than blindly carrying whatever decision they made at the old one.
101+
/// <c>OffsetTop</c>-shifted: nothing after this child in its parent's loop has been touched yet
102+
/// this pass, so re-entering its own layout at the new top is cheap, and it is also more correct
103+
/// than a flat shift - any of the child's OWN descendants that themselves have
104+
/// <c>break-inside:avoid</c> or a nested forced break get to make their own decision relative to
105+
/// the real page boundaries at the new position, rather than blindly carrying whatever decision
106+
/// they made at the old one.
107107
/// </remarks>
108108
internal static void RelocateIfNeeded(RGraphics g, CssBox child)
109109
{
@@ -130,14 +130,66 @@ internal static void RelocateIfNeeded(RGraphics g, CssBox child)
130130
return; // Fits on no single page - left in place rather than moved somewhere it also won't fit.
131131

132132
var target = container.PageTopOf(topSlot + 1);
133-
var delta = target - top;
133+
child.ResumeAt(null, target);
134+
child.PerformLayout(g);
135+
}
136+
137+
/// <summary>
138+
/// Called by a block container's child loop right after <paramref name="child"/> has finished
139+
/// laying out (and, if applicable, been relocated by <see cref="RelocateIfNeeded"/>) this pass. If
140+
/// a page break actually falls between <paramref name="child"/> and its immediately preceding
141+
/// in-flow sibling, and either of them asks it not to (<c>break-after</c>/<c>break-before: avoid</c>,
142+
/// keep-with-next, css-break-3 §3.1), the whole preceding run chained to that sibling is pulled
143+
/// down to join <paramref name="child"/>'s page instead of leaving it stranded on the page it just
144+
/// left - then <paramref name="child"/> itself is relaid out fresh, since its own natural top
145+
/// depends on the now-shifted sibling's new bottom.
146+
/// </summary>
147+
/// <remarks>
148+
/// A real gap found while building this: the pre-existing keep-with-next code only ever ran as a side effect
149+
/// of <see cref="RelocateIfNeeded"/> relocating <paramref name="child"/> itself - so it only ever
150+
/// fired when <paramref name="child"/> was ALSO <c>break-inside:avoid</c> or monolithic. The
151+
/// ordinary case (an unremarkable paragraph that simply doesn't fit after a keep-with-next-chained
152+
/// heading) never triggered it at all: the heading was left stranded on the page it started on
153+
/// while the paragraph moved on alone. This method is the general fix - checked unconditionally,
154+
/// not only after a relocation - and <see cref="RelocateIfNeeded"/>'s own preceding-run handling
155+
/// was removed as redundant once this covers it too (after a relocation moves the child, the
156+
/// preceding sibling is exactly as "left behind" as in the ordinary case, and this method treats
157+
/// both identically).
158+
/// </remarks>
159+
internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
160+
{
161+
var container = child.HtmlContainer;
162+
if (container == null || !container.HasRealPageGrid || child.IsOutOfFlow)
163+
return;
164+
165+
var prevSibling = DomUtils.GetPreviousSibling(child);
166+
if (prevSibling == null || prevSibling.IsOutOfFlow)
167+
return;
168+
169+
if (!BreakValues.AvoidsBreak(prevSibling.BreakAfter) && !BreakValues.AvoidsBreak(child.BreakBefore))
170+
return;
171+
172+
var prevBottomSlot = container.PageIndexOf(Math.Max(prevSibling.Location.Y, prevSibling.ActualBottom - 0.01));
173+
var childTopSlot = container.PageIndexOf(child.Location.Y);
174+
if (childTopSlot <= prevBottomSlot)
175+
return; // No break actually falls between them - nothing to enforce.
176+
177+
var run = CollectPrecedingKeepWithNextRun(prevSibling);
178+
run.Add(prevSibling);
134179

135-
foreach (var member in CollectPrecedingKeepWithNextRun(child))
180+
// Simplified for this stage: always pull the whole run to child's page, without checking
181+
// whether the run then fits alongside child there - the progressive relaxation ladder
182+
// (trim the run, drop it, leave the container behind) is a later plan stage's refinement.
183+
var delta = container.PageTopOf(childTopSlot) - run[0].Location.Y;
184+
if (delta <= 0)
185+
return; // Defensive - a positive shift is the only sensible outcome here.
186+
187+
foreach (var member in run)
136188
{
137189
member.OffsetTop(delta);
138190
}
139191

140-
child.ResumeAt(null, target);
192+
child.ResumeAt(null, null);
141193
child.PerformLayout(g);
142194
}
143195

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
using System.Collections.Generic;
2+
using System.Drawing;
3+
using System.Linq;
4+
using System.Reflection;
5+
using Microsoft.VisualStudio.TestTools.UnitTesting;
6+
using TheArtOfDev.HtmlRenderer.Core;
7+
using TheArtOfDev.HtmlRenderer.Core.Fragments;
8+
using TheArtOfDev.HtmlRenderer.WinForms;
9+
10+
namespace TheArtOfDev.HtmlRenderer.IntegrationTest;
11+
12+
/// <summary>
13+
/// Verifies the R4 stage of the fragmentation-engine-parity plan: keep-with-next
14+
/// (<c>BlockFragmentation.EnforceKeepWithNext</c>) now fires for the ordinary case, not just as a side
15+
/// effect of the following box also being <c>break-inside:avoid</c>/monolithic.
16+
/// </summary>
17+
/// <remarks>
18+
/// The pre-existing <c>KeepWithNext_HeadingStaysWithFollowingParagraph</c> PDF test (still passing, still
19+
/// kept) only ever asserted a page COUNT of 2 - which is also exactly what you get if the heading is left
20+
/// stranded alone at the bottom of page 1 while the paragraph moves to page 2 by itself (2 pages either
21+
/// way). It never actually proved the heading and paragraph land on the SAME page. This test does, using
22+
/// the fragment tree directly: filler content is calibrated so the heading provably fits alone on page 0
23+
/// in isolation (confirmed by a companion assertion with no trailing paragraph), then, with the paragraph
24+
/// present, both must appear in the SAME fragmentainer.
25+
/// </remarks>
26+
[TestClass]
27+
[DoNotParallelize]
28+
public sealed class StageR4KeepWithNextTest
29+
{
30+
private const int FillerCount = 39;
31+
32+
private static HtmlContainerInt GetInternal(HtmlContainer wrapper)
33+
{
34+
var prop = typeof(HtmlContainer).GetProperty("HtmlContainerInt", BindingFlags.NonPublic | BindingFlags.Instance)!;
35+
return (HtmlContainerInt)prop.GetValue(wrapper)!;
36+
}
37+
38+
private static async Task<FragmentTree> LayoutAsync(string bodyHtml)
39+
{
40+
using var wrapper = new HtmlContainer();
41+
await wrapper.SetHtml($"<html><body>{bodyHtml}</body></html>");
42+
43+
var container = GetInternal(wrapper);
44+
container.PageSize = new TheArtOfDev.HtmlRenderer.Adapters.Entities.RSize(595, 800);
45+
container.MarginTop = 20;
46+
wrapper.MaxSize = new SizeF(595, 0);
47+
48+
using var bitmap = new Bitmap(595, 20000);
49+
using var g = Graphics.FromImage(bitmap);
50+
wrapper.PerformLayout(g);
51+
52+
return container.FragmentTree;
53+
}
54+
55+
private static string AllText(BoxFragment fragment)
56+
{
57+
var words = new List<string>();
58+
Collect(fragment, words);
59+
return string.Join(" ", words);
60+
61+
static void Collect(BoxFragment f, List<string> into)
62+
{
63+
foreach (var word in f.Words)
64+
into.Add(word.Word.Text);
65+
foreach (var child in f.Children)
66+
Collect(child, into);
67+
}
68+
}
69+
70+
private static string Filler() =>
71+
string.Concat(Enumerable.Repeat("<p style='margin:0;'>filler line of text</p>", FillerCount));
72+
73+
// WinForms reports media type "screen", not "print" - the UA stylesheet's h1-h6 { break-after: avoid }
74+
// rule lives under @media print (see PdfSharpAdapter vs RAdapter.DefaultMediaType) and never applies
75+
// to this IntegrationTest project's WinForms-based HtmlContainer. Set it explicitly rather than
76+
// relying on the UA default.
77+
private const string HeadingStyle = "margin:0; break-after: avoid;";
78+
79+
[TestMethod]
80+
public async Task Precondition_HeadingAloneFitsOnPageZero()
81+
{
82+
// Establishes the calibration this stage's real test depends on: with FillerCount fillers and no
83+
// trailing paragraph, the heading fits on the same page as the filler (a stray trailing blank
84+
// fragmentainer past it is an unrelated pre-existing quirk, not what this checks).
85+
var tree = await LayoutAsync($"{Filler()}<h4 style='{HeadingStyle}'>Section heading</h4>");
86+
StringAssert.Contains(AllText(tree.Fragmentainers[0].Root), "Section heading");
87+
}
88+
89+
[TestMethod]
90+
public async Task HeadingAndParagraph_LandOnTheSamePage_NotStranded()
91+
{
92+
var tree = await LayoutAsync(
93+
$"{Filler()}<h4 style='{HeadingStyle}'>Section heading</h4><p style='margin:0;'>Paragraph right after the heading.</p>");
94+
95+
// Page 0's own text must NOT contain the heading - it should have been pulled forward to join
96+
// the paragraph, not left stranded where the precondition test shows it would otherwise fit.
97+
var pageZeroText = AllText(tree.Fragmentainers[0].Root);
98+
StringAssert.DoesNotMatch(pageZeroText, new System.Text.RegularExpressions.Regex("Section heading"));
99+
100+
var withHeading = tree.Fragmentainers.Select(f => AllText(f.Root)).FirstOrDefault(t => t.Contains("Section heading"));
101+
Assert.IsNotNull(withHeading, "heading should appear on some page");
102+
StringAssert.Contains(withHeading, "Paragraph right after the heading.");
103+
}
104+
}

0 commit comments

Comments
 (0)