Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 26 additions & 15 deletions Source/HtmlRenderer/Core/HtmlContainerInt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,11 @@ public sealed class HtmlContainerInt : IDisposable
private CssData _cssData;

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

private CssData _baseCssData;

/// <summary>
/// The device the current cascade was computed against.
/// </summary>
Expand Down Expand Up @@ -599,26 +597,37 @@ public async Task SetHtmlAsync(string htmlSource, CssData baseCssData = null)
{
Clear();
_htmlSource = htmlSource;
_baseCssData = baseCssData;

if (!string.IsNullOrEmpty(htmlSource))
{
_loadComplete = false;
_cssData = baseCssData ?? _adapter.DefaultCssData;

DomParser parser = new DomParser(_cssParser);
(_root, _cssData) = await parser.GenerateCssTree(htmlSource, this, _cssData).ConfigureAwait(false);
_cascadeMedia = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
if (_root != null)
{
_selectionHandler = new SelectionHandler(_root);
}
var parser = new DomParser(_cssParser);
CssBox root;
(root, _cssData) = await parser.LoadAsync(htmlSource, this, _cssData).ConfigureAwait(false);
BuildRoot(parser, root);
}
}

/// <summary>
/// Builds the box tree from a parsed document and the loaded <see cref="_cssData"/>, and makes it the root.
/// </summary>
private void BuildRoot(DomParser parser, CssBox root)
{
parser.BuildCssTree(root, this, _cssData);
_root = root;
_cascadeMedia = MediaQueryContext.FromAdapter(_adapter, _maxSize.Width, _maxSize.Height);
if (_root != null)
{
_selectionHandler = new SelectionHandler(_root);
}
}

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

// PerformLayout is synchronous, so this blocks on the async SetHtmlAsync
SetHtmlAsync(_htmlSource, _baseCssData).GetAwaiter().GetResult();
var parser = new DomParser(_cssParser);
var root = parser.ParseDocument(_htmlSource, this);
Clear();
BuildRoot(parser, root);
}

/// <summary>
Expand Down
74 changes: 49 additions & 25 deletions Source/HtmlRenderer/Core/Parse/DomParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,51 +52,75 @@ public DomParser(CssParser cssParser)
}

/// <summary>
/// Generate css tree by parsing the given html and applying the given css style data on it.
/// Parses the html and loads everything the box tree is built from: the style sheets of the
/// document and its <c>@font-face</c> fonts. The only step that does I/O.
/// </summary>
/// <param name="html">the html to parse</param>
/// <param name="htmlContainer">the html container to use for reference resolve</param>
/// <param name="cssData">the css data to use</param>
/// <returns>the root of the generated tree</returns>
public async Task<(CssBox root, CssData cssData)> GenerateCssTree(string html, HtmlContainerInt htmlContainer, CssData cssData)
/// <param name="cssData">the base css data, the document's style sheets are added to a copy</param>
/// <returns>the parsed document, to pass to <see cref="BuildCssTree"/>, and the css data with the document's style sheets</returns>
public async Task<(CssBox root, CssData cssData)> LoadAsync(string html, HtmlContainerInt htmlContainer, CssData cssData)
{
var root = HtmlParser.ParseDocument(html);
var root = ParseDocument(html, htmlContainer);
if (root != null)
{
root.HtmlContainer = htmlContainer;

(cssData, _) = await CascadeParseStyles(root, htmlContainer, cssData, false).ConfigureAwait(false);

await RegisterFontFaces(cssData, htmlContainer).ConfigureAwait(false);
}
return (root, cssData);
}

/// <summary>
/// Parses the html again, for building a new box tree from already loaded css data.
/// </summary>
public CssBox ParseDocument(string html, HtmlContainerInt htmlContainer)
{
var root = HtmlParser.ParseDocument(html);
if (root != null)
root.HtmlContainer = htmlContainer;
return root;
}

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

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

SetTextSelectionStyle(htmlContainer, cssData);
CascadeApplyStyles(root, cssData, media);

CssCounterEngine.ResolveCounters(root);
SetTextSelectionStyle(htmlContainer, cssData);

CorrectTextBoxes(root);
CssCounterEngine.ResolveCounters(root);

CorrectImgBoxes(root);
CorrectTextBoxes(root);

CorrectLineBreaksBlocks(root);
CorrectImgBoxes(root);

CorrectInlineBoxesParent(root);
CorrectLineBreaksBlocks(root);

CorrectBlockInsideInline(root);
CorrectInlineBoxesParent(root);

CorrectInlineBoxesParent(root);
CorrectBlockInsideInline(root);

CorrectAnonymousTables(root);
}
return (root, cssData);
CorrectInlineBoxesParent(root);

CorrectAnonymousTables(root);
}


Expand Down
77 changes: 77 additions & 0 deletions Source/Test/HtmlRenderer.Test/Css/MediaRefreshTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System.Text;
using HtmlRenderer.Test.TestSupport;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core;
using TheArtOfDev.HtmlRenderer.Core.Network;

namespace HtmlRenderer.Test.Css;

[TestClass]
public sealed class MediaRefreshTests
{
private const string StyleSheetUrl = "https://example.com/style.css";

private static readonly RColor Red = RColor.FromArgb(255, 0, 0);
private static readonly RColor Green = RColor.FromArgb(0, 128, 0);

[TestMethod]
[Spec("css-conditional-3", "#processing")]
public void ResizingAcrossABreakpoint_AppliesTheRulesThatMatchNow()
{
var container = Load("<style>p { color: red } @media (max-width: 400px) { p { color: green } }</style>", new CountingLoader());

Assert.AreEqual(Red, ColorAt(container, 800));
Assert.AreEqual(Green, ColorAt(container, 300));
Assert.AreEqual(Red, ColorAt(container, 800));
}

[TestMethod]
[Spec("css-conditional-3", "#processing")]
public void ResizingAcrossABreakpoint_DoesntLoadTheStyleSheetsAgain()
{
var loader = new CountingLoader { StyleSheet = "p { color: red } @media (max-width: 400px) { p { color: green } }" };
var container = Load($"<link rel=stylesheet href='{StyleSheetUrl}'>", loader);

Assert.AreEqual(Red, ColorAt(container, 800));
Assert.AreEqual(Green, ColorAt(container, 300));
Assert.AreEqual(1, loader.Requests.Count(r => r == StyleSheetUrl));
}

private static HtmlContainerInt Load(string head, CountingLoader loader)
{
var container = new HtmlContainerInt(new MockAdapter { NetworkLoader = loader }) { MaxSize = new RSize(800, 600) };
container.SetHtmlAsync($"<html><head>{head}</head><body><p id=x>a</p></body></html>").GetAwaiter().GetResult();
return container;
}

private static RColor ColorAt(HtmlContainerInt container, double width)
{
container.MaxSize = new RSize(width, 600);
container.PerformLayout(new RecordingGraphics());

var box = LayoutHarness.FindById(container.Root!, "x");
Assert.IsNotNull(box);
return box.ActualColor;
}

private sealed class CountingLoader : RNetworkLoader
{
public string StyleSheet { get; init; } = string.Empty;

public List<string> Requests { get; } = [];

public override RUri? BaseUri => new("https://example.com/index.html");

public override Task<string> GetPrimaryContentsAsync() => Task.FromResult(string.Empty);

public override Task<RNetworkResponse?> GetResourceStreamAsync(RUri uri)
{
Requests.Add(uri.AbsoluteUri);
if (uri.AbsoluteUri != StyleSheetUrl)
return Task.FromResult<RNetworkResponse?>(null);

var headers = new Dictionary<string, string[]> { ["Content-Type"] = ["text/css"] };
return Task.FromResult<RNetworkResponse?>(new RNetworkResponse(new MemoryStream(Encoding.UTF8.GetBytes(StyleSheet)), headers));
}
}
}
Loading