diff --git a/Source/HtmlRenderer/Core/HtmlContainerInt.cs b/Source/HtmlRenderer/Core/HtmlContainerInt.cs index a2120ed47..b8ff8c4ea 100644 --- a/Source/HtmlRenderer/Core/HtmlContainerInt.cs +++ b/Source/HtmlRenderer/Core/HtmlContainerInt.cs @@ -125,13 +125,11 @@ public sealed class HtmlContainerInt : IDisposable private CssData _cssData; /// - /// The html and base stylesheet last given to , kept so the cascade can be - /// re-run when a viewport change alters which @media rules apply. + /// The html last given to , kept so the box tree can be built again + /// when a viewport change alters which @media rules apply. /// private string _htmlSource; - private CssData _baseCssData; - /// /// The device the current cascade was computed against. /// @@ -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); + } + } + + /// + /// Builds the box tree from a parsed document and the loaded , and makes it the root. + /// + 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); } } /// /// Re-runs the cascade when a viewport change flips the outcome of an @media 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 are reused, so it's safe in a synchronous layout. /// private void RefreshMediaDependentCascade() { @@ -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); } /// diff --git a/Source/HtmlRenderer/Core/Parse/DomParser.cs b/Source/HtmlRenderer/Core/Parse/DomParser.cs index 41bb81950..6f66027d4 100644 --- a/Source/HtmlRenderer/Core/Parse/DomParser.cs +++ b/Source/HtmlRenderer/Core/Parse/DomParser.cs @@ -52,51 +52,75 @@ public DomParser(CssParser cssParser) } /// - /// 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 @font-face fonts. The only step that does I/O. /// /// the html to parse /// the html container to use for reference resolve - /// the css data to use - /// the root of the generated tree - public async Task<(CssBox root, CssData cssData)> GenerateCssTree(string html, HtmlContainerInt htmlContainer, CssData cssData) + /// the base css data, the document's style sheets are added to a copy + /// the parsed document, to pass to , and the css data with the document's style sheets + 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); + } + + /// + /// Parses the html again, for building a new box tree from already loaded css data. + /// + 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); + /// + /// Builds the box tree of a parsed document by applying the css data to it. Synchronous, all + /// resources it needs were loaded by . Changes the tree, so each build + /// needs a freshly parsed document. + /// + /// the parsed document + /// the html container to use for reference resolve + /// the css data from + 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); } diff --git a/Source/Test/HtmlRenderer.Test/Css/MediaRefreshTests.cs b/Source/Test/HtmlRenderer.Test/Css/MediaRefreshTests.cs new file mode 100644 index 000000000..1b8dfdac9 --- /dev/null +++ b/Source/Test/HtmlRenderer.Test/Css/MediaRefreshTests.cs @@ -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("", 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($"", 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($"{head}

a

").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 Requests { get; } = []; + + public override RUri? BaseUri => new("https://example.com/index.html"); + + public override Task GetPrimaryContentsAsync() => Task.FromResult(string.Empty); + + public override Task GetResourceStreamAsync(RUri uri) + { + Requests.Add(uri.AbsoluteUri); + if (uri.AbsoluteUri != StyleSheetUrl) + return Task.FromResult(null); + + var headers = new Dictionary { ["Content-Type"] = ["text/css"] }; + return Task.FromResult(new RNetworkResponse(new MemoryStream(Encoding.UTF8.GetBytes(StyleSheet)), headers)); + } + } +}