Skip to content

Commit 9fa176a

Browse files
committed
Build the box tree again on a media change without loading
1 parent 84b0e96 commit 9fa176a

3 files changed

Lines changed: 152 additions & 40 deletions

File tree

‎Source/HtmlRenderer/Core/HtmlContainerInt.cs‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -125,13 +125,11 @@ public sealed class HtmlContainerInt : IDisposable
125125
private CssData _cssData;
126126

127127
/// <summary>
128-
/// The html and base stylesheet last given to <see cref="SetHtmlAsync"/>, kept so the cascade can be
129-
/// re-run when a viewport change alters which <c>@media</c> rules apply.
128+
/// The html last given to <see cref="SetHtmlAsync"/>, kept so the box tree can be built again
129+
/// when a viewport change alters which <c>@media</c> rules apply.
130130
/// </summary>
131131
private string _htmlSource;
132132

133-
private CssData _baseCssData;
134-
135133
/// <summary>
136134
/// The device the current cascade was computed against.
137135
/// </summary>
@@ -599,26 +597,37 @@ public async Task SetHtmlAsync(string htmlSource, CssData baseCssData = null)
599597
{
600598
Clear();
601599
_htmlSource = htmlSource;
602-
_baseCssData = baseCssData;
603600

604601
if (!string.IsNullOrEmpty(htmlSource))
605602
{
606603
_loadComplete = false;
607604
_cssData = baseCssData ?? _adapter.DefaultCssData;
608605

609-
DomParser parser = new DomParser(_cssParser);
610-
(_root, _cssData) = await parser.GenerateCssTree(htmlSource, this, _cssData).ConfigureAwait(false);
611-
_cascadeMedia = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
612-
if (_root != null)
613-
{
614-
_selectionHandler = new SelectionHandler(_root);
615-
}
606+
var parser = new DomParser(_cssParser);
607+
CssBox root;
608+
(root, _cssData) = await parser.LoadAsync(htmlSource, this, _cssData).ConfigureAwait(false);
609+
BuildRoot(parser, root);
610+
}
611+
}
612+
613+
/// <summary>
614+
/// Builds the box tree from a parsed document and the loaded <see cref="_cssData"/>, and makes it the root.
615+
/// </summary>
616+
private void BuildRoot(DomParser parser, CssBox root)
617+
{
618+
parser.BuildCssTree(root, this, _cssData);
619+
_root = root;
620+
_cascadeMedia = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
621+
if (_root != null)
622+
{
623+
_selectionHandler = new SelectionHandler(_root);
616624
}
617625
}
618626

619627
/// <summary>
620628
/// Re-runs the cascade when a viewport change flips the outcome of an <c>@media</c> condition
621-
/// (CSS Conditional 3 §2), by parsing the document again.
629+
/// (CSS Conditional 3 §2), by building the box tree again. Loads nothing, the style sheets and
630+
/// fonts from <see cref="SetHtmlAsync"/> are reused, so it's safe in a synchronous layout.
622631
/// </summary>
623632
private void RefreshMediaDependentCascade()
624633
{
@@ -627,8 +636,10 @@ private void RefreshMediaDependentCascade()
627636
var media = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
628637
if (!_cssData.MediaOutcomeChanged(_cascadeMedia, media)) return;
629638

630-
// PerformLayout is synchronous, so this blocks on the async SetHtmlAsync
631-
SetHtmlAsync(_htmlSource, _baseCssData).GetAwaiter().GetResult();
639+
var parser = new DomParser(_cssParser);
640+
var root = parser.ParseDocument(_htmlSource, this);
641+
Clear();
642+
BuildRoot(parser, root);
632643
}
633644

634645
/// <summary>

‎Source/HtmlRenderer/Core/Parse/DomParser.cs‎

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -52,51 +52,75 @@ public DomParser(CssParser cssParser)
5252
}
5353

5454
/// <summary>
55-
/// Generate css tree by parsing the given html and applying the given css style data on it.
55+
/// Parses the html and loads everything the box tree is built from: the style sheets of the
56+
/// document and its <c>@font-face</c> fonts. The only step that does I/O.
5657
/// </summary>
5758
/// <param name="html">the html to parse</param>
5859
/// <param name="htmlContainer">the html container to use for reference resolve</param>
59-
/// <param name="cssData">the css data to use</param>
60-
/// <returns>the root of the generated tree</returns>
61-
public async Task<(CssBox root, CssData cssData)> GenerateCssTree(string html, HtmlContainerInt htmlContainer, CssData cssData)
60+
/// <param name="cssData">the base css data, the document's style sheets are added to a copy</param>
61+
/// <returns>the parsed document, to pass to <see cref="BuildCssTree"/>, and the css data with the document's style sheets</returns>
62+
public async Task<(CssBox root, CssData cssData)> LoadAsync(string html, HtmlContainerInt htmlContainer, CssData cssData)
6263
{
63-
var root = HtmlParser.ParseDocument(html);
64+
var root = ParseDocument(html, htmlContainer);
6465
if (root != null)
6566
{
66-
root.HtmlContainer = htmlContainer;
67-
6867
(cssData, _) = await CascadeParseStyles(root, htmlContainer, cssData, false).ConfigureAwait(false);
6968

7069
await RegisterFontFaces(cssData, htmlContainer).ConfigureAwait(false);
70+
}
71+
return (root, cssData);
72+
}
73+
74+
/// <summary>
75+
/// Parses the html again, for building a new box tree from already loaded css data.
76+
/// </summary>
77+
public CssBox ParseDocument(string html, HtmlContainerInt htmlContainer)
78+
{
79+
var root = HtmlParser.ParseDocument(html);
80+
if (root != null)
81+
root.HtmlContainer = htmlContainer;
82+
return root;
83+
}
7184

72-
// The device @media queries are evaluated against: media type and colour scheme come
73-
// from the platform adapter, the viewport from the container's max size (which is the
74-
// available width/height at this point; zero means "not known yet", and geometry
75-
// conditions then match permissively).
76-
var media = MediaQueryContext.FromAdapter(
77-
htmlContainer.Adapter, htmlContainer.MaxSize.Width, htmlContainer.MaxSize.Height);
85+
/// <summary>
86+
/// Builds the box tree of a parsed document by applying the css data to it. Synchronous, all
87+
/// resources it needs were loaded by <see cref="LoadAsync"/>. Changes the tree, so each build
88+
/// needs a freshly parsed document.
89+
/// </summary>
90+
/// <param name="root">the parsed document</param>
91+
/// <param name="htmlContainer">the html container to use for reference resolve</param>
92+
/// <param name="cssData">the css data from <see cref="LoadAsync"/></param>
93+
public void BuildCssTree(CssBox root, HtmlContainerInt htmlContainer, CssData cssData)
94+
{
95+
if (root == null)
96+
return;
7897

79-
CascadeApplyStyles(root, cssData, media);
98+
// The device @media queries are evaluated against: media type and colour scheme come
99+
// from the platform adapter, the viewport from the container's max size (which is the
100+
// available width/height at this point; zero means "not known yet", and geometry
101+
// conditions then match permissively).
102+
var media = MediaQueryContext.FromAdapter(
103+
htmlContainer.Adapter, htmlContainer.MaxSize.Width, htmlContainer.MaxSize.Height);
80104

81-
SetTextSelectionStyle(htmlContainer, cssData);
105+
CascadeApplyStyles(root, cssData, media);
82106

83-
CssCounterEngine.ResolveCounters(root);
107+
SetTextSelectionStyle(htmlContainer, cssData);
84108

85-
CorrectTextBoxes(root);
109+
CssCounterEngine.ResolveCounters(root);
86110

87-
CorrectImgBoxes(root);
111+
CorrectTextBoxes(root);
88112

89-
CorrectLineBreaksBlocks(root);
113+
CorrectImgBoxes(root);
90114

91-
CorrectInlineBoxesParent(root);
115+
CorrectLineBreaksBlocks(root);
92116

93-
CorrectBlockInsideInline(root);
117+
CorrectInlineBoxesParent(root);
94118

95-
CorrectInlineBoxesParent(root);
119+
CorrectBlockInsideInline(root);
96120

97-
CorrectAnonymousTables(root);
98-
}
99-
return (root, cssData);
121+
CorrectInlineBoxesParent(root);
122+
123+
CorrectAnonymousTables(root);
100124
}
101125

102126

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
using System.Text;
2+
using HtmlRenderer.Test.TestSupport;
3+
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
4+
using TheArtOfDev.HtmlRenderer.Core;
5+
using TheArtOfDev.HtmlRenderer.Core.Network;
6+
7+
namespace HtmlRenderer.Test.Css;
8+
9+
[TestClass]
10+
public sealed class MediaRefreshTests
11+
{
12+
private const string StyleSheetUrl = "https://example.com/style.css";
13+
14+
private static readonly RColor Red = RColor.FromArgb(255, 0, 0);
15+
private static readonly RColor Green = RColor.FromArgb(0, 128, 0);
16+
17+
[TestMethod]
18+
[Spec("css-conditional-3", "#processing")]
19+
public void ResizingAcrossABreakpoint_AppliesTheRulesThatMatchNow()
20+
{
21+
var container = Load("<style>p { color: red } @media (max-width: 400px) { p { color: green } }</style>", new CountingLoader());
22+
23+
Assert.AreEqual(Red, ColorAt(container, 800));
24+
Assert.AreEqual(Green, ColorAt(container, 300));
25+
Assert.AreEqual(Red, ColorAt(container, 800));
26+
}
27+
28+
[TestMethod]
29+
[Spec("css-conditional-3", "#processing")]
30+
public void ResizingAcrossABreakpoint_DoesntLoadTheStyleSheetsAgain()
31+
{
32+
var loader = new CountingLoader { StyleSheet = "p { color: red } @media (max-width: 400px) { p { color: green } }" };
33+
var container = Load($"<link rel=stylesheet href='{StyleSheetUrl}'>", loader);
34+
35+
Assert.AreEqual(Red, ColorAt(container, 800));
36+
Assert.AreEqual(Green, ColorAt(container, 300));
37+
Assert.AreEqual(1, loader.Requests.Count(r => r == StyleSheetUrl));
38+
}
39+
40+
private static HtmlContainerInt Load(string head, CountingLoader loader)
41+
{
42+
var container = new HtmlContainerInt(new MockAdapter { NetworkLoader = loader }) { MaxSize = new RSize(800, 600) };
43+
container.SetHtmlAsync($"<html><head>{head}</head><body><p id=x>a</p></body></html>").GetAwaiter().GetResult();
44+
return container;
45+
}
46+
47+
private static RColor ColorAt(HtmlContainerInt container, double width)
48+
{
49+
container.MaxSize = new RSize(width, 600);
50+
container.PerformLayout(new RecordingGraphics());
51+
52+
var box = LayoutHarness.FindById(container.Root!, "x");
53+
Assert.IsNotNull(box);
54+
return box.ActualColor;
55+
}
56+
57+
private sealed class CountingLoader : RNetworkLoader
58+
{
59+
public string StyleSheet { get; init; } = string.Empty;
60+
61+
public List<string> Requests { get; } = [];
62+
63+
public override RUri? BaseUri => new("https://example.com/index.html");
64+
65+
public override Task<string> GetPrimaryContentsAsync() => Task.FromResult(string.Empty);
66+
67+
public override Task<RNetworkResponse?> GetResourceStreamAsync(RUri uri)
68+
{
69+
Requests.Add(uri.AbsoluteUri);
70+
if (uri.AbsoluteUri != StyleSheetUrl)
71+
return Task.FromResult<RNetworkResponse?>(null);
72+
73+
var headers = new Dictionary<string, string[]> { ["Content-Type"] = ["text/css"] };
74+
return Task.FromResult<RNetworkResponse?>(new RNetworkResponse(new MemoryStream(Encoding.UTF8.GetBytes(StyleSheet)), headers));
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)