From bebc624190483595d81784b2b808a0855653a467 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 09:16:42 +0100 Subject: [PATCH 01/19] Fixes due to Acid2 test --- CHANGELOG.md | 8 +++ src/AngleSharp.Css.Docs/package.json | 2 +- src/AngleSharp.Css.Tests/Styling/CssSheet.cs | 34 +++++++++++ src/AngleSharp.Css/Parser/CssBuilder.cs | 10 ++++ src/AngleSharp.Css/Parser/CssTokenizer.cs | 60 +++++++++++++++++++- src/Directory.Build.props | 2 +- 6 files changed, 113 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fe46eb..b3c671e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +# 1.5.1 + +Released on tbd. + +- Fixed a comment in a declaration's value with a quote in it (e.g. `/* shouldn't */`) starting a string, which swallowed the rest of the style sheet (Acid2) +- Fixed an escaped `}` or `;` in a declaration's value (e.g. `error: \}`) ending the rule +- Fixed a `;` after a rule (e.g. `a { color: red; };`) being skipped instead of making the selector of the next rule invalid, which then applied + # 1.5.0 Released on Wednesday, November 18 2026. diff --git a/src/AngleSharp.Css.Docs/package.json b/src/AngleSharp.Css.Docs/package.json index fb31480e..0f08dd5d 100644 --- a/src/AngleSharp.Css.Docs/package.json +++ b/src/AngleSharp.Css.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/css", - "version": "1.5.0", + "version": "1.5.1", "preview": true, "description": "The doclet for the AngleSharp.Css documentation.", "keywords": [ diff --git a/src/AngleSharp.Css.Tests/Styling/CssSheet.cs b/src/AngleSharp.Css.Tests/Styling/CssSheet.cs index eb3a6f6f..7295cecf 100644 --- a/src/AngleSharp.Css.Tests/Styling/CssSheet.cs +++ b/src/AngleSharp.Css.Tests/Styling/CssSheet.cs @@ -1349,5 +1349,39 @@ public void CssColorFunctionsMixAllShouldWork() Assert.IsNotNull(hwbAlpha); Assert.IsNotNull(hwbAngleAlpha); } + + [Test] + public void CssSheetCommentWithQuoteInValueStartsNoString() + { + // Acid2: an apostrophe in a comment used to swallow the rest of the style sheet + var sheet = ParseStyleSheet(@".chin { background: yellow /* shouldn't be visible */ no-repeat; } +.next { color: red; }"); + Assert.AreEqual(2, sheet.Rules.Length); + Assert.AreEqual("rgba(255, 255, 0, 1)", ((ICssStyleRule)sheet.Rules[0]).Style.GetPropertyValue("background-color")); + Assert.AreEqual(".next", ((ICssStyleRule)sheet.Rules[1]).SelectorText); + } + + [Test] + public void CssSheetEscapedCurlyBracketInValueDoesNotEndTheRule() + { + var sheet = ParseStyleSheet(@".parser { width: 2em; error: \}; background: yellow; } +.next { color: red; }"); + Assert.AreEqual(2, sheet.Rules.Length); + var parser = (ICssStyleRule)sheet.Rules[0]; + Assert.AreEqual("2em", parser.Style.GetPropertyValue("width")); + Assert.AreEqual("rgba(255, 255, 0, 1)", parser.Style.GetPropertyValue("background-color")); + } + + [Test] + public void CssSheetSemicolonAfterRuleInvalidatesTheNextSelector() + { + // a ';' is part of the prelude of the next rule, which then matches nothing + var sheet = ParseStyleSheet(@".parser { margin: 2em; }; +.parser { height: 3em; } +.after { color: red; }"); + Assert.AreEqual(3, sheet.Rules.Length); + Assert.IsNull(((CssStyleRule)sheet.Rules[1]).Selector); + Assert.AreEqual(".after", ((ICssStyleRule)sheet.Rules[2]).SelectorText); + } } } diff --git a/src/AngleSharp.Css/Parser/CssBuilder.cs b/src/AngleSharp.Css/Parser/CssBuilder.cs index 25ca568f..7c685c42 100644 --- a/src/AngleSharp.Css/Parser/CssBuilder.cs +++ b/src/AngleSharp.Css/Parser/CssBuilder.cs @@ -536,6 +536,16 @@ public CssStyleRule CreateStyle(CssStyleRule rule, CssToken current) CollectTrivia(rule.Owner, ref current); var selectorText = GetArgument(ref current); + // a ';' does not end the prelude of a rule outside of declarations (CSS Syntax 3, + // consume a qualified rule), it is part of its (then invalid) selector, e.g. of the + // rule after "a { color: red; };", which must not apply + while (current.Type == CssTokenType.Semicolon) + { + var next = NextToken(); + selectorText = String.Concat(selectorText, ";", GetArgument(ref next)); + current = next; + } + rule.SelectorText = selectorText; if (rule.Selector is null && _options.IsToleratingInvalidSelectors) diff --git a/src/AngleSharp.Css/Parser/CssTokenizer.cs b/src/AngleSharp.Css/Parser/CssTokenizer.cs index 712f6a7f..32adf401 100644 --- a/src/AngleSharp.Css/Parser/CssTokenizer.cs +++ b/src/AngleSharp.Css/Parser/CssTokenizer.cs @@ -81,7 +81,32 @@ public String ContentFrom(Int32 position) continue; } - if ((current == Symbols.DoubleQuote || current == Symbols.SingleQuote) && previous != Symbols.ReverseSolidus) + // an escaped character, e.g. "\}", is part of the value, even ';', '{' or '}' + if (current == Symbols.ReverseSolidus) + { + var escaped = GetNext(); + + if (escaped != Symbols.EndOfFile && !escaped.IsLineBreak()) + { + sb.Append(current).Append(escaped); + trailingWhitespace = 0; + previous = escaped; + current = GetNext(); + continue; + } + + Back(); + } + + // a comment is kept as it is, but quotes in it start no string + if (current == Symbols.Solidus && TryAppendComment(sb, ref current)) + { + trailingWhitespace = 0; + previous = Symbols.Solidus; + continue; + } + + if (current == Symbols.DoubleQuote || current == Symbols.SingleQuote) { trailingWhitespace = 0; var quote = current; @@ -144,6 +169,39 @@ public String ContentFrom(Int32 position) return sb.ToPool(); } + /// + /// Appends a comment starting at the current position, if there is one, and moves on to + /// the character after it. + /// + private Boolean TryAppendComment(StringBuilder sb, ref Char current) + { + if (GetNext() != Symbols.Asterisk) + { + Back(); + return false; + } + + sb.Append(Symbols.Solidus).Append(Symbols.Asterisk); + current = GetNext(); + + while (current != Symbols.EndOfFile) + { + sb.Append(current); + var next = GetNext(); + + if (current == Symbols.Asterisk && next == Symbols.Solidus) + { + sb.Append(next); + current = GetNext(); + return true; + } + + current = next; + } + + return true; + } + /// /// Checks if the given character would continue an identifier, i.e. if a /// following "url(" belongs to a longer function name such as "myurl(". diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 46acf4d8..67a24233 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ Extends the CSSOM from the core AngleSharp library. AngleSharp.Css - 1.5.0 + 1.5.1 enable latest true From 34bfade8805254b746dc0af7b463e0934741085a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 12:28:59 +0100 Subject: [PATCH 02/19] Fixes for improving Acid3 --- CHANGELOG.md | 3 + .../Extensions/Acid3Tests.cs | 68 +++++++++++++++++++ .../Extensions/MediaListExtensions.cs | 10 +++ .../ColorFeatureValidator.cs | 18 +++-- .../MonochromeFeatureValidator.cs | 18 +++-- src/AngleSharp.Css/Parser/CssBuilder.cs | 25 +++++-- 6 files changed, 123 insertions(+), 19 deletions(-) create mode 100644 src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b3c671e1..e7476d3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ Released on tbd. - Fixed a comment in a declaration's value with a quote in it (e.g. `/* shouldn't */`) starting a string, which swallowed the rest of the style sheet (Acid2) - Fixed an escaped `}` or `;` in a declaration's value (e.g. `error: \}`) ending the rule - Fixed a `;` after a rule (e.g. `a { color: red; };`) being skipped instead of making the selector of the next rule invalid, which then applied +- Fixed `! important` with whitespace after the `!` not making the declaration important +- Fixed the `color` media feature, e.g. `(color)` and `(min-color: 0)` not matching, and `monochrome` without a value +- Fixed `not` making a media query with an unknown feature (e.g. `not all and (bogus)`) match # 1.5.0 diff --git a/src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs b/src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs new file mode 100644 index 00000000..30dbca5b --- /dev/null +++ b/src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs @@ -0,0 +1,68 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Extensions +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Parser; + using AngleSharp.Dom; + using AngleSharp.Html.Parser; + using NUnit.Framework; + + /// + /// Behavior the Acid3 test (acid3.acidtests.org) relies on. + /// + [TestFixture] + public class Acid3Tests + { + [TestCase("color: red ! important", "rgba(255, 0, 0, 1)")] + [TestCase("color: red !important", "rgba(255, 0, 0, 1)")] + [TestCase("color: red!IMPORTANT ", "rgba(255, 0, 0, 1)")] + [TestCase("border: 1px solid ! important", "1px solid")] + public void ImportantMayHaveWhitespaceAfterTheBang(System.String declaration, System.String expected) + { + var parser = new CssParser(); + var sheet = parser.ParseStyleSheet($"p {{ {declaration} }}"); + var style = ((ICssStyleRule)sheet.Rules[0]).Style; + var name = declaration.Substring(0, declaration.IndexOf(':')); + + Assert.AreEqual("important", style.GetPropertyPriority(name)); + Assert.AreEqual(expected, style.GetPropertyValue(name)); + } + + [Test] + public void ImportantNeedsTheBang() + { + var parser = new CssParser(); + var sheet = parser.ParseStyleSheet("p { color: red important }"); + var style = ((ICssStyleRule)sheet.Rules[0]).Style; + + Assert.AreEqual(System.String.Empty, style.GetPropertyPriority("color")); + } + + [TestCase("all and (min-color: 0)", true)] + [TestCase("(color)", true)] + [TestCase("(min-color: 1)", true)] + [TestCase("(max-color: 0)", false)] + [TestCase("(monochrome)", false)] + [TestCase("(max-monochrome: 0)", true)] + [TestCase("(min-monochrome: 1)", false)] + [TestCase("(max-color: 0) and (max-monochrome: 0)", false)] + [TestCase("(min-color: 1), (min-monochrome: 1)", true)] + [TestCase("not all and (min-color: 1), not all and (min-monochrome: 1)", true)] + [TestCase("not all and (bogus)", false)] + [TestCase("(bogus), all", true)] + public void MediaQueriesOfAColorScreen(System.String query, System.Boolean expected) + { + var window = CreateWindow(new DefaultRenderDevice { ColorBits = 32, MonochromeBits = 0, ViewPortWidth = 1000, ViewPortHeight = 800 }); + Assert.AreEqual(expected, window.MatchMedia(query).IsMatched, query); + } + + private static IWindow CreateWindow(IRenderDevice device) + { + var config = Configuration.Default.WithCss().WithRenderDevice(device); + var context = BrowsingContext.New(config); + var parser = context.GetService(); + var document = parser.ParseDocument("Example"); + return document.DefaultView; + } + } +} diff --git a/src/AngleSharp.Css/Extensions/MediaListExtensions.cs b/src/AngleSharp.Css/Extensions/MediaListExtensions.cs index 4fb83868..c9d879aa 100644 --- a/src/AngleSharp.Css/Extensions/MediaListExtensions.cs +++ b/src/AngleSharp.Css/Extensions/MediaListExtensions.cs @@ -74,11 +74,21 @@ private static Boolean Validate(this IFeatureValidator validator, MediaFeature f public static Boolean Validate(this ICssMedium medium, IRenderDevice device) { + // an unknown feature makes the query unknown, which `not` doesn't turn into a match + // (e.g. `not all and (bogus)`, Media Queries 4, 3.2) + if (medium.IsInverse && medium.Features.Any(IsUnknown)) + { + return false; + } + // `not` negates the whole query, i.e. the media type and all features together var matches = medium.MatchesType(device) && medium.MatchesFeatures(device); return matches != medium.IsInverse; } + private static Boolean IsUnknown(IMediaFeature feature) => + feature is not MediaCondition && (!AssociatedValidators.TryGetValue(feature, out var validator) || validator is null); + private static Boolean MatchesType(this ICssMedium medium, IRenderDevice device) { var type = medium.Type; diff --git a/src/AngleSharp.Css/FeatureValidators/ColorFeatureValidator.cs b/src/AngleSharp.Css/FeatureValidators/ColorFeatureValidator.cs index 427745c7..a0951ae3 100644 --- a/src/AngleSharp.Css/FeatureValidators/ColorFeatureValidator.cs +++ b/src/AngleSharp.Css/FeatureValidators/ColorFeatureValidator.cs @@ -2,7 +2,6 @@ namespace AngleSharp.Css.FeatureValidators { using AngleSharp.Css.Converters; using AngleSharp.Css.Dom; - using AngleSharp.Css.Values; using System; using static ValueConverters; @@ -10,14 +9,19 @@ sealed class ColorFeatureValidator : IFeatureValidator { public Boolean Validate(IMediaFeature feature, IRenderDevice renderDevice) { - var defaultValue = new CssLengthValue(1.0, CssLengthValue.Unit.None); - var converter = feature.IsMinimum || feature.IsMaximum ? PositiveIntegerConverter : PositiveIntegerConverter.Option(defaultValue); - var color = converter.Convert(feature); + // the bits per color component (or of a monochrome pixel), 0 if the device has none + var available = renderDevice.ColorBits >= 24 ? 8 : renderDevice.ColorBits / 3; - if (color != null) + if (!feature.HasValue) { - var desired = color.AsInt32(); - var available = Math.Pow(renderDevice.ColorBits, 2); + return !feature.IsMinimum && !feature.IsMaximum && available > 0; + } + + var value = NaturalIntegerConverter.Convert(feature); + + if (value != null) + { + var desired = value.AsInt32(); if (feature.IsMaximum) { diff --git a/src/AngleSharp.Css/FeatureValidators/MonochromeFeatureValidator.cs b/src/AngleSharp.Css/FeatureValidators/MonochromeFeatureValidator.cs index 60a5b8ee..c0ea30b9 100644 --- a/src/AngleSharp.Css/FeatureValidators/MonochromeFeatureValidator.cs +++ b/src/AngleSharp.Css/FeatureValidators/MonochromeFeatureValidator.cs @@ -2,7 +2,6 @@ namespace AngleSharp.Css.FeatureValidators { using AngleSharp.Css.Converters; using AngleSharp.Css.Dom; - using AngleSharp.Css.Values; using System; using static ValueConverters; @@ -10,14 +9,19 @@ sealed class MonochromeFeatureValidator : IFeatureValidator { public Boolean Validate(IMediaFeature feature, IRenderDevice renderDevice) { - var defaultValue = new CssLengthValue(1.0, CssLengthValue.Unit.None); - var converter = feature.IsMinimum || feature.IsMaximum ? NaturalIntegerConverter : NaturalIntegerConverter.Option(defaultValue); - var index = converter.Convert(feature); + // the bits per color component (or of a monochrome pixel), 0 if the device has none + var available = renderDevice.MonochromeBits; - if (index != null) + if (!feature.HasValue) { - var desired = index.AsInt32(); - var available = renderDevice.MonochromeBits; + return !feature.IsMinimum && !feature.IsMaximum && available > 0; + } + + var value = NaturalIntegerConverter.Convert(feature); + + if (value != null) + { + var desired = value.AsInt32(); if (feature.IsMaximum) { diff --git a/src/AngleSharp.Css/Parser/CssBuilder.cs b/src/AngleSharp.Css/Parser/CssBuilder.cs index 7c685c42..569ed0df 100644 --- a/src/AngleSharp.Css/Parser/CssBuilder.cs +++ b/src/AngleSharp.Css/Parser/CssBuilder.cs @@ -1148,11 +1148,26 @@ private void RaiseErrorOccurred(CssParseError code, TextPosition position) => private String CreateValue(ref CssToken token, out Boolean important) { - var keyword = CssKeywords.BangImportant; + const String keyword = "important"; var value = _tokenizer.ContentFrom(token.Position.Position); - var keywordStart = value.Length - keyword.Length; - important = keywordStart >= 0 && - value[keywordStart] == Symbols.ExclamationMark && + var end = value.Length; + + while (end > 0 && value[end - 1].IsSpaceCharacter()) + { + end--; + } + + var keywordStart = end - keyword.Length; + var bang = keywordStart - 1; + + // whitespace may separate the "!" from "important" (e.g., "! important") + while (bang >= 0 && value[bang].IsSpaceCharacter()) + { + bang--; + } + + important = keywordStart > 0 && bang >= 0 && + value[bang] == Symbols.ExclamationMark && String.Compare(value, keywordStart, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase) == 0; token = NextToken(); @@ -1161,7 +1176,7 @@ private String CreateValue(ref CssToken token, out Boolean important) return value; } - var end = keywordStart; + end = bang; while (end > 0 && value[end - 1].IsSpaceCharacter()) { From fccd2383ae5431eb8be252881824c9cfbe294077 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sat, 21 Nov 2026 18:16:49 +0100 Subject: [PATCH 03/19] Improved grid template columns declaration --- CHANGELOG.md | 1 + .../Declarations/CssGridProperty.cs | 27 +++++++++++++++++++ src/AngleSharp.Css/Parser/Micro/GridParser.cs | 6 ++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e7476d3e..c456fcaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Released on tbd. - Fixed `! important` with whitespace after the `!` not making the declaration important - Fixed the `color` media feature, e.g. `(color)` and `(min-color: 0)` not matching, and `monochrome` without a value - Fixed `not` making a media query with an unknown feature (e.g. `not all and (bogus)`) match +- Fixed `minmax()` with a math function (e.g. `repeat(auto-fill, minmax(min(100%, 17rem), 1fr))`) making `grid-template-columns` invalid in an auto repeat # 1.5.0 diff --git a/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs b/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs index 65bf7f2d..2c52b9d2 100644 --- a/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs +++ b/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs @@ -155,6 +155,33 @@ public void CssGridTemplateColumnsLengthAutoRepeatLengthLegal() Assert.AreEqual("200px repeat(auto-fill, 100px) 300px", property.Value); } + [Test] + public void CssGridTemplateColumnsAutoRepeatMinmaxOfMathFunctionLegal() + { + var snippet = "grid-template-columns: repeat(auto-fill, minmax(min(100%, 17rem), 1fr))"; + var property = ParseDeclaration(snippet); + Assert.AreEqual("grid-template-columns", property.Name); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("repeat(auto-fill, minmax(min(100%, 17rem), 1fr))", property.Value); + } + + [Test] + public void CssGridTemplateColumnsAutoRepeatMinmaxOfCalcLegal() + { + var snippet = "grid-template-columns: repeat(auto-fit, minmax(calc(10rem + 2px), 1fr))"; + var property = ParseDeclaration(snippet); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("repeat(auto-fit, minmax(calc(10rem + 2px), 1fr))", property.Value); + } + + [Test] + public void CssGridTemplateColumnsAutoRepeatMinmaxWithoutFixedBreadthIllegal() + { + var snippet = "grid-template-columns: repeat(auto-fill, minmax(auto, 1fr))"; + var property = ParseDeclaration(snippet); + Assert.IsFalse(property.HasValue); + } + [Test] public void CssGridTemplateColumnsMultilineLinenamesAutoRepeatLegal() { diff --git a/src/AngleSharp.Css/Parser/Micro/GridParser.cs b/src/AngleSharp.Css/Parser/Micro/GridParser.cs index 1b9831cf..f98e872a 100644 --- a/src/AngleSharp.Css/Parser/Micro/GridParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/GridParser.cs @@ -197,7 +197,7 @@ public static ICssValue ParseFixedSize(this StringSource source) var max = source.ParseTrackBreadth(); c = source.SkipSpacesAndComments(); - if (max != null && c == Symbols.RoundBracketClose && (min is CssLengthValue? || max is CssLengthValue?)) + if (max != null && c == Symbols.RoundBracketClose && (IsFixedBreadth(min) || IsFixedBreadth(max))) { source.Next(); return new CssMinMaxValue(min, max); @@ -212,6 +212,10 @@ public static ICssValue ParseFixedSize(this StringSource source) return length; } + // A is a , which includes math functions such as + // calc() or min(); the other track breadths are keywords and flexible lengths. + private static Boolean IsFixedBreadth(ICssValue value) => value is not (CssIdentifierValue or CssFractionValue); + /// /// Parses a grid track size value. /// From 4e332dbb18309b478822699a09b6256cbf0cfef8 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 15:44:06 +0100 Subject: [PATCH 04/19] Improved default stylesheet --- src/AngleSharp.Css.Tests/Styling/Configuration.cs | 4 +++- src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/AngleSharp.Css.Tests/Styling/Configuration.cs b/src/AngleSharp.Css.Tests/Styling/Configuration.cs index 3e216a72..8b816227 100644 --- a/src/AngleSharp.Css.Tests/Styling/Configuration.cs +++ b/src/AngleSharp.Css.Tests/Styling/Configuration.cs @@ -54,7 +54,9 @@ public void ObtainDefaultSheet() // shown, centered in the viewport, and the `::backdrop` of a shown popover). // 86, not 85: headings and `th` are `bold` (as in the HTML standard), `b` and // `strong` stay `bolder`, which takes a rule of its own. - Assert.AreEqual(86, sheet.Rules.Length); + // 89, not 86: the UA stylesheet now also carries the dialog rules (hidden unless + // open, centered, and fixed in the viewport while it is a modal). + Assert.AreEqual(89, sheet.Rules.Length); } } } diff --git a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs index cf7cb41d..7a440eb8 100644 --- a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs +++ b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs @@ -85,6 +85,9 @@ private static ICssStyleSheet Parse(String source) [hidden] { display: none } [popover]:not(:popover-open):not(dialog[open]) { display: none } dialog:popover-open { display: block } +dialog:not([open]) { display: none } +dialog { display: block; position: absolute; left: 0; right: 0; width: fit-content; height: fit-content; margin: auto; border: solid; padding: 1em; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255) } +dialog:modal { position: fixed; overflow: auto; top: 0; bottom: 0; max-width: calc(100% - 6px - 2em); max-height: calc(100% - 6px - 2em) } [popover] { position: fixed; inset: 0; width: fit-content; height: fit-content; margin: auto; border: solid; padding: 0.25em; overflow: auto; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255) } :popover-open::backdrop { position: fixed; inset: 0; pointer-events: none !important; background-color: transparent } table { display: table } From 1dd74de3898ff35aa5c526843975fe6151db2f2b Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 15:52:11 +0100 Subject: [PATCH 05/19] Improved pseudo selectors and scope handling --- .../Dom/Internal/ModalPseudoClassSelector.cs | 22 +++++++++++ .../Extensions/StyleSheetExtensions.cs | 7 ++++ .../CssPseudoClassSelectorFactory.cs | 12 ++++++ .../CssPseudoElementSelectorFactory.cs | 37 +++++++++++++++++++ .../Factories/DefaultPseudoElementFactory.cs | 3 ++ 5 files changed, 81 insertions(+) create mode 100644 src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs diff --git a/src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs b/src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs new file mode 100644 index 00000000..3e184be0 --- /dev/null +++ b/src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs @@ -0,0 +1,22 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using System; + + /// + /// Matches the `:modal` pseudo-class (Selectors 4 §13.4), i.e., a dialog shown as a modal. + /// + sealed class ModalPseudoClassSelector : ISelector + { + public Priority Specificity => Priority.OneClass; + + public String Text => PseudoClassNames.Separator + CssPseudoClassSelectorFactory.Modal; + + public void Accept(ISelectorVisitor visitor) => visitor.PseudoClass(CssPseudoClassSelectorFactory.Modal); + + public Boolean Match(IElement element, IElement? scope) => + element is IHtmlDialogElement dialog && dialog.Open && dialog.GetIsModal(); + } +} diff --git a/src/AngleSharp.Css/Extensions/StyleSheetExtensions.cs b/src/AngleSharp.Css/Extensions/StyleSheetExtensions.cs index 63ad9ea1..df915d61 100644 --- a/src/AngleSharp.Css/Extensions/StyleSheetExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleSheetExtensions.cs @@ -63,6 +63,13 @@ public static IEnumerable GetMatchingStyles(this ICssRuleList rul } } } + else if (rule is ICssScopeRule scope) + { + foreach (var subrule in scope.Rules.GetMatchingStyles(device)) + { + yield return subrule; + } + } else if (rule is ICssLayerRule { IsStatement: false } layer) { foreach (var subrule in layer.Rules.GetMatchingStyles(device)) diff --git a/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs b/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs index 9085328d..12500a57 100644 --- a/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs +++ b/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs @@ -15,8 +15,15 @@ sealed class CssPseudoClassSelectorFactory : IPseudoClassSelectorFactory /// public static readonly String PopoverOpen = "popover-open"; + /// + /// The name of the `:modal` pseudo-class (Selectors 4 §13.4). + /// + public static readonly String Modal = "modal"; + private static readonly ISelector PopoverOpenSelector = new PopoverOpenPseudoClassSelector(); + private static readonly ISelector ModalSelector = new ModalPseudoClassSelector(); + private readonly IPseudoClassSelectorFactory _inner; public CssPseudoClassSelectorFactory(IPseudoClassSelectorFactory inner) @@ -33,6 +40,11 @@ public CssPseudoClassSelectorFactory(IPseudoClassSelectorFactory inner) return PopoverOpenSelector; } + if (selector is null && name.Equals(Modal, StringComparison.OrdinalIgnoreCase)) + { + return ModalSelector; + } + return selector; } } diff --git a/src/AngleSharp.Css/Factories/CssPseudoElementSelectorFactory.cs b/src/AngleSharp.Css/Factories/CssPseudoElementSelectorFactory.cs index d005c9c7..b6627719 100644 --- a/src/AngleSharp.Css/Factories/CssPseudoElementSelectorFactory.cs +++ b/src/AngleSharp.Css/Factories/CssPseudoElementSelectorFactory.cs @@ -20,8 +20,29 @@ sealed class CssPseudoElementSelectorFactory : IPseudoElementSelectorFactory /// public static readonly String Backdrop = "backdrop"; + /// + /// The name of the `::marker` pseudo-element (CSS Pseudo-Elements 4 §3.1). + /// + public static readonly String Marker = "marker"; + + /// + /// The name of the `::first-line` pseudo-element (CSS Pseudo-Elements 4 §2.1). + /// + public static readonly String FirstLine = "first-line"; + + /// + /// The name of the `::first-letter` pseudo-element (CSS Pseudo-Elements 4 §2.2). + /// + public static readonly String FirstLetter = "first-letter"; + private static readonly ISelector PlaceholderSelector = new CssPseudoElementSelector(Placeholder); + private static readonly ISelector MarkerSelector = new CssPseudoElementSelector(Marker); + + private static readonly ISelector FirstLineSelector = new CssPseudoElementSelector(FirstLine); + + private static readonly ISelector FirstLetterSelector = new CssPseudoElementSelector(FirstLetter); + private static readonly ISelector BackdropSelector = new CssPseudoElementSelector(Backdrop); private readonly IPseudoElementSelectorFactory _inner; @@ -33,6 +54,17 @@ public CssPseudoElementSelectorFactory(IPseudoElementSelectorFactory inner) public ISelector Create(String name) { + // AngleSharp knows these, but leaves them unmatched; a renderer styles them + if (name.Equals(FirstLine, StringComparison.OrdinalIgnoreCase)) + { + return FirstLineSelector; + } + + if (name.Equals(FirstLetter, StringComparison.OrdinalIgnoreCase)) + { + return FirstLetterSelector; + } + var selector = _inner.Create(name); if (selector is null) @@ -46,6 +78,11 @@ public ISelector Create(String name) { return BackdropSelector; } + + if (name.Equals(Marker, StringComparison.OrdinalIgnoreCase)) + { + return MarkerSelector; + } } return selector; diff --git a/src/AngleSharp.Css/Factories/DefaultPseudoElementFactory.cs b/src/AngleSharp.Css/Factories/DefaultPseudoElementFactory.cs index 61e76179..510c4584 100644 --- a/src/AngleSharp.Css/Factories/DefaultPseudoElementFactory.cs +++ b/src/AngleSharp.Css/Factories/DefaultPseudoElementFactory.cs @@ -27,6 +27,9 @@ public class DefaultPseudoElementFactory : IPseudoElementFactory { CssPseudoElementSelectorFactory.Placeholder, CreatePlaceholder }, { CssPseudoElementSelectorFactory.Backdrop, CreateBackdrop }, { PseudoElementNames.Selection, element => new PseudoElement(element, PseudoElementNames.Selection) }, + { CssPseudoElementSelectorFactory.Marker, element => new PseudoElement(element, CssPseudoElementSelectorFactory.Marker) }, + { CssPseudoElementSelectorFactory.FirstLine, element => new PseudoElement(element, CssPseudoElementSelectorFactory.FirstLine) }, + { CssPseudoElementSelectorFactory.FirstLetter, element => new PseudoElement(element, CssPseudoElementSelectorFactory.FirstLetter) }, }; private static IPseudoElement CreatePlaceholder(IElement host) From 95bc7f6617e254f9f1b337277172ab37941f504e Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 15:52:39 +0100 Subject: [PATCH 06/19] Fixes for gradient parsing --- .../Parser/Micro/GradientParser.cs | 140 ++++++++++++++++-- .../Values/Composites/CssGradientStopValue.cs | 32 +++- .../Values/Functions/CssConicGradientValue.cs | 46 +++++- .../Functions/CssLinearGradientValue.cs | 30 +++- .../Functions/CssRadialGradientValue.cs | 39 ++++- 5 files changed, 258 insertions(+), 29 deletions(-) diff --git a/src/AngleSharp.Css/Parser/Micro/GradientParser.cs b/src/AngleSharp.Css/Parser/Micro/GradientParser.cs index f29439aa..68027e2b 100644 --- a/src/AngleSharp.Css/Parser/Micro/GradientParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/GradientParser.cs @@ -56,10 +56,27 @@ private static ICssGradientFunctionValue ParseRepeatingLinearGradient(StringSour /// private static ICssGradientFunctionValue ParseLinearGradient(StringSource source, Boolean repeating) { + var interpolation = ParseInterpolation(source); + + if (interpolation != null) + { + source.SkipSpacesAndComments(); + } + var start = source.Index; var angle = ParseLinearAngle(source); - if (angle != null) + if (angle == null) + { + source.BackTo(start); + } + else if (interpolation == null) + { + source.SkipSpacesAndComments(); + interpolation = ParseInterpolation(source); + } + + if (angle != null || interpolation != null) { var current = source.SkipSpacesAndComments(); @@ -70,17 +87,13 @@ private static ICssGradientFunctionValue ParseLinearGradient(StringSource source source.SkipCurrentAndSpaces(); } - else - { - source.BackTo(start); - } var stops = ParseGradientStops(source); if (stops != null && source.Current == Symbols.RoundBracketClose) { source.SkipCurrentAndSpaces(); - return new CssLinearGradientValue(angle, stops, repeating); + return new CssLinearGradientValue(angle, stops, repeating, interpolation); } return null; @@ -102,10 +115,27 @@ private static ICssGradientFunctionValue ParseRepeatingRadialGradient(StringSour /// private static ICssGradientFunctionValue ParseRadialGradient(StringSource source, Boolean repeating) { + var interpolation = ParseInterpolation(source); + + if (interpolation != null) + { + source.SkipSpacesAndComments(); + } + var start = source.Index; var options = ParseRadialOptions(source); - if (options.HasValue) + if (!options.HasValue) + { + source.BackTo(start); + } + else if (interpolation == null) + { + source.SkipSpacesAndComments(); + interpolation = ParseInterpolation(source); + } + + if (options.HasValue || interpolation != null) { var current = source.SkipSpacesAndComments(); @@ -116,10 +146,6 @@ private static ICssGradientFunctionValue ParseRadialGradient(StringSource source source.SkipCurrentAndSpaces(); } - else - { - source.BackTo(start); - } var stops = ParseGradientStops(source); @@ -131,7 +157,7 @@ private static ICssGradientFunctionValue ParseRadialGradient(StringSource source var height = options?.Height; var sizeMode = options?.Size ?? CssRadialGradientValue.SizeMode.None; source.SkipCurrentAndSpaces(); - return new CssRadialGradientValue(circle, center, width, height, sizeMode, stops, repeating); + return new CssRadialGradientValue(circle, center, width, height, sizeMode, stops, repeating, interpolation); } return null; @@ -156,6 +182,8 @@ private static ICssGradientFunctionValue ParseConicGradient(StringSource source, ICssValue angle = null; ICssValue center = null; + source.SkipSpacesAndComments(); + var interpolation = ParseInterpolation(source); source.SkipSpacesAndComments(); if (source.IsIdentifier(CssKeywords.From)) @@ -182,7 +210,13 @@ private static ICssGradientFunctionValue ParseConicGradient(StringSource source, } } - if (angle != null || center != null) + if (interpolation == null && (angle != null || center != null)) + { + source.SkipSpacesAndComments(); + interpolation = ParseInterpolation(source); + } + + if (angle != null || center != null || interpolation != null) { var current = source.SkipSpacesAndComments(); @@ -199,7 +233,7 @@ private static ICssGradientFunctionValue ParseConicGradient(StringSource source, if (stops != null && source.Current == Symbols.RoundBracketClose) { source.SkipCurrentAndSpaces(); - return new CssConicGradientValue(angle, center, stops, repeating); + return new CssConicGradientValue(angle, center, stops, repeating, interpolation); } return null; @@ -226,6 +260,12 @@ private static CssGradientStopValue[] ParseGradientStops(StringSource source) current = source.SkipSpacesAndComments(); } + // a color hint is only allowed between two color stops + if (stops.Count == 0 || stops[stops.Count - 1].IsHint) + { + return null; + } + return stops.ToArray(); } @@ -262,9 +302,71 @@ private static Boolean ParseGradientStop(StringSource source, List 0 && !stops[stops.Count - 1].IsHint) + { + stops.Add(CssGradientStopValue.CreateHint(position)); + return true; + } + return false; } + /// + /// Parses the color interpolation method of a gradient (CSS Images 4 §3.1), e.g. + /// "in oklch" or "in hsl longer hue", returning its normalized text. + /// + private static String ParseInterpolation(StringSource source) + { + var start = source.Index; + + if (source.IsIdentifier(CssKeywords.In)) + { + source.SkipSpacesAndComments(); + var space = source.ParseIdent(); + + if (space != null && (RectangularColorSpaces.Contains(space) || PolarColorSpaces.Contains(space))) + { + var result = String.Concat(CssKeywords.In, " ", space.ToLowerInvariant()); + + if (PolarColorSpaces.Contains(space)) + { + var methodStart = source.Index; + source.SkipSpacesAndComments(); + var method = source.ParseIdent(); + source.SkipSpacesAndComments(); + + if (method != null && HueInterpolationMethods.Contains(method) && source.IsIdentifier(CssKeywords.Hue)) + { + return String.Concat(result, " ", method.ToLowerInvariant(), " ", CssKeywords.Hue); + } + + source.BackTo(methodStart); + } + + return result; + } + } + + source.BackTo(start); + return null; + } + + private static readonly HashSet RectangularColorSpaces = new(StringComparer.OrdinalIgnoreCase) + { + "srgb", "srgb-linear", "display-p3", "a98-rgb", "prophoto-rgb", "rec2020", "lab", "oklab", "xyz", "xyz-d50", "xyz-d65", + }; + + private static readonly HashSet PolarColorSpaces = new(StringComparer.OrdinalIgnoreCase) + { + "hsl", "hwb", "lch", "oklch", + }; + + private static readonly HashSet HueInterpolationMethods = new(StringComparer.OrdinalIgnoreCase) + { + "shorter", "longer", "increasing", "decreasing", + }; + private static ICssValue ParseGradientStopPosition(StringSource source) => source.ParseDistanceOrCalc() ?? source.ParseAngleOrCalc(); @@ -330,6 +432,7 @@ private static ICssValue ParseLinearAngleKeywords(StringSource source) var height = default(ICssValue); var size = CssRadialGradientValue.SizeMode.None; var redo = false; + var identStart = source.Index; var ident = source.ParseIdent(); if (ident != null) @@ -379,6 +482,7 @@ private static ICssValue ParseLinearAngleKeywords(StringSource source) { size = Map.RadialGradientSizeModes[ident]; source.SkipSpacesAndComments(); + identStart = source.Index; ident = source.ParseIdent(); if (ident != null) @@ -424,9 +528,17 @@ private static ICssValue ParseLinearAngleKeywords(StringSource source) if (redo) { source.SkipSpacesAndComments(); + identStart = source.Index; ident = source.ParseIdent(); } + if (ident != null && ident.Isi(CssKeywords.In)) + { + // the color interpolation method follows + source.BackTo(identStart); + ident = null; + } + if (ident != null) { if (!ident.Isi(CssKeywords.At)) diff --git a/src/AngleSharp.Css/Values/Composites/CssGradientStopValue.cs b/src/AngleSharp.Css/Values/Composites/CssGradientStopValue.cs index 20226f13..2dcf136c 100644 --- a/src/AngleSharp.Css/Values/Composites/CssGradientStopValue.cs +++ b/src/AngleSharp.Css/Values/Composites/CssGradientStopValue.cs @@ -15,6 +15,7 @@ public sealed class CssGradientStopValue : ICssCompositeValue, IEquatable + /// Creates a color hint ("red, 20%, blue"): the position between two color stops + /// where their colors are mixed half and half. + /// + /// The location of the hint. + /// The hint, which has no color of its own. + public static CssGradientStopValue CreateHint(ICssValue location) => new(location, true); + #endregion #region Properties @@ -55,10 +70,15 @@ public CssGradientStopValue(CssColorValue color, ICssValue location = null) /// public ICssValue Location => _location; + /// + /// Gets if this is a color hint rather than a color stop. + /// + public Boolean IsHint => _hint; + /// /// Gets the CSS text representation. /// - public String CssText => IsDetermined ? String.Concat(_color.CssText, " ", _location.CssText) : _color.CssText; + public String CssText => _hint ? _location.CssText : IsDetermined ? String.Concat(_color.CssText, " ", _location.CssText) : _color.CssText; #endregion @@ -74,7 +94,7 @@ public Boolean Equals(CssGradientStopValue other) if (other is not null) { var comparer = EqualityComparer.Default; - return comparer.Equals(_color, other._color) && comparer.Equals(_location, other._location); + return _hint == other._hint && comparer.Equals(_color, other._color) && comparer.Equals(_location, other._location); } return false; @@ -82,8 +102,14 @@ public Boolean Equals(CssGradientStopValue other) ICssValue ICssValue.Compute(ICssComputeContext context) { - var color = ((ICssValue)_color).Compute(context); var location = _location?.Compute(context); + + if (_hint) + { + return CreateHint(location); + } + + var color = ((ICssValue)_color).Compute(context); return new CssGradientStopValue((CssColorValue)color, location); } diff --git a/src/AngleSharp.Css/Values/Functions/CssConicGradientValue.cs b/src/AngleSharp.Css/Values/Functions/CssConicGradientValue.cs index 07d48a7d..eedbb334 100644 --- a/src/AngleSharp.Css/Values/Functions/CssConicGradientValue.cs +++ b/src/AngleSharp.Css/Values/Functions/CssConicGradientValue.cs @@ -19,6 +19,7 @@ public sealed class CssConicGradientValue : ICssGradientFunctionValue, IEquatabl private readonly ICssValue _center; private readonly ICssValue _angle; private readonly Boolean _repeating; + private readonly String _interpolation; #endregion @@ -32,11 +33,25 @@ public sealed class CssConicGradientValue : ICssGradientFunctionValue, IEquatabl /// The stops to use. /// Indicates if the gradient is repeating. public CssConicGradientValue(ICssValue angle, ICssValue center, ICssValue[] stops, Boolean repeating = false) + : this(angle, center, stops, repeating, null) + { + } + + /// + /// Creates a new conic gradient interpolating its colors as given. + /// + /// The angle of the conic gradient. + /// The center to use. + /// The stops to use. + /// Indicates if the gradient is repeating. + /// The color interpolation method, e.g. "in oklch", if any. + public CssConicGradientValue(ICssValue angle, ICssValue center, ICssValue[] stops, Boolean repeating, String interpolation) { _stops = stops; _center = center; _angle = angle; _repeating = repeating; + _interpolation = interpolation; } #endregion @@ -80,22 +95,34 @@ public String CssText { var defaultAngle = _angle as CssAngleValue?; var defaultPosition = _center as CssPoint2D?; - var offset = (defaultAngle.HasValue ? 1 : 0) + (defaultPosition.HasValue ? 1 : 0); - var args = new String[_stops.Length + offset]; + var prelude = new List(); + // "from at " is a single argument if (defaultAngle.HasValue) { - args[0] = $"from {defaultAngle.Value.CssText}"; + prelude.Add($"from {defaultAngle.Value.CssText}"); } if (defaultPosition.HasValue) { - args[offset - 1] = $"at {defaultPosition.Value.CssText}"; + prelude.Add($"at {defaultPosition.Value.CssText}"); + } + + if (_interpolation != null) + { + prelude.Add(_interpolation); + } + + var args = new List(_stops.Length + 1); + + if (prelude.Count > 0) + { + args.Add(String.Join(" ", prelude)); } for (var i = 0; i < _stops.Length; i++) { - args[offset++] = _stops[i].CssText; + args.Add(_stops[i].CssText); } return Name.CssFunction(String.Join(", ", args)); @@ -124,6 +151,11 @@ public String CssText /// public Boolean IsRepeating => _repeating; + /// + /// Gets the color interpolation method, e.g. "in oklch" or "in hsl longer hue", if any. + /// + public String Interpolation => _interpolation; + #endregion #region Methods @@ -140,7 +172,7 @@ public Boolean Equals(CssConicGradientValue other) var comparer = EqualityComparer.Default; var l = _stops.Length; - if (comparer.Equals(_angle, other._angle) && comparer.Equals(_center, other._center) && _repeating == other._repeating && l == other._stops.Length) + if (comparer.Equals(_angle, other._angle) && comparer.Equals(_center, other._center) && _repeating == other._repeating && _interpolation == other._interpolation && l == other._stops.Length) { for (var i = 0; i < l; i++) { @@ -171,7 +203,7 @@ ICssValue ICssValue.Compute(ICssComputeContext context) var center = _center?.Compute(context); var angle = _angle?.Compute(context); var stops = _stops.Select(m => (CssGradientStopValue)((ICssValue)m).Compute(context)).ToArray(); - return new CssConicGradientValue(angle, center, stops, _repeating); + return new CssConicGradientValue(angle, center, stops, _repeating, _interpolation); } #endregion diff --git a/src/AngleSharp.Css/Values/Functions/CssLinearGradientValue.cs b/src/AngleSharp.Css/Values/Functions/CssLinearGradientValue.cs index 3b0478a4..20ac080d 100644 --- a/src/AngleSharp.Css/Values/Functions/CssLinearGradientValue.cs +++ b/src/AngleSharp.Css/Values/Functions/CssLinearGradientValue.cs @@ -18,6 +18,7 @@ public sealed class CssLinearGradientValue : ICssGradientFunctionValue, IEquatab private readonly ICssValue[] _stops; private readonly ICssValue _angle; private readonly Boolean _repeating; + private readonly String _interpolation; #endregion @@ -30,10 +31,23 @@ public sealed class CssLinearGradientValue : ICssGradientFunctionValue, IEquatab /// The stops to use. /// Indicates if the gradient is repeating. public CssLinearGradientValue(ICssValue angle, ICssValue[] stops, Boolean repeating = false) + : this(angle, stops, repeating, null) + { + } + + /// + /// Creates a new linear gradient interpolating its colors as given. + /// + /// The angle of the linear gradient. + /// The stops to use. + /// Indicates if the gradient is repeating. + /// The color interpolation method, e.g. "in oklch", if any. + public CssLinearGradientValue(ICssValue angle, ICssValue[] stops, Boolean repeating, String interpolation) { _stops = stops; _angle = angle; _repeating = repeating; + _interpolation = interpolation; } #endregion @@ -71,7 +85,7 @@ public String CssText get { var defaultAngle = _angle as CssAngleValue?; - var offset = defaultAngle.HasValue ? 1 : 0; + var offset = defaultAngle.HasValue || _interpolation != null ? 1 : 0; var args = new String[_stops.Length + offset]; if (defaultAngle.HasValue) @@ -90,6 +104,11 @@ public String CssText args[0] = args[0] ?? _angle.CssText; } + if (_interpolation != null) + { + args[0] = args[0] != null ? String.Concat(args[0], " ", _interpolation) : _interpolation; + } + for (var i = 0; i < _stops.Length; i++) { args[offset++] = _stops[i].CssText; @@ -114,6 +133,11 @@ public String CssText /// public Boolean IsRepeating => _repeating; + /// + /// Gets the color interpolation method, e.g. "in oklch" or "in hsl longer hue", if any. + /// + public String Interpolation => _interpolation; + #endregion #region Methods @@ -130,7 +154,7 @@ public Boolean Equals(CssLinearGradientValue other) var comparer = EqualityComparer.Default; var l = _stops.Length; - if (comparer.Equals(_angle, other._angle) && _repeating == other._repeating && l == other._stops.Length) + if (comparer.Equals(_angle, other._angle) && _repeating == other._repeating && _interpolation == other._interpolation && l == other._stops.Length) { for (var i = 0; i < l; i++) { @@ -159,7 +183,7 @@ ICssValue ICssValue.Compute(ICssComputeContext context) // unconditionally threw a NullReferenceException for that ordinary case. var angle = _angle?.Compute(context); var stops = _stops.Select(m => (CssGradientStopValue)((ICssValue)m).Compute(context)).ToArray(); - return new CssLinearGradientValue(angle, stops, _repeating); + return new CssLinearGradientValue(angle, stops, _repeating, _interpolation); } #endregion diff --git a/src/AngleSharp.Css/Values/Functions/CssRadialGradientValue.cs b/src/AngleSharp.Css/Values/Functions/CssRadialGradientValue.cs index 764b9af6..56bdd16f 100644 --- a/src/AngleSharp.Css/Values/Functions/CssRadialGradientValue.cs +++ b/src/AngleSharp.Css/Values/Functions/CssRadialGradientValue.cs @@ -23,6 +23,7 @@ public sealed class CssRadialGradientValue : ICssGradientFunctionValue, IEquatab private readonly Boolean _repeating; private readonly Boolean _circle; private readonly SizeMode _sizeMode; + private readonly String _interpolation; #endregion @@ -39,7 +40,24 @@ public sealed class CssRadialGradientValue : ICssGradientFunctionValue, IEquatab /// A collection of stops to use. /// The repeating setting. public CssRadialGradientValue(Boolean circle, CssPoint2D center, ICssValue width, ICssValue height, SizeMode sizeMode, ICssValue[] stops, Boolean repeating = false) + : this(circle, center, width, height, sizeMode, stops, repeating, null) { + } + + /// + /// Creates a new radial gradient interpolating its colors as given. + /// + /// Determines if the radial gradient has to be forced to a circle form. + /// The center point of the gradient. + /// The width of the ellipsoid. + /// The height of the ellipsoid. + /// The size mode of the ellipsoid. + /// A collection of stops to use. + /// The repeating setting. + /// The color interpolation method, e.g. "in oklch", if any. + public CssRadialGradientValue(Boolean circle, CssPoint2D center, ICssValue width, ICssValue height, SizeMode sizeMode, ICssValue[] stops, Boolean repeating, String interpolation) + { + _interpolation = interpolation; _stops = stops; _center = center; _width = width; @@ -105,6 +123,18 @@ public ICssValue[] Arguments }.Where(m => !String.IsNullOrEmpty(m))))); } + if (_interpolation != null) + { + if (args.Count > 0) + { + args[0] = new CssAnyValue(String.Concat(args[0].CssText, " ", _interpolation)); + } + else + { + args.Add(new CssAnyValue(_interpolation)); + } + } + foreach (var stop in _stops) { args.Add(stop); @@ -154,6 +184,11 @@ public ICssValue[] Arguments /// public Boolean IsRepeating => _repeating; + /// + /// Gets the color interpolation method, e.g. "in oklch" or "in hsl longer hue", if any. + /// + public String Interpolation => _interpolation; + #endregion #region Methods @@ -168,7 +203,7 @@ public Boolean Equals(CssRadialGradientValue other) if (other is not null) { var comparer = EqualityComparer.Default; - if (comparer.Equals(_center, other._center) && comparer.Equals(_width, other._width) && comparer.Equals(_height, other._height) && _repeating == other._repeating && _sizeMode == other._sizeMode && _circle == other._circle) + if (comparer.Equals(_center, other._center) && comparer.Equals(_width, other._width) && comparer.Equals(_height, other._height) && _repeating == other._repeating && _sizeMode == other._sizeMode && _circle == other._circle && _interpolation == other._interpolation) { var count = _stops.Length; @@ -203,7 +238,7 @@ ICssValue ICssValue.Compute(ICssComputeContext context) var width = _width?.Compute(context); var height = _height?.Compute(context); var stops = _stops.Select(m => (CssGradientStopValue)((ICssValue)m).Compute(context)).ToArray(); - return new CssRadialGradientValue(_circle, center, width, height, _sizeMode, stops, _repeating); + return new CssRadialGradientValue(_circle, center, width, height, _sizeMode, stops, _repeating, _interpolation); } Boolean IEquatable.Equals(ICssValue other) => other is CssRadialGradientValue value && Equals(value); From de5bd492036834d3e618f4d1e80ae956ae27a22d Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 15:53:50 +0100 Subject: [PATCH 07/19] Scope fixes --- .../Dom/Internal/Rules/CssScopeRule.cs | 114 ++++++++++++++++++ .../Dom/Internal/Rules/CssStyleRule.cs | 13 ++ .../Dom/Internal/StyleCollection.cs | 14 +++ 3 files changed, 141 insertions(+) diff --git a/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs b/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs index c44bda3a..0460e9ef 100644 --- a/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs +++ b/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs @@ -1,6 +1,7 @@ #nullable disable namespace AngleSharp.Css.Dom { + using AngleSharp.Dom; using System; using System.Diagnostics; using System.IO; @@ -16,8 +17,121 @@ internal CssScopeRule(ICssStyleSheet owner) { } + private String _parsedText; + private ISelector _start; + private ISelector _end; + public String ScopeText { get; set; } + /// + /// Finds the scoping root of the element (CSS Cascade 6, 2.5): the closest inclusive + /// ancestor matching the scope's start (the parent of the style sheet's owner if there + /// is none), such that the element is not in a scoping limit below it. + /// + internal Boolean TryGetScopeRoot(IElement element, out IElement root) + { + root = null; + EnsureSelectors(); + + if (_start is null) + { + // @scope { ... } is scoped to the parent of the " + + "
in
out
x"); + var window = document.DefaultView; + + Assert.AreEqual(Green, window.GetComputedStyle(document.GetElementById("in")).GetColor()); + Assert.AreEqual("rgba(255, 0, 0, 1)", window.GetComputedStyle(document.GetElementById("out")).GetColor()); + Assert.AreEqual("rgba(255, 0, 0, 1)", window.GetComputedStyle(document.GetElementById("outside")).GetColor()); + } + + [TestCase("::marker", "
  • A
")] + [TestCase("::first-line", "

A

")] + [TestCase("::first-letter", "

A

")] + public async Task PseudoElementOfARendererIsStyled(string pseudo, string html) + { + var document = await OpenAsync(html); + Assert.AreEqual(Green, document.DefaultView.GetComputedStyle(document.GetElementById("t"), pseudo).GetColor()); + } + + [Test] + public async Task ModalDialogMatchesModalAndClosedOneIsHidden() + { + var document = await OpenAsync("A"); + var dialog = (IHtmlDialogElement)document.GetElementById("d"); + + Assert.AreEqual("none", document.DefaultView.GetComputedStyle(dialog).GetDisplay()); + dialog.ShowModal(); + Assert.IsTrue(dialog.Matches(":modal")); + Assert.AreEqual("fixed", document.DefaultView.GetComputedStyle(dialog).GetPosition()); + dialog.Close(); + Assert.IsFalse(dialog.Matches(":modal")); + } + + [Test] + public async Task ShadowTreeIsStyledByItsOwnSheetsAndInheritsFromTheHost() + { + var document = await OpenAsync("
"); + var host = document.GetElementById("host"); + var root = host.AttachShadow(); + root.InnerHtml = "A"; + var window = document.DefaultView; + + Assert.AreEqual(Green, window.GetComputedStyle(root.QuerySelector(".label")).GetColor()); + Assert.AreEqual("300", window.GetComputedStyle(root.QuerySelector("b")).GetFontWeight()); + } + } +} diff --git a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs index 29de0f84..e9e2bdae 100644 --- a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs @@ -49,7 +49,11 @@ public static IStyleCollection GetStyleCollection(this IShadowRoot shadowRoot, I var defaultStyleSheetProvider = ctx.GetServices(); var defaultSheets = defaultStyleSheetProvider.Select(m => m.Default).Where(m => m != null).ToList(); var shadowSheets = shadowRoot.GetEffectiveStyleSheets().ToList(); - return new StyleCollection(defaultSheets, shadowSheets, renderDevice, host); + return new StyleCollection(defaultSheets, shadowSheets, renderDevice, host) + { + OuterProvider = () => (host.GetRoot() is IShadowRoot outerRoot ? outerRoot.GetStyleCollection(renderDevice) : + host.Owner?.DefaultView?.GetStyleCollection(renderDevice)) as StyleCollection, + }; } /// @@ -118,7 +122,11 @@ private static ICssStyleDeclaration GetComputedDeclarations(IStyleCollection sty while (nodes.Count > 0) { var node = nodes.Pop(); - var explicitStyle = styles.ComputeExplicitStyle(node); + // a shadow host is also styled by the :host rules of its shadow tree + var explicitStyle = node is not IPseudoElement && node.ShadowRoot is { } shadowRoot && styles is StyleCollection && + shadowRoot.GetStyleCollection(styles.Device) is StyleCollection shadowStyles + ? styles.ComputeHostStyle(shadowStyles, node) + : styles.ComputeExplicitStyle(node); var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parent, (styles as StyleCollection)?.GetRegistrations()); parent = explicitStyle.PrepareComputedDeclarations(parent!, context).Compute(context).Blockify(node, parent); } @@ -170,6 +178,7 @@ public static ICssStyleDeclaration ComputeExplicitStyle(this IStyleCollection st ApplyImportantLayerOrder(computedStyle, matches); ReturnMatches(styles, matches); + ApplyPartRules(styles, element, computedStyle); if (element is IHtmlElement || element is ISvgElement) { @@ -379,6 +388,40 @@ private static Int32 CountDeclarations(List matches) return count; } + /// + /// An element of a shadow tree with a part attribute is also styled by the ::part() rules + /// of the tree its host is in, which win over the ones of its own tree (CSS Shadow Parts 1). + /// + private static void ApplyPartRules(IStyleCollection styles, IElement element, CssStyleDeclaration computedStyle) + { + if (styles is not StyleCollection { Scope: { } host } collection || element is IPseudoElement || + element.GetAttribute("part") is not { Length: > 0 } part || element.GetRoot() is not IShadowRoot root || + root.Host != host || collection.Outer is not { } outer) + { + return; + } + + var names = part.Split(new[] { ' ', '\t', '\n', '\r', '\f' }, StringSplitOptions.RemoveEmptyEntries); + + if (names.Length == 0) + { + return; + } + + var partElement = new PseudoElement(host, "part(" + String.Join(" ", names) + ")"); + var matches = outer.SortBySpecificity(partElement); + + foreach (var match in matches) + { + if (!match.IsDefault) + { + computedStyle.SetDeclarations(match.Rule.Style); + } + } + + ReturnMatches(outer, matches); + } + private static void ReturnMatches(IStyleCollection styles, List matches) { if (styles is StyleCollection collection) diff --git a/src/AngleSharp.Css/Extensions/WindowExtensions.cs b/src/AngleSharp.Css/Extensions/WindowExtensions.cs index 48758cb5..8988a8cf 100644 --- a/src/AngleSharp.Css/Extensions/WindowExtensions.cs +++ b/src/AngleSharp.Css/Extensions/WindowExtensions.cs @@ -116,10 +116,46 @@ public static Double DevicePixelRatio(this IWindow window) public static ICssStyleDeclaration GetComputedStyle(this IWindow window, IElement element, String? pseudo = null) { var device = window.GetRenderDevice(); + + if (element.GetRoot() is IShadowRoot) + { + return ComputeShadowTreeStyle(window, device, element, pseudo); + } + var styleCollection = ComputedStyleCollections.Get(window.Document, window.GetStyleCollection(device)); return styleCollection.ComputeDeclarations(element, pseudo); } + /// + /// An element of a shadow tree is styled by the sheets of its shadow root and inherits + /// from the elements of its tree up to the host (CSS Scoping 1, 2.4). + /// + private static ICssStyleDeclaration ComputeShadowTreeStyle(IWindow window, IRenderDevice device, IElement element, String? pseudo) + { + var shadowRoot = (IShadowRoot)element.GetRoot(); + var styles = shadowRoot.GetStyleCollection(device); + var chain = new Stack(); + + for (var current = element; current is not null; current = current.ParentElement) + { + chain.Push(current); + } + + var style = window.GetComputedStyle(shadowRoot.Host); + + while (chain.Count > 0) + { + style = styles.ComputeDeclarationsWithParent(chain.Pop(), style); + } + + if (!String.IsNullOrEmpty(pseudo) && element.Pseudo(pseudo!.TrimStart(':')) is { } pseudoElement) + { + style = styles.ComputeDeclarationsWithParent(pseudoElement, style); + } + + return style; + } + /// /// The style collection of the last computed style of each document: scripts ask for /// computed styles many times in a row (e.g. Elementor reads the device mode from the diff --git a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs index 9c86cabf..5c7400c9 100644 --- a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs +++ b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs @@ -451,7 +451,7 @@ private static IEnumerable GetFlatChildren( } var shadowSheets = shadowRoot.GetEffectiveStyleSheets().ToList(); - return new StyleCollection(_defaultSheets, shadowSheets, collection.Device, element); + return new StyleCollection(_defaultSheets, shadowSheets, collection.Device, element) { OuterProvider = () => collection }; } private static IEnumerable ExpandSlots( From e793b1148deabfbb2d2370c60eedb9da53d093f9 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 15:54:13 +0100 Subject: [PATCH 09/19] Changed to 1.6 --- CHANGELOG.md | 10 +++++++++- src/AngleSharp.Css.Docs/package.json | 2 +- src/Directory.Build.props | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c456fcaf..676357a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# 1.5.1 +# 1.6.0 Released on tbd. @@ -9,6 +9,14 @@ Released on tbd. - Fixed the `color` media feature, e.g. `(color)` and `(min-color: 0)` not matching, and `monochrome` without a value - Fixed `not` making a media query with an unknown feature (e.g. `not all and (bogus)`) match - Fixed `minmax()` with a math function (e.g. `repeat(auto-fill, minmax(min(100%, 17rem), 1fr))`) making `grid-template-columns` invalid in an auto repeat +- Fixed `@scope` rules never applying; a scope root and limit (`@scope (.a) to (.b)`) are respected +- Fixed color hints (e.g. `linear-gradient(black, 20%, white)`) and color interpolation methods (e.g. `in oklch`, `in hsl longer hue`) making a gradient invalid +- Fixed `conic-gradient` with both `from` and `at` being serialized with a comma between them +- Fixed `getComputedStyle` of a shadow host leaving out the `:host` rules of its shadow tree +- Fixed `getComputedStyle` of an element in a shadow tree ignoring the styles of its shadow root and not inheriting from the host +- Fixed `::marker`, `::first-line` and `::first-letter` rules never matching (e.g. for `getComputedStyle(li, '::marker')`) +- Added the `:modal` pseudo-class and the user agent styles of `dialog` +- Added `::part()` styling the parts of shadow trees # 1.5.0 diff --git a/src/AngleSharp.Css.Docs/package.json b/src/AngleSharp.Css.Docs/package.json index 0f08dd5d..5bb81e44 100644 --- a/src/AngleSharp.Css.Docs/package.json +++ b/src/AngleSharp.Css.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/css", - "version": "1.5.1", + "version": "1.6.0", "preview": true, "description": "The doclet for the AngleSharp.Css documentation.", "keywords": [ diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 67a24233..7f04ea87 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ Extends the CSSOM from the core AngleSharp library. AngleSharp.Css - 1.5.1 + 1.6.0 enable latest true From fbf1732e66ed6dc225213bf47b45afbb85083d5c Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 21:03:22 +0100 Subject: [PATCH 10/19] Added fullscreen pseudo selector --- .../Styling/FullscreenTests.cs | 65 +++++++++++++++++++ .../Internal/FullscreenPseudoClassSelector.cs | 21 ++++++ .../CssPseudoClassSelectorFactory.cs | 9 +++ 3 files changed, 95 insertions(+) create mode 100644 src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs create mode 100644 src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs diff --git a/src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs b/src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs new file mode 100644 index 00000000..5657a8e3 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs @@ -0,0 +1,65 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using NUnit.Framework; + using static CssConstructionFunctions; + + /// + /// The CSS part of the Fullscreen API: the `:fullscreen` pseudo-class, which the host forces + /// on the element it shows fullscreen, and the user-agent styles making it cover the viewport. + /// + [TestFixture] + public class FullscreenTests + { + [Test] + public void FullscreenDoesNotMatchByItself() + { + var document = ParseDocument("
x
"); + var video = document.GetElementById("video"); + + Assert.IsFalse(video.Matches(":fullscreen")); + Assert.IsTrue(video.Matches(":not(:fullscreen)")); + } + + [Test] + public void FullscreenMatchesTheElementTheHostShowsFullscreen() + { + var document = ParseDocument("
x
"); + var video = document.GetElementById("video"); + + video.SetPseudoClass("fullscreen"); + Assert.IsTrue(video.Matches(":fullscreen")); + + video.RemovePseudoClass("fullscreen"); + Assert.IsFalse(video.Matches(":fullscreen")); + } + + [Test] + public void FullscreenElementCoversTheViewport() + { + var document = ParseDocument("
x
"); + var video = document.GetElementById("video"); + + video.SetPseudoClass("fullscreen"); + var style = document.DefaultView.GetComputedStyle(video); + + Assert.AreEqual("fixed", style.GetPosition()); + Assert.AreEqual("100%", style.GetWidth()); + Assert.AreEqual("0px", style.GetPropertyValue("margin-top")); + } + + [Test] + public void AppendedDefaultRulesAreKept() + { + var provider = new CssDefaultStyleSheetProvider(); + provider.AppendDefault("x-first { color: red }"); + provider.AppendDefault("x-second { color: blue }"); + var css = provider.Default.ToCss(); + + StringAssert.Contains("x-first", css); + StringAssert.Contains("x-second", css); + } + } +} diff --git a/src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs b/src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs new file mode 100644 index 00000000..cbb23a40 --- /dev/null +++ b/src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs @@ -0,0 +1,21 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Dom; + using System; + + /// + /// The :fullscreen pseudo-class, which only the host knows to match: it forces it on the + /// element it shows fullscreen (see ElementExtensions.SetPseudoClass). + /// + sealed class FullscreenPseudoClassSelector : ISelector + { + public Priority Specificity => Priority.OneClass; + + public String Text => PseudoClassNames.Separator + CssPseudoClassSelectorFactory.Fullscreen; + + public void Accept(ISelectorVisitor visitor) => visitor.PseudoClass(CssPseudoClassSelectorFactory.Fullscreen); + + public Boolean Match(IElement element, IElement? scope) => false; + } +} diff --git a/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs b/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs index 12500a57..e35a233c 100644 --- a/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs +++ b/src/AngleSharp.Css/Factories/CssPseudoClassSelectorFactory.cs @@ -20,10 +20,14 @@ sealed class CssPseudoClassSelectorFactory : IPseudoClassSelectorFactory ///
public static readonly String Modal = "modal"; + public static readonly String Fullscreen = "fullscreen"; + private static readonly ISelector PopoverOpenSelector = new PopoverOpenPseudoClassSelector(); private static readonly ISelector ModalSelector = new ModalPseudoClassSelector(); + private static readonly ISelector FullscreenSelector = new FullscreenPseudoClassSelector(); + private readonly IPseudoClassSelectorFactory _inner; public CssPseudoClassSelectorFactory(IPseudoClassSelectorFactory inner) @@ -45,6 +49,11 @@ public CssPseudoClassSelectorFactory(IPseudoClassSelectorFactory inner) return ModalSelector; } + if (selector is null && name.Equals(Fullscreen, StringComparison.OrdinalIgnoreCase)) + { + return FullscreenSelector; + } + return selector; } } From e3655e89128a4c23bbb42662003bfbf4503a236a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 21:03:42 +0100 Subject: [PATCH 11/19] Added support for details element --- .../Extensions/PseudoElementRenderTests.cs | 16 ++++++++++- .../RenderTree/RenderTreeBuilder.cs | 27 ++++++++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs b/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs index 20b88cfe..38e7c3f2 100644 --- a/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs +++ b/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs @@ -255,5 +255,19 @@ public void ContentAddedThroughTheObjectModelGeneratesANode() Assert.IsTrue(FindElement((ElementRenderNode)window.Render(new PlainRenderDevice()), "target").Children.Any(m => m.Ref is IPseudoElement)); } -} + + [Test] + public void ClosedDetailsRendersItsSummaryOnly() + { + var root = Render("
SumText

Body

SumText

Body

"); + var closed = FindElement(root, "closed"); + var open = FindElement(root, "open"); + + Assert.AreEqual(1, closed.Children.Count()); + Assert.IsNotNull(FindElement(closed, "s1")); + Assert.IsNull(FindElement(closed, "p1")); + Assert.AreEqual(3, open.Children.Count()); + Assert.IsNotNull(FindElement(open, "p2")); + } + } } diff --git a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs index 5c7400c9..6a4cfa80 100644 --- a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs +++ b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs @@ -436,9 +436,34 @@ private static IEnumerable GetFlatChildren( return ExpandSlots(element.ShadowRoot!.ChildNodes, shadowCollection, collection); } + if (IsClosedDetails(element)) + { + return ExpandSlots(GetSummary(element), collection, slottedCollection); + } + return ExpandSlots(element.ChildNodes, collection, slottedCollection); } + /// + /// A closed details element only shows its summary: the rest of its content is in a slot + /// of its shadow tree that is not rendered then (HTML 15.5.15). + /// + private static Boolean IsClosedDetails(IElement element) => + element is not IPseudoElement && element.LocalName.Is(TagNames.Details) && + element.NamespaceUri.Is(NamespaceNames.HtmlUri) && !element.HasAttribute(AttributeNames.Open); + + private static IEnumerable GetSummary(IElement details) + { + foreach (var child in details.Children) + { + if (child.LocalName.Is(TagNames.Summary) && child.NamespaceUri.Is(NamespaceNames.HtmlUri)) + { + yield return child; + yield break; + } + } + } + /// /// Creates the styles of the shadow tree of a shadow host, i.e. the ones from the shadow /// root's own style sheets, which also style the host via :host. @@ -455,7 +480,7 @@ private static IEnumerable GetFlatChildren( } private static IEnumerable ExpandSlots( - INodeList nodes, + IEnumerable nodes, StyleCollection collection, StyleCollection? slottedCollection) { From e67f279255f743d38c1c9ef6d3b53779c78e39ec Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 21:05:39 +0100 Subject: [PATCH 12/19] Improved default sheet and persist appendices --- .../Styling/Configuration.cs | 4 +++- .../CssDefaultStyleSheetProvider.cs | 18 ++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/AngleSharp.Css.Tests/Styling/Configuration.cs b/src/AngleSharp.Css.Tests/Styling/Configuration.cs index 8b816227..bf8bf9c4 100644 --- a/src/AngleSharp.Css.Tests/Styling/Configuration.cs +++ b/src/AngleSharp.Css.Tests/Styling/Configuration.cs @@ -56,7 +56,9 @@ public void ObtainDefaultSheet() // `strong` stay `bolder`, which takes a rule of its own. // 89, not 86: the UA stylesheet now also carries the dialog rules (hidden unless // open, centered, and fixed in the viewport while it is a modal). - Assert.AreEqual(89, sheet.Rules.Length); + // 92, not 89: the UA stylesheet now also carries the fullscreen rules (covering the + // viewport, without the border of an iframe, and a black `::backdrop`). + Assert.AreEqual(92, sheet.Rules.Length); } } } diff --git a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs index 7a440eb8..ae030283 100644 --- a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs +++ b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs @@ -10,6 +10,7 @@ sealed class CssDefaultStyleSheetProvider : ICssDefaultStyleSheetProvider #region Fields private ICssStyleSheet? _default; + private String _appended = String.Empty; #endregion @@ -21,11 +22,21 @@ sealed class CssDefaultStyleSheetProvider : ICssDefaultStyleSheetProvider #region Methods - public void SetDefault(ICssStyleSheet? sheet) => _default = sheet; + public void SetDefault(ICssStyleSheet? sheet) + { + _default = sheet; + _appended = String.Empty; + } public void SetDefault(String source) => SetDefault(Parse(source)); - public void AppendDefault(String source) => SetDefault(Parse($"{DefaultSource}\r\n{source}")); + // what was appended before stays (e.g. the rules of several extensions) + public void AppendDefault(String source) + { + var appended = $"{_appended}\r\n{source}"; + SetDefault(Parse($"{DefaultSource}{appended}")); + _appended = appended; + } #endregion @@ -90,6 +101,9 @@ private static ICssStyleSheet Parse(String source) dialog:modal { position: fixed; overflow: auto; top: 0; bottom: 0; max-width: calc(100% - 6px - 2em); max-height: calc(100% - 6px - 2em) } [popover] { position: fixed; inset: 0; width: fit-content; height: fit-content; margin: auto; border: solid; padding: 0.25em; overflow: auto; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255) } :popover-open::backdrop { position: fixed; inset: 0; pointer-events: none !important; background-color: transparent } +:not(:root):fullscreen { position: fixed !important; inset: 0 !important; margin: 0 !important; box-sizing: border-box !important; min-width: 0 !important; max-width: none !important; min-height: 0 !important; max-height: none !important; width: 100% !important; height: 100% !important; transform: none !important; object-fit: contain } +iframe:fullscreen { border: none !important; padding: 0 !important } +:not(:root):fullscreen::backdrop { background: black } table { display: table } tr { display: table-row } thead { display: table-header-group } From 80e01777c6f01d8d50c2e424daece6dc9fd538c9 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 21:05:45 +0100 Subject: [PATCH 13/19] Updated changelog --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 676357a6..4c1067ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,11 @@ Released on tbd. - Fixed `getComputedStyle` of a shadow host leaving out the `:host` rules of its shadow tree - Fixed `getComputedStyle` of an element in a shadow tree ignoring the styles of its shadow root and not inheriting from the host - Fixed `::marker`, `::first-line` and `::first-letter` rules never matching (e.g. for `getComputedStyle(li, '::marker')`) -- Added the `:modal` pseudo-class and the user agent styles of `dialog` +- Fixed `AppendDefault` of the default style sheet provider dropping what was appended before +- Fixed a closed `details` showing more than its `summary` - Added `::part()` styling the parts of shadow trees +- Added the `:modal` pseudo-class and the user agent styles of `dialog` +- Added the `:fullscreen` pseudo-class, which a host forces (`SetPseudoClass`) on the element it shows fullscreen, and its user agent styles # 1.5.0 From c676a035d07eaf6684d1e84b24c7deb97feaf798 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 23:37:23 +0100 Subject: [PATCH 14/19] More fixes and improvements --- CHANGELOG.md | 3 ++ .../Declarations/CssTransitionProperty.cs | 16 ++++++++++ .../Styling/RegisteredCustomPropertyTests.cs | 31 ++++++++++++++++++- .../BrowsingContextExtensions.cs | 28 +++++++++++++++++ .../Extensions/StyleCollectionExtensions.cs | 26 ++++++++++++++++ src/AngleSharp.Css/IAnimatedValueProvider.cs | 30 ++++++++++++++++++ .../Parser/Micro/IdentParser.cs | 15 +++++++++ .../Values/Primitives/CssAngleValue.cs | 6 ++-- 8 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 src/AngleSharp.Css/IAnimatedValueProvider.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c1067ae..d239c8c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,9 +17,12 @@ Released on tbd. - Fixed `::marker`, `::first-line` and `::first-letter` rules never matching (e.g. for `getComputedStyle(li, '::marker')`) - Fixed `AppendDefault` of the default style sheet provider dropping what was appended before - Fixed a closed `details` showing more than its `summary` +- Fixed `transition-property` not accepting custom properties +- Fixed angles being computed in `rad` instead of the canonical `deg` - Added `::part()` styling the parts of shadow trees - Added the `:modal` pseudo-class and the user agent styles of `dialog` - Added the `:fullscreen` pseudo-class, which a host forces (`SetPseudoClass`) on the element it shows fullscreen, and its user agent styles +- Added `IAnimatedValueProvider` as the animation origin of the cascade # 1.5.0 diff --git a/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs b/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs index db5ac62c..97350806 100644 --- a/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs +++ b/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs @@ -63,6 +63,22 @@ public void CssTransitionPropertyDashSpecificIllegal() Assert.IsFalse(property.HasValue); } + [Test] + public void CssTransitionPropertyCustomPropertyLegal() + { + var property = ParseDeclaration("transition-property : opacity, --My-Angle"); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("opacity, --My-Angle", property.Value); + } + + [Test] + public void CssTransitionWithCustomPropertyLegal() + { + var property = ParseDeclaration("transition : --angle 1s"); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("--angle 1s", property.Value); + } + [Test] public void CssTransitionPropertySlidingVerticallyIllegal() { diff --git a/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs b/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs index f6303922..5e5ae145 100644 --- a/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs @@ -239,5 +239,34 @@ public void DeclaredStyleKeepsTheSpecifiedValue() Assert.AreEqual("2em", element.GetStyle().GetPropertyValue("--len")); } - } + + [Test] + public void AngleIsComputedInDegrees() + { + var style = Compute("@property --a { syntax: \"\"; inherits: false; initial-value: 0deg; } #target { --a: 0.5turn }", "
"); + Assert.AreEqual("180deg", style.GetPropertyValue("--a")); + } + + private sealed class AnimatedValues : IAnimatedValueProvider + { + public System.Collections.Generic.IReadOnlyDictionary GetAnimatedValues(IElement element, ICssStyleDeclaration declared) => + element.Id == "target" ? new System.Collections.Generic.Dictionary { { "--len", "7px" }, { "--imp", "1px" } } : null; + } + + [Test] + public void AnimatedValueWinsOverTheDeclaredOneButNotOverAnImportantOne() + { + var document = ParseDocument("
"); + document.Context.SetAnimatedValueProvider(new AnimatedValues()); + var style = document.GetElementById("target").ComputeCurrentStyle(); + var child = document.GetElementById("child").ComputeCurrentStyle(); + document.Context.SetAnimatedValueProvider(null); + + Assert.AreEqual("7px", style.GetPropertyValue("--len")); + Assert.AreEqual("7px", style.GetPropertyValue("width")); + Assert.AreEqual("3px", style.GetPropertyValue("height")); + // inherited as any value of the element is + Assert.AreEqual("7px", child.GetPropertyValue("--len")); + } +} } diff --git a/src/AngleSharp.Css/BrowsingContextExtensions.cs b/src/AngleSharp.Css/BrowsingContextExtensions.cs index 2e59013f..748c9cc9 100644 --- a/src/AngleSharp.Css/BrowsingContextExtensions.cs +++ b/src/AngleSharp.Css/BrowsingContextExtensions.cs @@ -17,6 +17,34 @@ public static class BrowsingContextExtensions { // the services of a context are fixed; resolving them walks all services private static readonly ConditionalWeakTable DeclarationFactories = new(); + private static readonly ConditionalWeakTable AnimatedValueProviders = new(); + + // most processes never have one, which spares every computed style the lookup + private static volatile Boolean _anyAnimatedValueProvider; + + /// + /// Sets what gives the animated values of the elements of the context's documents (see + /// ), or removes it with null. The styles computed from + /// then on include them; styles computed before stay as they are. + /// + /// The context to use. + /// The provider, or null. + public static void SetAnimatedValueProvider(this IBrowsingContext context, IAnimatedValueProvider provider) + { + if (context is null) + throw new ArgumentNullException(nameof(context)); + + AnimatedValueProviders.Remove(context); + + if (provider is not null) + { + _anyAnimatedValueProvider = true; + AnimatedValueProviders.Add(context, provider); + } + } + + internal static IAnimatedValueProvider GetAnimatedValueProvider(this IBrowsingContext context) => + _anyAnimatedValueProvider && context is not null && AnimatedValueProviders.TryGetValue(context, out var provider) ? provider : null; /// /// Loads a stylesheet resource via its URL. diff --git a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs index e9e2bdae..3980e0ad 100644 --- a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs @@ -185,10 +185,35 @@ public static ICssStyleDeclaration ComputeExplicitStyle(this IStyleCollection st computedStyle.SetDeclarations(element.GetStyleIfDeclared()); } + ApplyAnimatedValues(computedStyle, element, ctx); computedStyle.TrimExcess(); return computedStyle; } + /// + /// Gives the declarations the animated values of the element, which win over all but the + /// important ones (the animation origin, CSS Cascade 5, 6.2). + /// + private static void ApplyAnimatedValues(CssStyleDeclaration style, IElement element, IBrowsingContext context) + { + var values = context.GetAnimatedValueProvider()?.GetAnimatedValues(element, style); + + if (values is null || values.Count == 0) + { + return; + } + + var animated = new CssStyleDeclaration(context); + + foreach (var value in values) + { + animated.SetProperty(value.Key, value.Value); + } + + // an important declaration stays + style.SetDeclarations(animated); + } + /// /// Computes the declarations for the given element using a pre-computed /// parent style for inheritance, avoiding the O(depth) ancestor walk of @@ -257,6 +282,7 @@ internal static ICssStyleDeclaration ComputeHostStyle(this IStyleCollection styl ReturnMatches(styles, matches); computedStyle.SetDeclarations(host.GetStyleIfDeclared()); computedStyle.SetDeclarations(shadowStyle.Where(m => m.IsImportant).ToList()); + ApplyAnimatedValues(computedStyle, host, ctx); return computedStyle; } diff --git a/src/AngleSharp.Css/IAnimatedValueProvider.cs b/src/AngleSharp.Css/IAnimatedValueProvider.cs new file mode 100644 index 00000000..9fc2125d --- /dev/null +++ b/src/AngleSharp.Css/IAnimatedValueProvider.cs @@ -0,0 +1,30 @@ +#nullable enable +namespace AngleSharp.Css +{ + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + + /// + /// Gives the values the running animations and transitions of elements have now, which a host + /// following them (e.g. a renderer advancing its clock) knows. They are the animation origin of + /// the cascade (CSS Cascade 5, 6.2): an animated value wins over the declarations of the element, + /// unless one is important, so what depends on it follows, e.g. a var() of an animated custom + /// property or the input properties of a paint worklet. + /// + public interface IAnimatedValueProvider + { + /// + /// Gets the values the animations and transitions of the element give it now, by property + /// name (e.g. --angle: 37deg), or null if none does. + /// + /// The element whose style is computed. + /// + /// What the cascade gave the element without the animated values, e.g. the value a + /// transition goes to or the animation-name of the element. + /// + /// The animated values, or null. + IReadOnlyDictionary? GetAnimatedValues(IElement element, ICssStyleDeclaration declared); + } +} diff --git a/src/AngleSharp.Css/Parser/Micro/IdentParser.cs b/src/AngleSharp.Css/Parser/Micro/IdentParser.cs index aefed3bf..ca6e2543 100644 --- a/src/AngleSharp.Css/Parser/Micro/IdentParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/IdentParser.cs @@ -266,6 +266,21 @@ public static String ParseAnimatableIdent(this StringSource source) } source.BackTo(pos); + + // a custom property, animatable once registered, whose name keeps its case + if (test == null && source.Current == Symbols.Minus && source.Next() == Symbols.Minus) + { + var current = source.Next(); + + if (current.IsName() || source.IsValidEscape()) + { + var buffer = StringBuilderPool.Obtain().Append(Symbols.Minus).Append(Symbols.Minus); + return Rest(source, current, buffer); + } + + source.BackTo(pos); + } + return null; } diff --git a/src/AngleSharp.Css/Values/Primitives/CssAngleValue.cs b/src/AngleSharp.Css/Values/Primitives/CssAngleValue.cs index 4973a011..3045da9e 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssAngleValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssAngleValue.cs @@ -148,12 +148,12 @@ public String UnitString #region Methods + // the canonical unit of an angle is deg (CSS Values 4, 6.1), e.g. 0.5turn computes to 180deg ICssValue ICssValue.Compute(ICssComputeContext context) { - if (_unit != Unit.Rad) + if (_unit != Unit.Deg) { - var rad = ToRadian(); - return new CssAngleValue(rad, Unit.Rad); + return new CssAngleValue(ToDegree(), Unit.Deg); } return this; From 3af2a0809249b3635958923f2ba859069f546c9a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 17:27:32 +0100 Subject: [PATCH 15/19] Included image selection --- CHANGELOG.md | 3 +- .../Extensions/ImageSources.cs | 169 +++++++++ .../Extensions/ImageSourceExtensions.cs | 326 ++++++++++++++++++ src/AngleSharp.Css/ImageSourceSelection.cs | 36 ++ .../RenderTree/ElementRenderNode.cs | 13 + 5 files changed, 546 insertions(+), 1 deletion(-) create mode 100644 src/AngleSharp.Css.Tests/Extensions/ImageSources.cs create mode 100644 src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs create mode 100644 src/AngleSharp.Css/ImageSourceSelection.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d239c8c5..cd6572c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 1.6.0 -Released on tbd. +Released on Monday, November 23 2026. - Fixed a comment in a declaration's value with a quote in it (e.g. `/* shouldn't */`) starting a string, which swallowed the rest of the style sheet (Acid2) - Fixed an escaped `}` or `;` in a declaration's value (e.g. `error: \}`) ending the rule @@ -23,6 +23,7 @@ Released on tbd. - Added the `:modal` pseudo-class and the user agent styles of `dialog` - Added the `:fullscreen` pseudo-class, which a host forces (`SetPseudoClass`) on the element it shows fullscreen, and its user agent styles - Added `IAnimatedValueProvider` as the animation origin of the cascade +- Added `GetImageSource()` for `img` elements and `ImageSource` of render nodes # 1.5.0 diff --git a/src/AngleSharp.Css.Tests/Extensions/ImageSources.cs b/src/AngleSharp.Css.Tests/Extensions/ImageSources.cs new file mode 100644 index 00000000..9e69a251 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Extensions/ImageSources.cs @@ -0,0 +1,169 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Extensions +{ + using AngleSharp.Css.RenderTree; + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using AngleSharp.Media; + using NUnit.Framework; + using System; + using System.Linq; + + [TestFixture] + public class ImageSourcesTests + { + private static readonly String BaseUrl = "http://localhost/"; + + private static IHtmlImageElement Construct(String html, IRenderDevice device = null, IConfiguration config = null) + { + config ??= Configuration.Default; + var context = BrowsingContext.New(config.WithCss().WithOnly(device ?? new DefaultRenderDevice { ViewPortWidth = 1280, ViewPortHeight = 800 })); + var document = context.OpenAsync(m => m.Content(html).Address(BaseUrl)).Result; + return document.QuerySelector("img"); + } + + private static String Source(String html, IRenderDevice device = null, IConfiguration config = null) => + Construct(html, device, config).GetImageSource()?.Url.Href; + + [Test] + public void ImageWithSrcOnlyShowsItsSrc() + { + Assert.AreEqual(BaseUrl + "cat.jpg", Source("cat")); + } + + [Test] + public void ImageWithoutSourceShowsNothing() + { + Assert.IsNull(Source("cat")); + } + + [Test] + public void DensityCandidateOfOneIsTakenOnAStandardDevice() + { + Assert.AreEqual(BaseUrl + "cat.jpg", Source("")); + } + + [Test] + public void DensityCandidateOfTheDevicePixelRatioIsTaken() + { + var device = new DefaultRenderDevice { ViewPortWidth = 1280, Resolution = 192 }; + Assert.AreEqual(BaseUrl + "cat-2x.jpg", Source("", device)); + } + + [Test] + public void SrcIsTheCandidateOfDensityOne() + { + Assert.AreEqual(BaseUrl + "cat.jpg", Source("")); + } + + [Test] + public void WidthCandidateFittingTheViewportIsTakenWithoutSizes() + { + var html = ""; + Assert.AreEqual(BaseUrl + "cat-1280.jpg", Source(html)); + Assert.AreEqual(BaseUrl + "cat-320.jpg", Source(html, new DefaultRenderDevice { ViewPortWidth = 300 })); + } + + [TestCase("300px", "cat-400.jpg")] + [TestCase("50vw", "cat-800.jpg")] + [TestCase("calc(20vw - 56px)", "cat-200.jpg")] + [TestCase("(max-width: 600px) 480px, 150px", "cat-200.jpg")] + [TestCase("(min-width: 600px) 380px, 150px", "cat-400.jpg")] + [TestCase("auto, 300px", "cat-400.jpg")] + public void WidthCandidateFittingTheSizesIsTaken(String sizes, String expected) + { + var html = $""; + Assert.AreEqual(BaseUrl + expected, Source(html)); + } + + [Test] + public void DensestCandidateIsTakenIfNoneIsDenseEnough() + { + var device = new DefaultRenderDevice { ViewPortWidth = 1280, Resolution = 192 }; + Assert.AreEqual(BaseUrl + "cat-400.jpg", Source("", device)); + } + + [Test] + public void UrlOfADataCandidateKeepsItsCommas() + { + Assert.AreEqual("data:image/png;base64,AAAA", Source("")); + } + + [Test] + public void PictureSourceWhoseMediaMatchesIsTaken() + { + var html = @" + + + +"; + Assert.AreEqual(BaseUrl + "cat-vertical.jpg", Source(html)); + Assert.AreEqual(BaseUrl + "cat-horizontal.jpg", Source(html, new DefaultRenderDevice { ViewPortWidth = 800 })); + Assert.AreEqual(BaseUrl + "cat.jpg", Source(html, new DefaultRenderDevice { ViewPortWidth = 500 })); + } + + [Test] + public void PictureSourceOfACombinedSrcsetIsTaken() + { + var html = @" + + + +"; + Assert.AreEqual(BaseUrl + "person@desktop.png", Source(html)); + Assert.AreEqual(BaseUrl + "person@mobile-2x.png", Source(html, new DefaultRenderDevice { ViewPortWidth = 500, Resolution = 192 })); + } + + [Test] + public void PictureSourceOfAnUnsupportedTypeIsSkipped() + { + var html = @" + + + +"; + Assert.AreEqual(BaseUrl + "logo.png", Source(html)); + + Assert.AreEqual(BaseUrl + "logo.webp", Source(html, config: Configuration.Default.With(new WebpImages()))); + } + + [TestCase("", 1.0)] + [TestCase("", 1.0)] + [TestCase("", 2.0)] + [TestCase("", 1.5)] + [TestCase("", 400.0 / 300.0)] + [TestCase("", 0.5)] + public void SourceKnowsTheDensityOfItsPixels(String html, Double expected) + { + Assert.AreEqual(expected, Construct(html).GetImageSource().Density, 0.0001); + } + + [Test] + public void RenderTreePicksTheImageForTheViewport() + { + var device = new DefaultRenderDevice { ViewPortWidth = 1280, ViewPortHeight = 800 }; + var img = Construct("", device); + var window = img.Owner.DefaultView; + + Assert.AreEqual(BaseUrl + "cat-400.jpg", FindNode(window.Render(), img).ImageSource?.Url.Href); + + // a tree built after the viewport was resized picks again + device.ViewPortWidth = 3000; + Assert.AreEqual(BaseUrl + "cat-800.jpg", FindNode(window.Render(), img).ImageSource?.Url.Href); + Assert.IsNull(FindNode(window.Render(), img.Owner.Body).ImageSource); + } + + private sealed class WebpImages : IResourceService + { + public Boolean SupportsType(String mimeType) => mimeType == "image/webp"; + + public System.Threading.Tasks.Task CreateAsync(AngleSharp.Io.IResponse response, System.Threading.CancellationToken cancel) => + System.Threading.Tasks.Task.FromResult(null); + } + + private static ElementRenderNode FindNode(IRenderNode node, IElement element) => + node is ElementRenderNode e && ReferenceEquals(e.Ref, element) + ? e + : node.Children.Select(child => FindNode(child, element)).FirstOrDefault(found => found is not null); + } +} diff --git a/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs b/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs new file mode 100644 index 00000000..3d7c0298 --- /dev/null +++ b/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs @@ -0,0 +1,326 @@ +namespace AngleSharp.Dom +{ + using AngleSharp.Css; + using AngleSharp.Css.Converters; + using AngleSharp.Css.Dom; + using AngleSharp.Html.Dom; + using AngleSharp.Media; + using AngleSharp.Text; + using System; + using System.Collections.Generic; + + /// + /// Picks the source of an image for a render device (see "select an image source" in + /// HTML): the first source of the picture around it whose type is supported and whose + /// media matches, then the candidate of its srcset whose density fits the one of the + /// device best, with the size of the image given by the sizes attribute. + /// + public static class ImageSourceExtensions + { + /// + /// Gets the source of the image to show for the image element, picked for the render + /// device of its document (the default device, if there is none). + /// + /// The image element. + /// The source of the image, or null if it has none. + public static ImageSourceSelection? GetImageSource(this IHtmlImageElement img) + { + var device = img.Owner?.Context?.GetService() ?? new DefaultRenderDevice(); + return img.GetImageSource(device); + } + + /// + /// Gets the source of the image to show for the image element on the given device. + /// + /// The image element. + /// The device the image is shown on. + /// The source of the image, or null if it has none. + public static ImageSourceSelection? GetImageSource(this IHtmlImageElement img, IRenderDevice device) + { + if (img is null) + { + throw new ArgumentNullException(nameof(img)); + } + + if (device is null) + { + throw new ArgumentNullException(nameof(device)); + } + + var context = img.Owner?.Context; + var sources = img.GetSources(); + + while (sources.Count > 0) + { + var source = sources.Pop(); + var type = source.Type; + var media = source.Media; + + if ((String.IsNullOrEmpty(type) || context?.GetResourceService(type!) is not null) && + (String.IsNullOrEmpty(media) || Matches(context, media!, device)) && + SelectCandidate(source.SourceSet, source.Sizes, null, context, device) is { } selected) + { + return Resolve(img, selected.Key, selected.Value); + } + } + + var candidate = SelectCandidate(img.SourceSet, img.Sizes, img.GetAttribute("src"), context, device); + return candidate is { } found ? Resolve(img, found.Key, found.Value) : null; + } + + private static ImageSourceSelection? Resolve(IHtmlImageElement img, String source, Double density) + { + var url = img.BaseUrl is { } baseUrl ? new Url(baseUrl, source) : new Url(source); + return url.IsInvalid ? null : new ImageSourceSelection(url, density); + } + + private static KeyValuePair? SelectCandidate(String? srcset, String? sizes, String? src, IBrowsingContext? context, IRenderDevice device) + { + var candidates = new List>(); + var sourceSize = default(Double?); + var hasWidth = false; + var hasDensityOne = false; + + foreach (var (url, descriptors) in ParseSourceSet(srcset)) + { + var density = 1.0; + + foreach (var descriptor in descriptors) + { + var number = descriptor.Substring(0, descriptor.Length - 1); + + switch (descriptor[descriptor.Length - 1]) + { + case 'w': + sourceSize ??= GetSourceSize(sizes, context, device); + density = sourceSize > 0 ? number.ToDouble(0.0) / sourceSize.Value : 1.0; + hasWidth = true; + break; + case 'x': + density = number.ToDouble(1.0); + break; + } + } + + hasDensityOne |= density == 1.0; + candidates.Add(new KeyValuePair(url, density)); + } + + // the src is the candidate of density 1, unless the srcset has one (or sizes) + if (src is { Length: > 0 } && !hasWidth && !hasDensityOne) + { + candidates.Add(new KeyValuePair(src, 1.0)); + } + + if (candidates.Count == 0) + { + return null; + } + + // the least dense candidate as dense as the device's pixels, else the densest one + var ratio = device.Resolution > 0 ? device.Resolution / 96.0 : 1.0; + var best = default(KeyValuePair?); + var densest = candidates[0]; + + foreach (var candidate in candidates) + { + if (candidate.Value >= ratio && (best is null || candidate.Value < best.Value.Value)) + { + best = candidate; + } + + if (candidate.Value > densest.Value) + { + densest = candidate; + } + } + + return best ?? densest; + } + + // the width of the image in CSS pixels: the length of the first size whose media + // matches, else the width of the viewport (100vw) + private static Double GetSourceSize(String? sizes, IBrowsingContext? context, IRenderDevice device) + { + if (sizes is { Length: > 0 }) + { + foreach (var size in SplitTopLevel(sizes)) + { + var (media, length) = SplitSize(size.Trim()); + + if (length.Length > 0 && (media.Length == 0 || Matches(context, media, device)) && + ValueConverters.LengthConverter.Convert(length) is { } value && + value.AsPx(device, RenderMode.Horizontal) is var pixels && pixels > 0) + { + return pixels; + } + } + } + + return device.ViewPortWidth; + } + + private static Boolean Matches(IBrowsingContext? context, String media, IRenderDevice device) + { + // without a context (e.g. a document of its own) media are not looked at + if (context is null) + { + return true; + } + + var list = new MediaList(context); + list.SetMediaText(media, throwOnError: false); + return list.Validate(device); + } + + // the length of a size is its last component (a dimension or a function, e.g. calc), + // what is in front of it the media condition + private static (String Media, String Length) SplitSize(String size) + { + if (size.EndsWith(")", StringComparison.Ordinal)) + { + var depth = 0; + + for (var index = size.Length - 1; index >= 0; index--) + { + if (size[index] == ')') + { + depth++; + } + else if (size[index] == '(' && --depth == 0) + { + var start = index; + + while (start > 0 && (Char.IsLetterOrDigit(size[start - 1]) || size[start - 1] == '-')) + { + start--; + } + + // a parenthesized media condition alone has no length + return start == index ? (size, String.Empty) : (size.Substring(0, start).Trim(), size.Substring(start)); + } + } + + return (size, String.Empty); + } + + var space = size.LastIndexOfAny(new[] { ' ', '\t', '\n', '\r', '\f' }); + return space < 0 ? (String.Empty, size) : (size.Substring(0, space).Trim(), size.Substring(space + 1)); + } + + private static List SplitTopLevel(String sizes) + { + var parts = new List(); + var depth = 0; + var start = 0; + + for (var index = 0; index < sizes.Length; index++) + { + switch (sizes[index]) + { + case '(': + depth++; + break; + case ')': + depth--; + break; + case ',' when depth == 0: + parts.Add(sizes.Substring(start, index - start)); + start = index + 1; + break; + } + } + + parts.Add(sizes.Substring(start)); + return parts; + } + + // the candidates of a srcset (HTML 4.8.4.3.10): a URL (commas at its end separate it + // from the next one), then descriptors up to a comma outside of parentheses + private static IEnumerable<(String Url, List Descriptors)> ParseSourceSet(String? srcset) + { + if (srcset is null) + { + yield break; + } + + var position = 0; + + while (position < srcset.Length) + { + while (position < srcset.Length && (srcset[position].IsSpaceCharacter() || srcset[position] == ',')) + { + position++; + } + + var start = position; + + while (position < srcset.Length && !srcset[position].IsSpaceCharacter()) + { + position++; + } + + if (position == start) + { + yield break; + } + + var url = srcset.Substring(start, position - start); + var descriptors = new List(); + + if (url.EndsWith(",", StringComparison.Ordinal)) + { + url = url.TrimEnd(','); + } + else + { + var depth = 0; + var descriptor = new System.Text.StringBuilder(); + + for (; position < srcset.Length; position++) + { + var c = srcset[position]; + + if (c == '(') + { + depth++; + } + else if (c == ')') + { + depth--; + } + else if (depth == 0 && (c == ',' || c.IsSpaceCharacter())) + { + if (descriptor.Length > 0) + { + descriptors.Add(descriptor.ToString()); + descriptor.Clear(); + } + + if (c == ',') + { + position++; + break; + } + + continue; + } + + descriptor.Append(c); + } + + if (descriptor.Length > 0) + { + descriptors.Add(descriptor.ToString()); + } + } + + if (url.Length > 0) + { + descriptors.RemoveAll(static descriptor => descriptor.Length < 2); + yield return (url, descriptors); + } + } + } + } +} diff --git a/src/AngleSharp.Css/ImageSourceSelection.cs b/src/AngleSharp.Css/ImageSourceSelection.cs new file mode 100644 index 00000000..6c38f10d --- /dev/null +++ b/src/AngleSharp.Css/ImageSourceSelection.cs @@ -0,0 +1,36 @@ +namespace AngleSharp.Css +{ + using AngleSharp.Dom; + using System; + + /// + /// The source picked for an image element (see "select an image source" in HTML): the + /// URL of its image and the density of its pixels, by which the natural size of the + /// image is divided (e.g. an image of 800 pixels picked as 2x is 400 CSS pixels wide). + /// + public sealed class ImageSourceSelection + { + /// + /// Creates a new selection. + /// + /// The URL of the image. + /// The density of its pixels (image pixels per CSS pixel). + public ImageSourceSelection(Url url, Double density) + { + Url = url ?? throw new ArgumentNullException(nameof(url)); + Density = density > 0 && !Double.IsInfinity(density) ? density : 1.0; + } + + /// + /// Gets the URL of the image. + /// + public Url Url { get; } + + /// + /// Gets the density of the pixels of the image: 1 for a plain source or an `1x` + /// candidate, 2 for `2x`, and the width of a `w` candidate per CSS pixel of the + /// size the image is shown at (its sizes). + /// + public Double Density { get; } + } +} diff --git a/src/AngleSharp.Css/RenderTree/ElementRenderNode.cs b/src/AngleSharp.Css/RenderTree/ElementRenderNode.cs index 8e2e9600..78de25c1 100644 --- a/src/AngleSharp.Css/RenderTree/ElementRenderNode.cs +++ b/src/AngleSharp.Css/RenderTree/ElementRenderNode.cs @@ -2,6 +2,7 @@ namespace AngleSharp.Css.RenderTree { using AngleSharp.Css.Dom; using AngleSharp.Dom; + using AngleSharp.Html.Dom; using System; using System.Collections.Generic; using System.Linq; @@ -113,6 +114,18 @@ internal ElementRenderNode( /// public ICssStyleDeclaration ComputedStyle => _computedStyle; + /// + /// Gets the source of the image an img element shows: the candidate of its srcset (or + /// of the sources of the picture around it) picked for the render device of its + /// document, with the density its natural size is divided by + /// (see ). + /// It is picked when read, so a render tree built after the viewport changed (e.g. was + /// resized) picks again. Null for other elements, and for an img without a source. + /// + public ImageSourceSelection? ImageSource => _reference is IHtmlImageElement image && _reference is not IPseudoElement + ? image.GetImageSource((_context ?? _reference.Owner?.Context)?.GetService() ?? new DefaultRenderDevice()) + : null; + private Boolean InheritsFromParent => _inheritedStyle is null && Pending?.GetInheritedStyle is null && _parent is not null; /// From b35861044ecc148031849ea5a1cfd6316be1b90a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 17:44:15 +0100 Subject: [PATCH 16/19] Removed value tuple --- .../Extensions/ImageSourceExtensions.cs | 56 +++++++++++++++---- 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs b/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs index 3d7c0298..5bbbd124 100644 --- a/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs +++ b/src/AngleSharp.Css/Extensions/ImageSourceExtensions.cs @@ -81,11 +81,11 @@ public static class ImageSourceExtensions var hasWidth = false; var hasDensityOne = false; - foreach (var (url, descriptors) in ParseSourceSet(srcset)) + foreach (var entry in ParseSourceSet(srcset)) { var density = 1.0; - foreach (var descriptor in descriptors) + foreach (var descriptor in entry.Descriptors) { var number = descriptor.Substring(0, descriptor.Length - 1); @@ -103,7 +103,7 @@ public static class ImageSourceExtensions } hasDensityOne |= density == 1.0; - candidates.Add(new KeyValuePair(url, density)); + candidates.Add(new KeyValuePair(entry.Url, density)); } // the src is the candidate of density 1, unless the srcset has one (or sizes) @@ -146,7 +146,7 @@ private static Double GetSourceSize(String? sizes, IBrowsingContext? context, IR { foreach (var size in SplitTopLevel(sizes)) { - var (media, length) = SplitSize(size.Trim()); + SplitSize(size.Trim(), out var media, out var length); if (length.Length > 0 && (media.Length == 0 || Matches(context, media, device)) && ValueConverters.LengthConverter.Convert(length) is { } value && @@ -175,8 +175,11 @@ private static Boolean Matches(IBrowsingContext? context, String media, IRenderD // the length of a size is its last component (a dimension or a function, e.g. calc), // what is in front of it the media condition - private static (String Media, String Length) SplitSize(String size) + private static void SplitSize(String size, out String media, out String length) { + media = String.Empty; + length = String.Empty; + if (size.EndsWith(")", StringComparison.Ordinal)) { var depth = 0; @@ -197,15 +200,35 @@ private static (String Media, String Length) SplitSize(String size) } // a parenthesized media condition alone has no length - return start == index ? (size, String.Empty) : (size.Substring(0, start).Trim(), size.Substring(start)); + if (start == index) + { + media = size; + } + else + { + media = size.Substring(0, start).Trim(); + length = size.Substring(start); + } + + return; } } - return (size, String.Empty); + media = size; + return; } var space = size.LastIndexOfAny(new[] { ' ', '\t', '\n', '\r', '\f' }); - return space < 0 ? (String.Empty, size) : (size.Substring(0, space).Trim(), size.Substring(space + 1)); + + if (space < 0) + { + length = size; + } + else + { + media = size.Substring(0, space).Trim(); + length = size.Substring(space + 1); + } } private static List SplitTopLevel(String sizes) @@ -237,7 +260,7 @@ private static List SplitTopLevel(String sizes) // the candidates of a srcset (HTML 4.8.4.3.10): a URL (commas at its end separate it // from the next one), then descriptors up to a comma outside of parentheses - private static IEnumerable<(String Url, List Descriptors)> ParseSourceSet(String? srcset) + private static IEnumerable ParseSourceSet(String? srcset) { if (srcset is null) { @@ -318,9 +341,22 @@ private static List SplitTopLevel(String sizes) if (url.Length > 0) { descriptors.RemoveAll(static descriptor => descriptor.Length < 2); - yield return (url, descriptors); + yield return new SourceSetEntry(url, descriptors); } } } + + private sealed class SourceSetEntry + { + public SourceSetEntry(String url, List descriptors) + { + Url = url; + Descriptors = descriptors; + } + + public String Url { get; } + + public List Descriptors { get; } + } } } From 423747884a5370e19d2c6cf5360b0876d68715fa Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 24 Nov 2026 09:00:40 +0100 Subject: [PATCH 17/19] Prepare for 1.11 --- .github/workflows/ci.yml | 45 ++---------------- CHANGELOG.md | 3 +- docs/general/05-Extensibility.md | 12 +++++ src/AngleSharp.Css.Docs/docs.config.json | 28 ------------ src/AngleSharp.Css.Docs/package.json | 58 ------------------------ src/AngleSharp.Css.Docs/src/index.tsx | 7 --- src/AngleSharp.Css.Docs/tsconfig.json | 25 ---------- src/AngleSharp.Css/AngleSharp.Css.csproj | 16 ++++++- 8 files changed, 32 insertions(+), 162 deletions(-) delete mode 100644 src/AngleSharp.Css.Docs/docs.config.json delete mode 100644 src/AngleSharp.Css.Docs/package.json delete mode 100644 src/AngleSharp.Css.Docs/src/index.tsx delete mode 100644 src/AngleSharp.Css.Docs/tsconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e37164c1..ebceb353 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,45 +4,8 @@ on: [push, pull_request] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCS_PATH: ${{ secrets.DOCS_PATH }} - DOCS_BRANCH: ${{ secrets.DOCS_BRANCH }} jobs: - can_document: - runs-on: ubuntu-latest - outputs: - value: ${{ steps.check_job.outputs.value }} - steps: - - name: Checks whether documentation can be built - id: check_job - run: | - echo "value: ${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - echo "::set-output name=value::${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - - documentation: - needs: [can_document] - runs-on: ubuntu-latest - if: needs.can_document.outputs.value == 'true' - - steps: - - uses: actions/checkout@v5 - - - name: Use Node.js - uses: actions/setup-node@v5 - with: - node-version: "20.x" - registry-url: 'https://registry.npmjs.org' - - - name: Install Dependencies - run: | - cd $DOCS_PATH - npm install - - - name: Deploy Doclet - run: | - cd $DOCS_PATH - npx pilet publish --fresh --url https://feed.piral.cloud/api/v1/pilet/anglesharp --api-key ${{ secrets.PIRAL_FEED_KEY }} - linux: runs-on: ubuntu-latest @@ -56,7 +19,7 @@ jobs: 10.0.x - name: Build - run: ./build.sh -AngleSharpVersion 1.10.0 + run: ./build.sh -AngleSharpVersion 1.11.0 windows: runs-on: windows-latest @@ -87,9 +50,9 @@ jobs: NUGET_API_KEY: ${{ steps.nuget_login.outputs.NUGET_API_KEY }} run: | if ($env:GITHUB_REF -eq "refs/heads/main") { - .\build.ps1 -Target Publish -AngleSharpVersion 1.10.0 + .\build.ps1 -Target Publish -AngleSharpVersion 1.11.0 } elseif ($env:GITHUB_REF -eq "refs/heads/devel") { - .\build.ps1 -Target PrePublish -AngleSharpVersion 1.10.0 + .\build.ps1 -Target PrePublish -AngleSharpVersion 1.11.0 } else { - .\build.ps1 -AngleSharpVersion 1.10.0 + .\build.ps1 -AngleSharpVersion 1.11.0 } diff --git a/CHANGELOG.md b/CHANGELOG.md index cd6572c9..651c1e4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 1.6.0 -Released on Monday, November 23 2026. +Released on Tuesday, November 24 2026. - Fixed a comment in a declaration's value with a quote in it (e.g. `/* shouldn't */`) starting a string, which swallowed the rest of the style sheet (Acid2) - Fixed an escaped `}` or `;` in a declaration's value (e.g. `error: \}`) ending the rule @@ -24,6 +24,7 @@ Released on Monday, November 23 2026. - Added the `:fullscreen` pseudo-class, which a host forces (`SetPseudoClass`) on the element it shows fullscreen, and its user agent styles - Added `IAnimatedValueProvider` as the animation origin of the cascade - Added `GetImageSource()` for `img` elements and `ImageSource` of render nodes +- Added `CssDom.Register`, the DOM of this library declared for a scripting engine # 1.5.0 diff --git a/docs/general/05-Extensibility.md b/docs/general/05-Extensibility.md index bd0d64b5..d834f281 100644 --- a/docs/general/05-Extensibility.md +++ b/docs/general/05-Extensibility.md @@ -89,6 +89,18 @@ The dictionary is keyed by the media feature name and holds the keyword the feat The value is compared to the queried keyword case insensitively, so a keyword that is newer than this library works as well. Used without a value, e.g., `@media (prefers-reduced-motion)`, the feature evaluates in a boolean context, where `no-preference` (and `none` for `forced-colors`, `hover`, `any-hover`, `pointer` and `any-pointer`) is `false`. Without a preference `hover` and `pointer` keep answering as they did before, i.e., as a device with no input mechanism. +## Expose The CSSOM To Scripts Without Reflection + +A scripting engine such as AngleSharp.Js finds the CSSOM by reflecting over its DOM attributes by default. A trimmed or natively compiled (AoT) application can instead hand the engine the registration that is generated for this library at build time, `AngleSharp.Css.CssDom.Register` (a `DomRegistration` of AngleSharp). It declares the CSSOM types, the `CSS` namespace and the members the library adds to the DOM, such as `element.style` or `getComputedStyle`: + +```cs +var config = Configuration.Default + .WithCss() + .WithJs(CssDom.Register); +``` + +The registration describes the version of AngleSharp.Css in use, so it never has to be kept in sync by hand. Several libraries are combined with `DomRegistrations.Combine`. + ## Composition Pattern Start from the default registrations and replace only what you need: diff --git a/src/AngleSharp.Css.Docs/docs.config.json b/src/AngleSharp.Css.Docs/docs.config.json deleted file mode 100644 index f3174b55..00000000 --- a/src/AngleSharp.Css.Docs/docs.config.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "AngleSharp.Css", - "author": "Florian Rappl", - "branch": "devel", - "repositoryUrl": "https://github.com/AngleSharp/AngleSharp.Css", - "rootDir": "../../", - "outputDir": "./dist", - "sitemap": { - "general": { - "sections": [ - { - "generator": "markdown", - "segment": "css", - "dir": "general" - } - ] - }, - "docs": { - "sections": [ - { - "generator": "markdown", - "segment": "css", - "dir": "tutorials" - } - ] - } - } -} \ No newline at end of file diff --git a/src/AngleSharp.Css.Docs/package.json b/src/AngleSharp.Css.Docs/package.json deleted file mode 100644 index 5bb81e44..00000000 --- a/src/AngleSharp.Css.Docs/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@anglesharp/css", - "version": "1.6.0", - "preview": true, - "description": "The doclet for the AngleSharp.Css documentation.", - "keywords": [ - "pilet" - ], - "dependencies": {}, - "devDependencies": { - "@anglesharp/website": "1.0.0", - "@types/react": "^17.0.5", - "@types/react-dom": "^17.0.5", - "@types/react-router": "latest", - "@types/react-router-dom": "^5.1.7", - "@types/node": "^15.3.0", - "typescript": "^4.2.4", - "@dbeining/react-atom": "4.1.19", - "@libre/atom": "1.3.3", - "history": "4.10.1", - "react": "17.0.2", - "react-dom": "17.0.2", - "react-router": "5.2.0", - "react-router-dom": "5.2.0", - "tslib": "2.2.0", - "path-to-regexp": "1.8.0", - "piral-cli": "^0.13.3-pre.2480", - "piral-cli-parcel": "^0.13.3-pre.2480" - }, - "peerDependencies": { - "@dbeining/react-atom": "*", - "@libre/atom": "*", - "history": "*", - "react": "*", - "react-dom": "*", - "react-router": "*", - "react-router-dom": "*", - "tslib": "*", - "path-to-regexp": "*", - "@anglesharp/website": "*" - }, - "scripts": { - "start": "pilet debug", - "build": "pilet build", - "upgrade": "pilet upgrade" - }, - "main": "dist/index.js", - "files": [ - "dist" - ], - "piral": { - "comment": "Keep this section to use the Piral CLI.", - "name": "@anglesharp/website" - }, - "peerModules": [ - "piral-docs-tools/components" - ] -} diff --git a/src/AngleSharp.Css.Docs/src/index.tsx b/src/AngleSharp.Css.Docs/src/index.tsx deleted file mode 100644 index dc50b37f..00000000 --- a/src/AngleSharp.Css.Docs/src/index.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { PiletApi } from 'piral-docs-tools'; - -const createDoclet = require('piral-docs-tools/doclet'); - -export function setup(api: PiletApi) { - createDoclet(api); -} diff --git a/src/AngleSharp.Css.Docs/tsconfig.json b/src/AngleSharp.Css.Docs/tsconfig.json deleted file mode 100644 index 610060fb..00000000 --- a/src/AngleSharp.Css.Docs/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "declaration": true, - "noImplicitAny": false, - "removeComments": false, - "noLib": false, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es6", - "sourceMap": true, - "outDir": "./dist", - "skipLibCheck": true, - "lib": ["dom", "es2018"], - "moduleResolution": "node", - "module": "esnext", - "jsx": "react", - "importHelpers": true - }, - "include": [ - "./src" - ], - "exclude": [ - "node_modules" - ] -} diff --git a/src/AngleSharp.Css/AngleSharp.Css.csproj b/src/AngleSharp.Css/AngleSharp.Css.csproj index 3a93345c..15c19d95 100644 --- a/src/AngleSharp.Css/AngleSharp.Css.csproj +++ b/src/AngleSharp.Css/AngleSharp.Css.csproj @@ -40,7 +40,7 @@ true true snupkg - 1.10.0 + 1.11.0 @@ -48,10 +48,18 @@ - + + + + + + @@ -62,6 +70,10 @@ <_Parameter1>false + + + <_Parameter1>AngleSharp.Css.CssDom + From 9e54fffc2a5e63a93fdac242d391a09c3da6acfe Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 24 Nov 2026 10:41:50 +0100 Subject: [PATCH 18/19] Updated --- src/AngleSharp.Css/AngleSharp.Css.csproj | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/AngleSharp.Css/AngleSharp.Css.csproj b/src/AngleSharp.Css/AngleSharp.Css.csproj index 15c19d95..690d5564 100644 --- a/src/AngleSharp.Css/AngleSharp.Css.csproj +++ b/src/AngleSharp.Css/AngleSharp.Css.csproj @@ -48,18 +48,10 @@ + - - - - - - From 859f5b254e46961272f9ba24ed64ff44e601ed28 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 24 Nov 2026 12:05:02 +0100 Subject: [PATCH 19/19] Updated for AngleSharp 1.11 --- AGENTS.md | 4 ++-- CHANGELOG.md | 1 + src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj | 2 +- src/AngleSharp.Css.Tests/Styling/ContextLoading.cs | 7 +++---- .../AngleSharp.Performance.Css.csproj | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 29170523..639459d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ dotnet run --project src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.c Notes: -- CI invokes `./build.sh -AngleSharpVersion 1.10.0` on Linux and `./build.ps1` on Windows. +- CI invokes `./build.sh -AngleSharpVersion 1.11.0` on Linux and `./build.ps1` on Windows. - Treat warnings as errors is enabled in `src/Directory.Build.props`. ## 3) Build and target framework facts @@ -43,7 +43,7 @@ Notes: - Library project: `src/AngleSharp.Css/AngleSharp.Css.csproj` - Targets: `netstandard2.0;net8.0;net10.0` - Additional Windows-only targets: `net462;net472` - - The AngleSharp dependency defaults to version `1.10.0` and allows versions below `2.0.0`. + - The AngleSharp dependency defaults to version `1.11.0` and allows versions below `2.0.0`. - The `net8.0` and `net10.0` targets set `IsAotCompatible`, so trim and AOT analyzer warnings fail the build. - Test project: `src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj` - Targets: `net8.0` diff --git a/CHANGELOG.md b/CHANGELOG.md index 651c1e4f..74fe819a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ Released on Tuesday, November 24 2026. - Fixed a closed `details` showing more than its `summary` - Fixed `transition-property` not accepting custom properties - Fixed angles being computed in `rad` instead of the canonical `deg` +- Updated minimum version of AngleSharp to 1.11.0 - Added `::part()` styling the parts of shadow trees - Added the `:modal` pseudo-class and the user agent styles of `dialog` - Added the `:fullscreen` pseudo-class, which a host forces (`SetPseudoClass`) on the element it shows fullscreen, and its user agent styles diff --git a/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj b/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj index 4bf64b57..eee8460d 100644 --- a/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj +++ b/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs b/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs index 381e2258..ceac415c 100644 --- a/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs +++ b/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs @@ -77,7 +77,7 @@ public async Task GetDownloadsOfExampleDocumentWithCssAndJsShouldYieldAllResourc var document = await BrowsingContext.New(config).OpenAsync(res => res.Content(content).Address("http://localhost")); var downloads = document.GetDownloads().ToArray(); - Assert.AreEqual(6, downloads.Length); + Assert.AreEqual(5, downloads.Length); foreach (var download in downloads) { @@ -88,9 +88,8 @@ public async Task GetDownloadsOfExampleDocumentWithCssAndJsShouldYieldAllResourc Assert.AreEqual(document.QuerySelectorAll("link").Skip(0).First(), downloads[0].Source); Assert.AreEqual(document.QuerySelectorAll("link").Skip(1).First(), downloads[1].Source); Assert.AreEqual(document.QuerySelectorAll("link").Skip(2).First(), downloads[2].Source); - Assert.AreEqual(document.QuerySelector("img"), downloads[3].Source); - Assert.AreEqual(document.QuerySelector("iframe"), downloads[4].Source); - Assert.AreEqual(document.QuerySelectorAll("script").Skip(1).First(), downloads[5].Source); + Assert.AreEqual(document.QuerySelector("iframe"), downloads[3].Source); + Assert.AreEqual(document.QuerySelectorAll("script").Skip(1).First(), downloads[4].Source); } } } diff --git a/src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.csproj b/src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.csproj index 2dfa0b18..5b540a90 100644 --- a/src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.csproj +++ b/src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.csproj @@ -3,7 +3,7 @@ net472;net10.0 Exe false - 1.10.0 + 1.11.0