From 4da1add9a02d865c222fe69a09c246c23fffccc4 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:19:47 +0100 Subject: [PATCH 1/8] Limit how deep values and conditions nest A value or condition nesting parentheses deeply ended the process with a stack overflow, which no caller can catch: the parser recurses once per level of parentheses and math functions in values (calc(), min(), max(), clamp()) and of parentheses in @media and @supports conditions, also when a value is set through the CSSOM. On a 256 KB thread stack, about 430 parentheses in calc() were enough (.NET 8, before the JIT optimizes); on a 1 MB stack about 1,900. - Add CssParserOptions.MaxValueNestingDepth (default 64). A value or condition nested deeper is invalid. The value parsers run inside the converters, which do not see the options, so a parser makes its limit current while it builds (ValueNesting); values set through the CSSOM without a parser get the default - Add tests at depths that crashed before and at the limit, parsing on a 256 KB thread stack, and for the option per parser, per browsing context and its scope - Add calc() and @supports shapes to the nesting benchmark This is a mitigation, not a fix: parsing still recurses once per level, and only the limit stops it. Raising the limit brings the crash back. --- AGENTS.md | 2 +- .../Parsing/DeepNesting.cs | 130 ++++++++++++++++++ src/AngleSharp.Css/Parser/CssParser.cs | 30 +++- src/AngleSharp.Css/Parser/CssParserOptions.cs | 27 ++++ src/AngleSharp.Css/Parser/Micro/CalcParser.cs | 50 +++++-- .../Parser/Micro/ConditionParser.cs | 27 ++-- .../Parser/Micro/MediumParser.cs | 41 +++--- src/AngleSharp.Css/Parser/ValueNesting.cs | 40 ++++++ .../DeepNestingBenchmarks.cs | 12 +- 9 files changed, 301 insertions(+), 58 deletions(-) create mode 100644 src/AngleSharp.Css/Parser/ValueNesting.cs diff --git a/AGENTS.md b/AGENTS.md index c14cc5d5..22bd99c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,7 +141,7 @@ dotnet test src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj - Existing code mixes nullable contexts (`#nullable enable` and `#nullable disable`); do not normalize unrelated files. - Stay trim- and AOT-clean. The library sets `IsAotCompatible` on its .NETCoreApp targets, so the trim and AOT analyzers run on every build and a warning breaks it. Reflection over a runtime type (`GetType().GetProperties()`, `Assembly.GetTypes()`) is what they reject: read members off an annotated generic parameter instead (`Css` via AngleSharp's `ToDictionary`), or use a fixed table. The analyzers only see the library itself; publishing a small `PublishAot` console app against it is the end-to-end check. - In `src/AngleSharp.Css/ValueConverters.cs`, avoid static field initializers that reference converters declared later in the same file. Forward references can capture `null` during type initialization and only fail at runtime. -- Untrusted input can nest arbitrarily deep, and a stack overflow ends the process. `CssBuilder` parses nested blocks recursively and carries a depth that stops at `CssParserOptions.MaxNestingDepth`; a new recursive parsing path needs the same. The limit is a mitigation, not a fix: the recursion is still there, so a raised limit can still overflow the stack. `src/AngleSharp.Css.Tests/Parsing/DeepNesting.cs` holds the tests, which parse on a 256 KB stack. +- Untrusted input can nest arbitrarily deep, and a stack overflow ends the process. `CssBuilder` parses nested blocks recursively and carries a depth that stops at `CssParserOptions.MaxNestingDepth`, and the value and condition parsers (`CalcParser`, `ConditionParser`, `MediumParser`) stop at `CssParserOptions.MaxValueNestingDepth`, made current by `ValueNesting` while a parser builds; a new recursive parsing path needs the same. The limits are a mitigation, not a fix: the recursion is still there, so a raised limit can still overflow the stack. `src/AngleSharp.Css.Tests/Parsing/DeepNesting.cs` holds the tests, which parse on a 256 KB stack. ## 8) Documentation and onboarding references diff --git a/src/AngleSharp.Css.Tests/Parsing/DeepNesting.cs b/src/AngleSharp.Css.Tests/Parsing/DeepNesting.cs index 6c412b9e..2aa907e7 100644 --- a/src/AngleSharp.Css.Tests/Parsing/DeepNesting.cs +++ b/src/AngleSharp.Css.Tests/Parsing/DeepNesting.cs @@ -4,6 +4,8 @@ namespace AngleSharp.Css.Tests.Parsing using AngleSharp.Css.Dom; using AngleSharp.Css.Dom.Events; using AngleSharp.Css.Parser; + using AngleSharp.Dom; + using AngleSharp.Html.Parser; using NUnit.Framework; using System; using System.Collections.Generic; @@ -168,5 +170,133 @@ public void NestedStyleRuleBeyondTheLimitIsDroppedAndTheDeclarationsContinue() Assert.AreEqual("rgba(0, 128, 0, 1)", b.Style.GetPropertyValue("color")); Assert.AreEqual(0, b.Rules.Length); } + + [TestCase("calc(", "(1px + ", ")", ")")] + [TestCase("", "calc(", ")", "")] + [TestCase("", "min(1px, ", ")", "")] + public void DeeplyNestedMathIsInvalid(String prefix, String open, String close, String suffix) + { + var value = prefix + Repeat(open, Deep) + "1px" + Repeat(close, Deep) + suffix; + var sheet = ParseOnSmallStack("a{width:" + value + "}"); + Assert.AreEqual("", ((ICssStyleRule)sheet.Rules[0]).Style.GetPropertyValue("width")); + } + + [Test] + public void MathNestedUpToTheLimitIsValid() + { + // calc() itself is the first level + var limit = CssParserOptions.DefaultMaxValueNestingDepth; + var style = OnSmallStack(() => ParseDeclarations("width: " + NestedCalc(limit - 1))); + Assert.AreNotEqual("", style.GetPropertyValue("width")); + style = OnSmallStack(() => ParseDeclarations("width: " + NestedCalc(limit))); + Assert.AreEqual("", style.GetPropertyValue("width")); + } + + [Test] + public void DeeplyNestedMathSetThroughTheCssomIsInvalid() + { + var document = ParseDocument("
"); + var style = document.QuerySelector("div").GetStyle(); + OnSmallStack(() => { style.SetProperty("width", "calc(" + Repeat("(1px + ", Deep) + "1px" + Repeat(")", Deep) + ")"); return style; }); + Assert.AreEqual("", style.GetPropertyValue("width")); + } + + [Test] + public void DeeplyNestedSupportsConditionIsInvalid() + { + var sheet = ParseOnSmallStack("@supports " + Repeat("(", Deep) + "display: block" + Repeat(")", Deep) + " { a { color: red } } b { color: blue }"); + Assert.AreEqual(1, sheet.Rules.Length); + Assert.AreEqual("b", ((ICssStyleRule)sheet.Rules[0]).SelectorText); + } + + [Test] + public void SupportsConditionNestedUpToTheLimitIsValid() + { + var limit = CssParserOptions.DefaultMaxValueNestingDepth; + var valid = ParseOnSmallStack("@supports " + Repeat("(", limit) + "display: block" + Repeat(")", limit) + " { a { color: red } }"); + var invalid = ParseOnSmallStack("@supports " + Repeat("(", limit + 1) + "display: block" + Repeat(")", limit + 1) + " { a { color: red } }"); + Assert.AreEqual(1, valid.Rules.Length); + Assert.AreEqual(0, invalid.Rules.Length); + } + + [Test] + public void DeeplyNestedMediaConditionDoesNotOverflow() + { + var sheet = ParseOnSmallStack("@media " + Repeat("(", Deep) + "min-width: 1px" + Repeat(")", Deep) + " { a { color: red } } b { color: blue }"); + Assert.AreEqual("b", ((ICssStyleRule)sheet.Rules[sheet.Rules.Length - 1]).SelectorText); + } + + [Test] + public void ModeratelyNestedMediaConditionIsStillValid() + { + var sheet = ParseStyleSheet("@media " + Repeat("(", 10) + "min-width: 1px" + Repeat(")", 10) + " { a { color: red } }"); + Assert.AreEqual("(min-width: 1px)", ((ICssMediaRule)sheet.Rules[0]).ConditionText); + } + + private static String NestedCalc(Int32 parentheses) => + "calc(" + Repeat("(", parentheses) + "1px" + Repeat(")", parentheses) + ")"; + + private static String WidthOf(ICssStyleSheet sheet) => + ((ICssStyleRule)sheet.Rules[0]).Style.GetPropertyValue("width"); + + [Test] + public void ValueNestingLimitIsConfigurable() + { + // calc() itself is the first level + var options = new CssParserOptions { MaxValueNestingDepth = 3 }; + Assert.AreNotEqual("", WidthOf(ParseStyleSheet("a{width:" + NestedCalc(2) + "}", options))); + Assert.AreEqual("", WidthOf(ParseStyleSheet("a{width:" + NestedCalc(3) + "}", options))); + } + + [Test] + public void ValueNestingLimitAboveTheDefaultIsHonored() + { + var options = new CssParserOptions { MaxValueNestingDepth = 100 }; + Assert.AreEqual("", WidthOf(ParseStyleSheet("a{width:" + NestedCalc(99) + "}"))); + Assert.AreNotEqual("", WidthOf(ParseStyleSheet("a{width:" + NestedCalc(99) + "}", options))); + } + + [Test] + public void ValueNestingLimitAppliesToSupportsConditions() + { + var options = new CssParserOptions { MaxValueNestingDepth = 3 }; + var valid = ParseStyleSheet("@supports " + Repeat("(", 3) + "display: block" + Repeat(")", 3) + " { a { color: red } }", options); + var invalid = ParseStyleSheet("@supports " + Repeat("(", 4) + "display: block" + Repeat(")", 4) + " { a { color: red } }", options); + Assert.AreEqual(1, valid.Rules.Length); + Assert.AreEqual(0, invalid.Rules.Length); + } + + [Test] + public void ValueNestingLimitOfTheBrowsingContextAppliesToItsStyleSheets() + { + var config = Configuration.Default.WithCss(new CssParserOptions { MaxValueNestingDepth = 3 }); + var document = BrowsingContext.New(config).GetService().ParseDocument(""); + Assert.AreEqual("", WidthOf((ICssStyleSheet)document.StyleSheets[0])); + } + + [Test] + public void ValueNestingLimitDoesNotOutliveItsParser() + { + ParseStyleSheet("a{width:" + NestedCalc(3) + "}", new CssParserOptions { MaxValueNestingDepth = 3 }); + // a value set without a parser right after, on the same thread, gets the default again + var style = ParseDocument("
").QuerySelector("div").GetStyle(); + style.SetProperty("width", NestedCalc(10)); + Assert.AreNotEqual("", style.GetPropertyValue("width")); + } + + [Test] + public void ValuesSetThroughTheCssomUseTheDefaultLimit() + { + var config = Configuration.Default.WithCss(new CssParserOptions { MaxValueNestingDepth = 3 }); + var document = BrowsingContext.New(config).GetService().ParseDocument("
"); + var divs = document.QuerySelectorAll("div"); + // an invalid value is ignored by SetProperty, so each case gets its own element + var accepted = divs[0].GetStyle(); + accepted.SetProperty("width", NestedCalc(10)); + Assert.AreNotEqual("", accepted.GetPropertyValue("width")); + var rejected = divs[1].GetStyle(); + rejected.SetProperty("width", NestedCalc(CssParserOptions.DefaultMaxValueNestingDepth)); + Assert.AreEqual("", rejected.GetPropertyValue("width")); + } } } diff --git a/src/AngleSharp.Css/Parser/CssParser.cs b/src/AngleSharp.Css/Parser/CssParser.cs index eb1dd81b..d2ebee8b 100644 --- a/src/AngleSharp.Css/Parser/CssParser.cs +++ b/src/AngleSharp.Css/Parser/CssParser.cs @@ -206,7 +206,12 @@ internal ICssStyleSheet ParseStylesheet(TextSource source) var tokenizer = CreateTokenizer(source); var builder = new CssBuilder(_options, tokenizer, _context); InvokeEventListener(new CssParseEvent(sheet, completed: false)); - builder.CreateRules(sheet); + + using (ValueNesting.Use(_options)) + { + builder.CreateRules(sheet); + } + InvokeEventListener(new CssParseEvent(sheet, completed: true)); return sheet; } @@ -229,7 +234,12 @@ internal async Task ParseStylesheetAsync(CssStyleSheet sheet, Ca var tasks = new List(); InvokeEventListener(new CssParseEvent(sheet, completed: false)); - builder.CreateRules(sheet); + + using (ValueNesting.Use(_options)) + { + builder.CreateRules(sheet); + } + InvokeEventListener(new CssParseEvent(sheet, completed: true)); foreach (var rule in sheet.Rules) @@ -290,7 +300,13 @@ private async Task ParseChildStyleSheetAsync(IDownload download, var tokenizer = CreateTokenizer(source); var token = tokenizer.Get(); var builder = new CssBuilder(_options, tokenizer, _context); - var rule = create.Invoke(builder, token); + T? rule; + + using (ValueNesting.Use(_options)) + { + rule = create.Invoke(builder, token); + } + return tokenizer.Get().Type == CssTokenType.EndOfFile ? rule : default; } @@ -299,7 +315,13 @@ private async Task ParseChildStyleSheetAsync(IDownload download, var tokenizer = CreateTokenizer(source); var token = tokenizer.Get(); var builder = new CssBuilder(_options, tokenizer, _context); - var pair = create.Invoke(builder, token); + Tuple pair; + + using (ValueNesting.Use(_options)) + { + pair = create.Invoke(builder, token); + } + return pair.Item2.Type == CssTokenType.EndOfFile ? pair.Item1 : default; } diff --git a/src/AngleSharp.Css/Parser/CssParserOptions.cs b/src/AngleSharp.Css/Parser/CssParserOptions.cs index d81f3ff5..851fe855 100644 --- a/src/AngleSharp.Css/Parser/CssParserOptions.cs +++ b/src/AngleSharp.Css/Parser/CssParserOptions.cs @@ -13,6 +13,33 @@ public struct CssParserOptions /// public const Int32 DefaultMaxNestingDepth = 64; + /// + /// The nesting depth allowed in values and conditions when + /// is not set: 64. + /// + public const Int32 DefaultMaxValueNestingDepth = 64; + + /// + /// Gets or sets how deep the parentheses and math functions of a value (calc(), min(), + /// max(), clamp()) and the parentheses of a @media or @supports condition may nest. A + /// value or condition nested deeper is invalid. It applies to what this parser parses; + /// values set through the CSSOM without a parser (e.g. SetProperty) use + /// . 0, the default, uses + /// . + /// + /// This is a mitigation, not a fix: values and conditions are still parsed recursively, + /// once per level, and only this limit keeps a hostile style sheet from overflowing the + /// stack, which ends the process. Raising it brings that crash back: without a limit, + /// about 1,900 parentheses in calc() overflow a 1 MB stack and about 430 a 256 KB thread + /// stack (.NET 8, before the JIT optimizes the code). + /// + /// + public Int32 MaxValueNestingDepth + { + get; + set; + } + /// /// Gets or sets the number of blocks a rule may be nested in, counting grouping rules /// such as @media, @supports, @layer or @container, and style rules holding nested diff --git a/src/AngleSharp.Css/Parser/Micro/CalcParser.cs b/src/AngleSharp.Css/Parser/Micro/CalcParser.cs index 208236b3..a59c7582 100644 --- a/src/AngleSharp.Css/Parser/Micro/CalcParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/CalcParser.cs @@ -22,7 +22,7 @@ public static CssCalcValue ParseCalc(this StringSource source) if (source.IsFunction(FunctionNames.Calc)) { - var expression = source.ParseExpression(); + var expression = source.ParseExpression(1); if (expression != null) { @@ -37,8 +37,18 @@ public static CssCalcValue ParseCalc(this StringSource source) /// /// Parses a comparison function value (min, max, or clamp), if any. /// - internal static ICssValue ParseMath(this StringSource source) + internal static ICssValue ParseMath(this StringSource source) => source.ParseMath(0); + + // The depth counts the enclosing parentheses and math functions. Each level recurses, so + // beyond the limit (CssParserOptions.MaxValueNestingDepth, see ValueNesting) the value + // is invalid rather than a risk to the stack. + private static ICssValue ParseMath(this StringSource source, Int32 depth) { + if (depth >= ValueNesting.Limit) + { + return null; + } + var pos = source.Index; var name = source.IsFunction(FunctionNames.Min) ? FunctionNames.Min : source.IsFunction(FunctionNames.Max) ? FunctionNames.Max : @@ -51,7 +61,7 @@ internal static ICssValue ParseMath(this StringSource source) while (true) { - var argument = source.ParseAddExpression(); + var argument = source.ParseAddExpression(depth + 1); if (argument == null) { @@ -81,9 +91,9 @@ internal static ICssValue ParseMath(this StringSource source) return null; } - private static ICssValue ParseExpression(this StringSource source) + private static ICssValue ParseExpression(this StringSource source, Int32 depth) { - var expression = source.ParseAddExpression(); + var expression = source.ParseAddExpression(depth); if (expression != null && source.Current == Symbols.RoundBracketClose) { @@ -94,15 +104,15 @@ private static ICssValue ParseExpression(this StringSource source) return null; } - private static ICssValue ParseAddExpression(this StringSource source) + private static ICssValue ParseAddExpression(this StringSource source, Int32 depth) { - var left = ParseMulExpression(source); + var left = ParseMulExpression(source, depth); while (left != null && (source.Current == Symbols.Plus || source.Current == Symbols.Minus)) { var add = source.Current == Symbols.Plus; source.SkipCurrentAndSpaces(); - var right = ParseMulExpression(source); + var right = ParseMulExpression(source, depth); if (right == null) { @@ -117,15 +127,15 @@ private static ICssValue ParseAddExpression(this StringSource source) return left; } - private static ICssValue ParseMulExpression(this StringSource source) + private static ICssValue ParseMulExpression(this StringSource source, Int32 depth) { - var left = ParseBracketExpression(source); + var left = ParseBracketExpression(source, depth); while (left != null && (source.Current == Symbols.Asterisk || source.Current == Symbols.Solidus)) { var mul = source.Current == Symbols.Asterisk; source.SkipCurrentAndSpaces(); - var right = ParseBracketExpression(source); + var right = ParseBracketExpression(source, depth); if (right == null) { @@ -140,21 +150,31 @@ private static ICssValue ParseMulExpression(this StringSource source) return left; } - private static ICssValue ParseBracketExpression(this StringSource source) + private static ICssValue ParseBracketExpression(this StringSource source, Int32 depth) { if (source.Current == Symbols.RoundBracketOpen) { + if (depth >= ValueNesting.Limit) + { + return null; + } + source.SkipCurrentAndSpaces(); - var content = source.ParseExpression(); + var content = source.ParseExpression(depth + 1); return new CssCalcBracketExpression(content); } else if (source.IsFunction(FunctionNames.Calc)) { - var content = source.ParseExpression(); + if (depth >= ValueNesting.Limit) + { + return null; + } + + var content = source.ParseExpression(depth + 1); return new CssCalcBracketExpression(content); } - return source.ParseMath() ?? source.ParseAtomicExpression(); + return source.ParseMath(depth) ?? source.ParseAtomicExpression(); } /// diff --git a/src/AngleSharp.Css/Parser/Micro/ConditionParser.cs b/src/AngleSharp.Css/Parser/Micro/ConditionParser.cs index 55561c83..bbcd23bb 100644 --- a/src/AngleSharp.Css/Parser/Micro/ConditionParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/ConditionParser.cs @@ -23,12 +23,12 @@ internal static IConditionFunction Parse(String str, IBrowsingContext context) /// Parse a CSS condition function using the current browsing context. /// public static IConditionFunction ParseConditionFunction(this StringSource source, IBrowsingContext context) => - source.Condition(context); + source.Condition(context, 0); - private static IConditionFunction Condition(this StringSource source, IBrowsingContext context) => - source.Negation(context) ?? source.ConjunctionOrDisjunction(context); + private static IConditionFunction Condition(this StringSource source, IBrowsingContext context, Int32 depth) => + source.Negation(context, depth) ?? source.ConjunctionOrDisjunction(context, depth); - private static IConditionFunction Negation(this StringSource source, IBrowsingContext context) + private static IConditionFunction Negation(this StringSource source, IBrowsingContext context, Int32 depth) { var pos = source.Index; var ident = source.ParseIdent(); @@ -36,7 +36,7 @@ private static IConditionFunction Negation(this StringSource source, IBrowsingCo if (ident != null && ident.Isi(CssKeywords.Not)) { source.SkipSpacesAndComments(); - var condition = source.Group(context); + var condition = source.Group(context, depth); if (condition != null) { @@ -48,9 +48,9 @@ private static IConditionFunction Negation(this StringSource source, IBrowsingCo return null; } - private static IConditionFunction ConjunctionOrDisjunction(this StringSource source, IBrowsingContext context) + private static IConditionFunction ConjunctionOrDisjunction(this StringSource source, IBrowsingContext context, Int32 depth) { - var condition = source.Group(context); + var condition = source.Group(context, depth); source.SkipSpacesAndComments(); var pos = source.Index; var ident = source.ParseIdent(); @@ -62,7 +62,7 @@ private static IConditionFunction ConjunctionOrDisjunction(this StringSource sou if (isAnd || isOr) { - var conditions = source.Scan(ident, condition, context); + var conditions = source.Scan(ident, condition, context, depth); if (isAnd) { @@ -79,16 +79,17 @@ private static IConditionFunction ConjunctionOrDisjunction(this StringSource sou return condition; } - private static IConditionFunction Group(this StringSource source, IBrowsingContext context) + private static IConditionFunction Group(this StringSource source, IBrowsingContext context, Int32 depth) { - if (source.Current == Symbols.RoundBracketOpen) + // each parenthesis recurses, so beyond the limit the condition is invalid + if (source.Current == Symbols.RoundBracketOpen && depth < ValueNesting.Limit) { var current = source.SkipCurrentAndSpaces(); var condition = default(IConditionFunction); if (current != Symbols.RoundBracketClose) { - condition = source.Condition(context) ?? source.Declaration(context); + condition = source.Condition(context, depth + 1) ?? source.Declaration(context); current = source.SkipSpacesAndComments(); if (condition == null) @@ -123,7 +124,7 @@ private static IConditionFunction Declaration(this StringSource source, IBrowsin return null; } - private static IEnumerable Scan(this StringSource source, String keyword, IConditionFunction condition, IBrowsingContext context) + private static IEnumerable Scan(this StringSource source, String keyword, IConditionFunction condition, IBrowsingContext context, Int32 depth) { var conditions = new List(); var ident = String.Empty; @@ -132,7 +133,7 @@ private static IEnumerable Scan(this StringSource source, St do { source.SkipSpacesAndComments(); - condition = source.Group(context); + condition = source.Group(context, depth); if (condition == null) break; diff --git a/src/AngleSharp.Css/Parser/Micro/MediumParser.cs b/src/AngleSharp.Css/Parser/Micro/MediumParser.cs index 939b25fb..ed62d3fb 100644 --- a/src/AngleSharp.Css/Parser/Micro/MediumParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/MediumParser.cs @@ -29,7 +29,7 @@ public static CssMedium ParseMedium(this StringSource source, IFeatureValidatorF // = | source.SkipSpacesAndComments(); - var medium = source.ParseMediaCondition() ?? source.ParseMediaType(); + var medium = source.ParseMediaCondition(0) ?? source.ParseMediaType(); if (medium is not null) { @@ -55,21 +55,21 @@ private static void AssociateValidators(CssMedium medium, IFeatureValidatorFacto } } - private static CssMedium ParseMediaCondition(this StringSource source) + private static CssMedium ParseMediaCondition(this StringSource source, Int32 depth) { // Syntax: // = | [ * | * ] - var medium = source.ParseMediaNot(); + var medium = source.ParseMediaNot(depth); if (medium is null) { - medium = source.ParseMediaInParens(); + medium = source.ParseMediaInParens(depth); if (medium is not null) { source.SkipSpacesAndComments(); - var other = source.ParseMediaConnectorMultiple(CssKeywords.And) ?? source.ParseMediaConnectorMultiple(CssKeywords.Or); + var other = source.ParseMediaConnectorMultiple(CssKeywords.And, depth) ?? source.ParseMediaConnectorMultiple(CssKeywords.Or, depth); if (other is not null) { @@ -81,23 +81,23 @@ private static CssMedium ParseMediaCondition(this StringSource source) return medium; } - private static CssMedium ParseMediaConditionWithoutOr(this StringSource source) + private static CssMedium ParseMediaConditionWithoutOr(this StringSource source, Int32 depth) { // Syntax: // = | * - var medium = source.ParseMediaNot(); + var medium = source.ParseMediaNot(depth); if (medium is null) { - medium = source.ParseMediaInParens(); + medium = source.ParseMediaInParens(depth); if (medium is not null) { do { source.SkipSpacesAndComments(); - var other = source.ParseMediaConnector(CssKeywords.And); + var other = source.ParseMediaConnector(CssKeywords.And, depth); if (other is null) { @@ -113,7 +113,7 @@ private static CssMedium ParseMediaConditionWithoutOr(this StringSource source) return medium; } - private static CssMedium ParseMediaNot(this StringSource source) + private static CssMedium ParseMediaNot(this StringSource source, Int32 depth) { // Syntax: // = not @@ -123,7 +123,7 @@ private static CssMedium ParseMediaNot(this StringSource source) if (source.IsIdentifier(CssKeywords.Not)) { source.SkipSpacesAndComments(); - var medium = source.ParseMediaInParens(); + var medium = source.ParseMediaInParens(depth); if (medium is not null) { @@ -136,16 +136,17 @@ private static CssMedium ParseMediaNot(this StringSource source) return null; } - private static CssMedium ParseMediaInParens(this StringSource source) + private static CssMedium ParseMediaInParens(this StringSource source, Int32 depth) { // Syntax: // = ( ) | | - if (source.Current == Symbols.RoundBracketOpen) + // each nested condition recurses, so beyond the limit it is invalid + if (source.Current == Symbols.RoundBracketOpen && depth < ValueNesting.Limit) { var pos = source.Index; source.SkipCurrentAndSpaces(); - var medium = source.ParseMediaCondition(); + var medium = source.ParseMediaCondition(depth + 1); if (medium is not null && source.Current == Symbols.RoundBracketClose) { @@ -166,12 +167,12 @@ private static CssMedium ParseMediaInParens(this StringSource source) return source.ParseMediaFeature() ?? source.ParseGeneralEnclosed(); } - private static CssMedium ParseMediaConnectorMultiple(this StringSource source, String connector) + private static CssMedium ParseMediaConnectorMultiple(this StringSource source, String connector, Int32 depth) { // Syntax: // [ * | * ] - var part = source.ParseMediaConnector(connector); + var part = source.ParseMediaConnector(connector, depth); if (part is not null) { @@ -181,7 +182,7 @@ private static CssMedium ParseMediaConnectorMultiple(this StringSource source, S { source.SkipSpacesAndComments(); features = features.Concat(part.Features); - part = source.ParseMediaConnector(connector); + part = source.ParseMediaConnector(connector, depth); } return new CssMedium(String.Empty, false, false, features, connector); @@ -190,7 +191,7 @@ private static CssMedium ParseMediaConnectorMultiple(this StringSource source, S return null; } - private static CssMedium ParseMediaConnector(this StringSource source, String connector) + private static CssMedium ParseMediaConnector(this StringSource source, String connector, Int32 depth) { // Syntax: // = and @@ -202,7 +203,7 @@ private static CssMedium ParseMediaConnector(this StringSource source, String co if (source.IsIdentifier(connector)) { source.SkipSpacesAndComments(); - var medium = source.ParseMediaInParens(); + var medium = source.ParseMediaInParens(depth); if (medium is not null) { @@ -236,7 +237,7 @@ private static CssMedium ParseMediaType(this StringSource source) } source.SkipSpacesAndComments(); - var features = source.ParseMediaConditionWithoutOr(); + var features = source.ParseMediaConditionWithoutOr(0); if (features is not null) { diff --git a/src/AngleSharp.Css/Parser/ValueNesting.cs b/src/AngleSharp.Css/Parser/ValueNesting.cs new file mode 100644 index 00000000..1e458a02 --- /dev/null +++ b/src/AngleSharp.Css/Parser/ValueNesting.cs @@ -0,0 +1,40 @@ +namespace AngleSharp.Css.Parser +{ + using System; + + /// + /// The nesting depth the value and condition parsers (calc(), @media and @supports + /// conditions) allow. Those parsers run inside the value converters, which do not see the + /// parser options, so a parser makes its CssParserOptions.MaxValueNestingDepth current for + /// the time it builds, which is synchronous; everything else (e.g. SetProperty on the CSSOM) + /// gets the default. + /// + static class ValueNesting + { + [ThreadStatic] + private static Int32 _limit; + + /// + /// The depth allowed on this thread right now. + /// + public static Int32 Limit => _limit > 0 ? _limit : CssParserOptions.DefaultMaxValueNestingDepth; + + /// + /// Makes the limit of the given options current until the returned scope is disposed. + /// + public static Scope Use(CssParserOptions options) => new Scope(options.MaxValueNestingDepth); + + public readonly struct Scope : IDisposable + { + private readonly Int32 _previous; + + public Scope(Int32 limit) + { + _previous = _limit; + _limit = limit; + } + + public void Dispose() => _limit = _previous; + } + } +} diff --git a/src/AngleSharp.Performance.Css/DeepNestingBenchmarks.cs b/src/AngleSharp.Performance.Css/DeepNestingBenchmarks.cs index e4b2b4ba..140d417d 100644 --- a/src/AngleSharp.Performance.Css/DeepNestingBenchmarks.cs +++ b/src/AngleSharp.Performance.Css/DeepNestingBenchmarks.cs @@ -6,10 +6,10 @@ namespace AngleSharp.Performance.Css using System.Text; /// - /// Parsing style sheets that nest deeply. The shapes stay within the default nesting limit - /// (64) and within what a parser without the limit survives (on a 1 MB stack, before the - /// JIT optimizes, about 580 nested @media rules), so builds with and without the limit do - /// the same work. + /// Parsing style sheets that nest deeply. The shapes stay within the default nesting limits + /// (64 nested blocks, 63 parentheses inside calc()) and within what a parser without them + /// survives (on a 1 MB stack, before the JIT optimizes, about 580 nested @media rules and + /// 1900 calc() parentheses), so builds with and without the limits do the same work. /// [MemoryDiagnoser] public class DeepStyleSheetBenchmarks @@ -18,7 +18,7 @@ public class DeepStyleSheetBenchmarks private String _source = null!; - [Params("media-10", "media-60", "style-10", "style-60")] + [Params("media-10", "media-60", "style-10", "style-60", "calc-10", "calc-60", "supports-10", "supports-60")] public String Shape { get; set; } = null!; [GlobalSetup] @@ -31,6 +31,8 @@ public void Setup() { "media" => Repeat("@media screen{", depth) + "a{color:red}" + Repeat("}", depth), "style" => "a{" + Repeat("& b{", depth) + "color:red" + Repeat("}", depth + 1), + "calc" => "a{width:calc(" + Repeat("(1px + ", depth) + "1px" + Repeat(")", depth) + ")}", + "supports" => "@supports " + Repeat("(", depth) + "display:block" + Repeat(")", depth) + "{a{color:red}}", _ => throw new ArgumentException(Shape), }; } From c5d2853370fea65a0f383b9fad91c2e6839b526b Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 2 Nov 2026 09:13:53 +0100 Subject: [PATCH 2/8] Changed version --- CHANGELOG.md | 6 ++++++ src/AngleSharp.Css.Docs/package.json | 2 +- src/Directory.Build.props | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45647e7d..7e073e41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 1.3.2 + +Released on Monday, November 2 2026. + +- Improved the parser with a nesting limit for values and conditions (`MaxValueNestingDepth`) (#260) @michaelthyregod + # 1.3.1 Released on Sunday, November 1 2026. diff --git a/src/AngleSharp.Css.Docs/package.json b/src/AngleSharp.Css.Docs/package.json index da5e46a7..315c7d3d 100644 --- a/src/AngleSharp.Css.Docs/package.json +++ b/src/AngleSharp.Css.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/css", - "version": "1.3.1", + "version": "1.3.2", "preview": true, "description": "The doclet for the AngleSharp.Css documentation.", "keywords": [ diff --git a/src/Directory.Build.props b/src/Directory.Build.props index be3a0c07..333dd16b 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.3.1 + 1.3.2 enable latest true From efea89f76324712f9829d9f4cf3897374fdb7f5d Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:57:48 +0100 Subject: [PATCH 3/8] Limit how deep the rule index looks into :is() Indexing a rule for the cascade looks into the arguments of :is(), :where() and :matches(), parsing them again at every level, so the cost grows quadratically with the nesting: computing a style with 75 nested :is() took 45 us, 35 us with the cap (allocating 132 KB, 82 KB with it). - Look into at most 8 levels; a rule nested deeper stays ungrouped, i.e., it is a candidate for every element, which is always correct - Add tests for the boundary and for matching beyond it - Add DeepSelectorBenchmarks with 10, 50 and 75 levels --- .../Styling/StyleRuleIndexTests.cs | 5 +++ .../Dom/Internal/StyleRuleIndex.cs | 26 +++++++---- .../DeepSelectorBenchmarks.cs | 44 +++++++++++++++++++ 3 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 src/AngleSharp.Performance.Css/DeepSelectorBenchmarks.cs diff --git a/src/AngleSharp.Css.Tests/Styling/StyleRuleIndexTests.cs b/src/AngleSharp.Css.Tests/Styling/StyleRuleIndexTests.cs index fcd55a33..a74b71d4 100644 --- a/src/AngleSharp.Css.Tests/Styling/StyleRuleIndexTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/StyleRuleIndexTests.cs @@ -72,6 +72,7 @@ public async Task GroupedAndUngroupedRulesKeepTheCascadeOrder(string css) [TestCase(":where(.x .a, div) { color: green }", "
A
")] [TestCase(":matches(.x, .b) { color: green }", "
A
")] [TestCase(":is(:is(.x, .b)) { color: green }", "
A
")] + [TestCase(":is(:is(:is(:is(:is(:is(:is(:is(:is(.b))))))))) { color: green }", "
A
")] [TestCase(":is(.x, *) { color: green }", "
A
")] [TestCase(":is(.x, :not(.y)) { color: green }", "
A
")] [TestCase(".parent { :is(&) { color: green } }", "

A

")] @@ -89,6 +90,7 @@ public async Task RulesAreFoundViaTheirSubject(string css, string body) [TestCase(".a .b { color: red }", "

A

")] [TestCase("[data-x] { color: red }", "

A

")] [TestCase(":is(.x .a, .b) { color: red }", "

A

")] + [TestCase(":is(:is(:is(:is(:is(:is(:is(:is(:is(.x))))))))) { color: red }", "

A

")] public async Task RulesForOtherSubjectsDoNotApply(string css, string body) { var color = await ColorOfAsync(css, body); @@ -102,6 +104,9 @@ public async Task RulesForOtherSubjectsDoNotApply(string css, string body) [TestCase(":is(.x, .a) { color: red }", 1)] [TestCase(":where(.x .y, #z) { color: red }", 0)] [TestCase(":is(.x, :not(.y)) { color: red }", 1)] + // the index looks into 8 levels of :is(); a deeper rule stays ungrouped, i.e., a candidate + [TestCase(":is(:is(:is(:is(:is(:is(:is(:is(.x)))))))) { color: red }", 0)] + [TestCase(":is(:is(:is(:is(:is(:is(:is(:is(:is(.x))))))))) { color: red }", 1)] [TestCase("! { color: red }", 0)] public void OnlyRulesThatMayMatchAreCandidates(string css, int count) { diff --git a/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs b/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs index b1c59514..6e860eb6 100644 --- a/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs +++ b/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs @@ -355,17 +355,27 @@ private sealed class SubjectKeyVisitor : ISelectorVisitor PseudoClassNames.Matches, }; + // How many :is() levels are looked into. Each one parses its arguments again, so a + // deeply nested selector would cost quadratic time (and stack) to index; real ones + // nest a level or two. Deeper, the rule just stays ungrouped, which is always correct. + private const Int32 MaxArgumentDepth = 8; + private readonly ISelector _selector; private readonly ICssSelectorParser? _parser; + private readonly Int32 _depth; private SubjectKey[]? _keys; - private SubjectKeyVisitor(ISelector selector, ICssSelectorParser? parser) + private SubjectKeyVisitor(ISelector selector, ICssSelectorParser? parser, Int32 depth) { _selector = selector; _parser = parser; + _depth = depth; } - public static SubjectKey[]? GetKeys(ISelector? selector, ICssSelectorParser? parser) + public static SubjectKey[]? GetKeys(ISelector? selector, ICssSelectorParser? parser) => + GetKeys(selector, parser, 0); + + private static SubjectKey[]? GetKeys(ISelector? selector, ICssSelectorParser? parser, Int32 depth) { // a forced pseudo-class matches independent of its own selector if (selector is null || selector is ForcingPseudoClassSelector) @@ -373,7 +383,7 @@ private SubjectKeyVisitor(ISelector selector, ICssSelectorParser? parser) return null; } - var visitor = new SubjectKeyVisitor(selector, parser); + var visitor = new SubjectKeyVisitor(selector, parser, depth); selector.Accept(visitor); return visitor._keys; } @@ -409,7 +419,7 @@ void ISelectorVisitor.PseudoClass(String name) { // :is(.a .b, .c) only exposes its text, but an element matching it matches one // of the arguments, i.e., it requires one of their keys - just as a list does - var arguments = GetArguments(name); + var arguments = _depth < MaxArgumentDepth ? GetArguments(name) : null; if (arguments is not null && _parser is not null) { @@ -419,7 +429,7 @@ void ISelectorVisitor.PseudoClass(String name) // are valid only where the rule is (e.g., nested); then the keys are incomplete if (selector is not null && selector.Text.Equals(arguments, StringComparison.Ordinal)) { - _keys = GetKeys(selector, _parser); + _keys = GetKeys(selector, _parser, _depth + 1); } } } @@ -434,7 +444,7 @@ void ISelectorVisitor.List(IEnumerable selectors) foreach (var selector in selectors) { - var alternative = GetKeys(selector, _parser); + var alternative = GetKeys(selector, _parser, _depth); if (alternative is null) { @@ -449,7 +459,7 @@ void ISelectorVisitor.List(IEnumerable selectors) void ISelectorVisitor.Combinator(IEnumerable selectors, IEnumerable symbols) { - _keys = GetKeys(selectors.LastOrDefault(), _parser); + _keys = GetKeys(selectors.LastOrDefault(), _parser, _depth); } void ISelectorVisitor.Many(IEnumerable selectors) @@ -457,7 +467,7 @@ void ISelectorVisitor.Many(IEnumerable selectors) // all parts of a compound must match, so any key of a part is required foreach (var selector in selectors) { - var keys = GetKeys(selector, _parser); + var keys = GetKeys(selector, _parser, _depth); if (keys is not null && (_keys is null || IsBetter(keys, _keys))) { diff --git a/src/AngleSharp.Performance.Css/DeepSelectorBenchmarks.cs b/src/AngleSharp.Performance.Css/DeepSelectorBenchmarks.cs new file mode 100644 index 00000000..b10f9d2c --- /dev/null +++ b/src/AngleSharp.Performance.Css/DeepSelectorBenchmarks.cs @@ -0,0 +1,44 @@ +namespace AngleSharp.Performance.Css +{ + using AngleSharp; + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using AngleSharp.Html.Parser; + using BenchmarkDotNet.Attributes; + using System; + using System.Text; + + /// + /// Computing a style with a rule whose selector nests :is(): the cascade indexes the rule by + /// looking into the arguments. The depths stay within the 75 levels AngleSharp allows from + /// 1.9.1 on (Firefox's limit). + /// + [MemoryDiagnoser] + public class DeepSelectorBenchmarks + { + private IHtmlParser _parser = null!; + private String _source = null!; + + [Params(10, 50, 75)] + public Int32 Depth { get; set; } + + [GlobalSetup] + public void Setup() + { + var context = BrowsingContext.New(Configuration.Default.WithCss()); + _parser = context.GetService()!; + _source = "
x
"; + } + + [Benchmark] + public String ComputedStyle() + { + // a fresh document, so the rule is indexed again (the index is kept with the rule) + var document = _parser.ParseDocument(_source); + return document.DefaultView!.GetComputedStyle(document.QuerySelector("div")!).GetColor(); + } + + private static String Repeat(String value, Int32 count) => + new StringBuilder(value.Length * count).Insert(0, value, count).ToString(); + } +} From fda6eb0bbac4d4494a3d12ea21d96177055697eb Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:50:08 +0100 Subject: [PATCH 4/8] Add the CHANGELOG entry --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e073e41..0ae2a913 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ Released on Monday, November 2 2026. - Improved the parser with a nesting limit for values and conditions (`MaxValueNestingDepth`) (#260) @michaelthyregod +- Improved indexing rules with deeply nested `:is()`, `:where()`, or `:matches()` (#261) @michaelthyregod # 1.3.1 From 1584135ec87d60c3152f5670d3ced900dd760c54 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:00:17 +0100 Subject: [PATCH 5/8] Remember inherited lookups on the way up A computed style looks inherited declarations up through the snapshots of its parents. A property that no ancestor declares, e.g. visibility, was looked up through every ancestor for every element, so GetInnerText and IsVisible on the render tree grew quadratically with the depth (#262). - Keep the nearest declaration found for a name, or that there is none, on the snapshots passed; they never change, so each one is walked once per name. The entries are copied on write and published atomically - Leave the lookup of explicitly inherited declarations as it was - Add tests for deep chains, read deepest first and twice - Add DeepTreeBenchmarks for GetInnerText and IsVisible at 100 and 500 levels --- .../Styling/InheritanceChainTests.cs | 73 +++++++++++ .../Dom/Internal/CssStyleDeclaration.cs | 113 +++++++++++++++++- .../DeepTreeBenchmarks.cs | 73 +++++++++++ 3 files changed, 258 insertions(+), 1 deletion(-) create mode 100644 src/AngleSharp.Performance.Css/DeepTreeBenchmarks.cs diff --git a/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs b/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs index 0fcdb8f4..c9c148b8 100644 --- a/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs @@ -6,6 +6,7 @@ namespace AngleSharp.Css.Tests.Styling using AngleSharp.Dom; using AngleSharp.Html.Parser; using NUnit.Framework; + using System; using System.Collections.Generic; using System.Linq; @@ -143,5 +144,77 @@ public void MutatingAChildStyleDoesNotChangeItsParent() Assert.AreEqual("rgba(0, 0, 255, 1)", child.ComputedStyle.GetPropertyValue("color")); Assert.AreEqual("rgba(255, 0, 0, 1)", parent.ComputedStyle.GetPropertyValue("color")); } + + // Lookups through the parents are remembered on the way, so the levels are read deepest + // first and then again: a value remembered below a declaration must not leak above it. + [Test] + public void DeepChainInheritsFromTheNearestDeclaringAncestor() + { + var levels = BuildChain(300, level => level switch + { + 100 => "color: red", + 200 => "color: blue", + _ => null, + }); + + for (var pass = 0; pass < 2; pass++) + { + for (var level = levels.Count - 1; level >= 0; level--) + { + // above the first declaration nothing is inherited (a computed style leaves it empty) + var expected = level >= 200 ? "rgba(0, 0, 255, 1)" : level >= 100 ? "rgba(255, 0, 0, 1)" : String.Empty; + Assert.AreEqual(expected, levels[level].ComputedStyle.GetPropertyValue("color"), $"level {level}, pass {pass}"); + } + } + } + + [Test] + public void DeepChainWithoutADeclarationKeepsTheInitialValue() + { + var levels = BuildChain(300, level => level == 150 ? "visibility: hidden" : null); + + for (var pass = 0; pass < 2; pass++) + { + for (var level = levels.Count - 1; level >= 0; level--) + { + Assert.AreEqual(level < 150, levels[level].IsVisible(), $"level {level}, pass {pass}"); + } + } + + Assert.AreEqual(String.Empty, levels[0].ComputedStyle.GetPropertyValue("--undeclared")); + } + + // a chain of divs built with the DOM API, with the given inline style per level + private static List BuildChain(int depth, Func style) + { + var document = Parse(""); + IElement current = document.Body; + + for (var level = 0; level < depth; level++) + { + var child = document.CreateElement("div"); + child.Id = "level" + level; + + if (style(level) is string css) + { + child.SetAttribute("style", css); + } + + current.AppendChild(child); + current = child; + } + + current.TextContent = "x"; + var levels = new List(); + var node = Find(document.DefaultView.Render(), "level0"); + + while (node is not null) + { + levels.Add(node); + node = node.Children.OfType().FirstOrDefault(); + } + + return levels; + } } } diff --git a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs index e6dd6ab1..f0fac4d8 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs @@ -10,6 +10,7 @@ namespace AngleSharp.Css.Dom using System.Collections.Generic; using System.IO; using System.Linq; + using System.Threading; /// /// Represents a single CSS declaration block. @@ -582,6 +583,8 @@ private sealed class Snapshot private readonly Snapshot _parent; private readonly HashSet _forced; private List _merged; + // the names looked up through this snapshot, with the nearest declaration found + private NearestEntry[] _nearest; public Snapshot(List declarations, Dictionary index, Snapshot parent, HashSet forced) { @@ -602,8 +605,15 @@ public Snapshot(List declarations, Dictionary index /// public static ICssProperty Inherit(Snapshot parent, HashSet forced, String name) { + if (forced is null || !forced.Contains(name)) + { + // the nearest declaration decides, and a non-inheritable one is not taken + var nearest = parent.Nearest(name); + return nearest is not null && nearest.CanBeInherited ? nearest : null; + } + // a non-inheritable declaration is only taken if forced on every level - var allForced = forced is not null && forced.Contains(name); + var allForced = true; for (var current = parent; current is not null; current = current._parent) { @@ -667,6 +677,107 @@ public static void Merge(List declarations, Dictionary + /// Finds the nearest declaration with the given name, this snapshot's own or an + /// ancestor's. The chain is as deep as the DOM, and a name declared nowhere (e.g. + /// visibility) would be looked up through all of it for every element, so the + /// answer is kept on the snapshots passed: they never change. + ///
+ private ICssProperty Nearest(String name) + { + var result = default(ICssProperty); + var stop = default(Snapshot); + + for (var current = this; current is not null; current = current._parent) + { + result = current.FindOwn(name); + + if (result is not null || current.TryGetNearest(name, out result)) + { + stop = current; + break; + } + } + + for (var current = this; current != stop; current = current._parent) + { + current.AddNearest(name, result); + } + + return result; + } + + private Boolean TryGetNearest(String name, out ICssProperty declaration) + { + var entries = Volatile.Read(ref _nearest); + + if (entries is not null) + { + for (var i = 0; i < entries.Length; i++) + { + if (String.Equals(entries[i].Name, name, StringComparison.Ordinal)) + { + declaration = entries[i].Declaration; + return true; + } + } + } + + declaration = null; + return false; + } + + private void AddNearest(String name, ICssProperty declaration) + { + // only a few names are looked up, so the entries are copied on write; a + // concurrent reader of the same computed style sees either list + var entries = Volatile.Read(ref _nearest); + + while (true) + { + var count = entries?.Length ?? 0; + + for (var i = 0; i < count; i++) + { + if (String.Equals(entries[i].Name, name, StringComparison.Ordinal)) + { + return; + } + } + + var updated = new NearestEntry[count + 1]; + + if (count > 0) + { + Array.Copy(entries, updated, count); + } + + updated[count] = new NearestEntry(name, declaration); + var previous = Interlocked.CompareExchange(ref _nearest, updated, entries); + + if (previous == entries) + { + return; + } + + entries = previous; + } + } + + private readonly struct NearestEntry + { + public NearestEntry(String name, ICssProperty declaration) + { + Name = name; + Declaration = declaration; + } + + public String Name { get; } + + // null if no snapshot up the chain declares the name + public ICssProperty Declaration { get; } + } + private ICssProperty FindOwn(String name) { if (_index.TryGetValue(name, out var i) && i < _declarations.Count) diff --git a/src/AngleSharp.Performance.Css/DeepTreeBenchmarks.cs b/src/AngleSharp.Performance.Css/DeepTreeBenchmarks.cs new file mode 100644 index 00000000..3f6aa837 --- /dev/null +++ b/src/AngleSharp.Performance.Css/DeepTreeBenchmarks.cs @@ -0,0 +1,73 @@ +namespace AngleSharp.Performance.Css +{ + using AngleSharp; + using AngleSharp.Css; + using AngleSharp.Css.RenderTree; + using AngleSharp.Dom; + using AngleSharp.Html.Parser; + using BenchmarkDotNet.Attributes; + using System; + using System.Collections.Generic; + + /// + /// Reading inherited properties on a deep tree built with the DOM API: visibility is + /// inherited and declared nowhere, so it is looked up through all ancestors. The depths stay + /// within what the recursive walks over the tree survive on a 1 MB stack. + /// + [MemoryDiagnoser] + public class DeepTreeBenchmarks + { + private IDocument _document = null!; + private IRenderNode _tree = null!; + + [Params(100, 500)] + public Int32 Depth { get; set; } + + [GlobalSetup] + public void Setup() + { + var context = BrowsingContext.New(Configuration.Default.WithCss()); + _document = context.GetService()!.ParseDocument(""); + IElement current = _document.Body!; + + for (var i = 0; i < Depth; i++) + { + var child = _document.CreateElement("div"); + current.AppendChild(child); + current = child; + } + + current.TextContent = "x"; + _tree = _document.DefaultView!.Render(); + } + + [Benchmark] + public Int32 InnerText() => _document.Body!.GetInnerText().Length; + + [Benchmark] + public Int32 IsVisible() + { + // the render tree is built once, so only the lookups are measured + var pending = new Stack(); + var visible = 0; + pending.Push(_tree); + + while (pending.Count > 0) + { + var node = pending.Pop(); + + if (node.IsVisible()) + { + visible++; + } + + foreach (var child in node.Children) + { + pending.Push(child); + } + } + + return visible; + } + } +} From d4b568739a48cd9529a27a67e209a8c3c99ac19b Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:04:05 +0100 Subject: [PATCH 6/8] Add the CHANGELOG entry --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ae2a913..bc4d594f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Released on Monday, November 2 2026. - Improved the parser with a nesting limit for values and conditions (`MaxValueNestingDepth`) (#260) @michaelthyregod - Improved indexing rules with deeply nested `:is()`, `:where()`, or `:matches()` (#261) @michaelthyregod +- Improved reading inherited properties on deep trees (e.g. `visibility` in `IsVisible` and `GetInnerText`) (#263) @michaelthyregod # 1.3.1 From f159df108bd0dfa4d1bac946a459ba5aefe7a528 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:14:38 +0100 Subject: [PATCH 7/8] Grow fewer lists while cascading The cascade allocated a new list for the matching rules of every element and grew the explicit style one declaration at a time; on a real document this growth and the garbage it leaves dominate the render tree. - Reuse the list of matching rules from element to element; it is taken and given back atomically, so a concurrent cascade gets its own - Size the explicit style for the declarations of the matching rules --- .../Dom/Internal/CssStyleDeclaration.cs | 11 ++++++ .../Dom/Internal/StyleCollection.cs | 20 +++++++++++ .../Extensions/StyleCollectionExtensions.cs | 35 ++++++++++++++++--- 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs index f0fac4d8..49231163 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs @@ -51,6 +51,17 @@ public CssStyleDeclaration(IBrowsingContext context) _context = context; } + /// + /// Creates the declarations with room for the given number of entries, e.g. for + /// a cascade that knows how many declarations its matching rules bring. + /// + internal CssStyleDeclaration(IBrowsingContext context, Int32 capacity) + { + _declarations = new List(capacity); + _declarationIndex = new Dictionary(capacity, StringComparer.Ordinal); + _context = context; + } + public CssStyleDeclaration(ICssRule parent) : this(parent.Owner?.Context) { diff --git a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs index 34010344..d24fc73c 100644 --- a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs +++ b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs @@ -5,6 +5,7 @@ namespace AngleSharp.Css.Dom using System.Collections; using System.Collections.Generic; using System.Linq; + using System.Threading; sealed class StyleCollection : IStyleCollection { @@ -16,6 +17,7 @@ sealed class StyleCollection : IStyleCollection private List? _rules; private List? _layerRanks; private StyleRuleIndex? _index; + private List? _matches; private Int32 _defaultRuleCount; #endregion @@ -69,6 +71,24 @@ public StyleCollection(IEnumerable defaultSheets, IEnumerable internal StyleRuleIndex GetIndex() => _index ??= new StyleRuleIndex(GetRules()); + /// + /// Takes the list for the rules matching an element, which is reused from + /// element to element instead of growing a new one each time. The list is + /// taken atomically, so a concurrent cascade on the same collection gets + /// a new one. + /// + internal List TakeMatches() => + Interlocked.Exchange(ref _matches, null) ?? new List(); + + /// + /// Gives back the list from TakeMatches once the element's style is computed. + /// + internal void ReturnMatches(List matches) + { + matches.Clear(); + Volatile.Write(ref _matches, matches); + } + /// /// Gets the rank of the cascade layer of the rule at the given index of /// GetRules: rules of a lower rank lose against rules of a higher rank diff --git a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs index 00fa3908..c3c7aae8 100644 --- a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs @@ -134,8 +134,8 @@ public static ICssStyleDeclaration ComputeCascadedStyle(this IStyleCollection st public static ICssStyleDeclaration ComputeExplicitStyle(this IStyleCollection styles, IElement element) { var ctx = element.Owner?.Context ?? throw new InvalidOperationException("The element must be associated with a browsing context."); - var computedStyle = new CssStyleDeclaration(ctx); var matches = styles.SortBySpecificity(element); + var computedStyle = new CssStyleDeclaration(ctx, CountDeclarations(matches)); var i = 0; for (; i < matches.Count && matches[i].IsDefault; i++) @@ -151,6 +151,7 @@ public static ICssStyleDeclaration ComputeExplicitStyle(this IStyleCollection st } ApplyImportantLayerOrder(computedStyle, matches); + ReturnMatches(styles, matches); if (element is IHtmlElement || element is ISvgElement) { @@ -221,6 +222,7 @@ internal static ICssStyleDeclaration ComputeHostStyle(this IStyleCollection styl } ApplyImportantLayerOrder(computedStyle, matches); + ReturnMatches(styles, matches); computedStyle.SetDeclarations(host.GetStyle()); computedStyle.SetDeclarations(shadowStyle.Where(m => m.IsImportant).ToList()); return computedStyle; @@ -312,8 +314,9 @@ private static List SortBySpecificity(this IStyleCollection styles, I var defaultRuleCount = collection.GetDefaultRuleCount(); var candidates = collection.GetIndex().GetCandidates(element); // not sized for the candidates: the unkeyed rules (e.g., [data-theme] or :root) - // are candidates for every element, but only a few of them match - matches = new List(); + // are candidates for every element, but only a few of them match; the list + // is reused from element to element instead + matches = collection.TakeMatches(); // the candidates keep the order of the rules, as required by the cascade foreach (var i in candidates) @@ -337,6 +340,30 @@ private static List SortBySpecificity(this IStyleCollection styles, I return matches; } + /// + /// Counts the declarations of the matching rules: the cascade keeps at most + /// these, so the explicit style does not grow while they are applied. + /// + private static Int32 CountDeclarations(List matches) + { + var count = 0; + + foreach (var match in matches) + { + count += match.Rule.Style.Length; + } + + return count; + } + + private static void ReturnMatches(IStyleCollection styles, List matches) + { + if (styles is StyleCollection collection) + { + collection.ReturnMatches(matches); + } + } + private static void MapPriority(ICssStyleRule rule, IElement element, IElement? scope, Boolean isDefault, Int32 layerRank, List matches) { if (rule.TryMatch(element, scope, out var specificity)) @@ -355,7 +382,7 @@ private static void MapPriority(ICssStyleRule rule, IElement element, IElement? } } - private readonly struct RuleMatch + internal readonly struct RuleMatch { public RuleMatch(ICssStyleRule rule, Boolean isDefault, Int32 layerRank, Priority priority, Int32 index) { From cbbfdf46d56dfc5c6a55a31e810b46234bec8779 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 3 Nov 2026 13:05:12 +0100 Subject: [PATCH 8/8] Improvements for rendering --- CHANGELOG.md | 12 +- .../CssColorProperties.cs | 13 + .../Declarations/CssBorderProperty.cs | 12 + .../Styling/Configuration.cs | 5 +- .../DefaultStyleSheetFormControlTests.cs | 100 ++++- .../Styling/PresentationalHintTests.cs | 126 ++++-- .../Styling/RelativeValueResolutionTests.cs | 4 +- src/AngleSharp.Css/Constants/Map.cs | 11 +- .../CssDefaultStyleSheetProvider.cs | 33 +- .../Declarations/VerticalAlignDeclaration.cs | 2 +- .../Dom/Internal/PresentationalHints.cs | 367 +++++++++++++++++- src/AngleSharp.Css/Dom/TextAlign.cs | 12 + src/AngleSharp.Css/Parser/CssBuilder.cs | 30 ++ src/AngleSharp.Css/Parser/Micro/UnitParser.cs | 5 +- src/AngleSharp.Css/ValueConverters.cs | 5 +- .../Values/Composites/CssShadowValue.cs | 3 +- 16 files changed, 667 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e073e41..d82df6a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,18 @@ # 1.3.2 -Released on Monday, November 2 2026. +Released on Tuesday, November 3 2026. - Improved the parser with a nesting limit for values and conditions (`MaxValueNestingDepth`) (#260) @michaelthyregod +- Fixed `min()`, `max()`, and `clamp()` being rejected in line widths such as `border-width` and the `border` shorthand +- Fixed `only` and the names of unknown schemes being rejected in `color-scheme` +- Fixed the default style of form controls to use the text color (not inherited, except for file inputs), font (`13.3333px Arial`, with a `normal` line height), padding, margins, and `box-sizing` of browsers, and added the one of `progress` and `meter` +- Fixed `font-size` keywords being relative to the parent's size, instead of absolute sizes matching browsers (`x-small` 10px, `small` 13px, `large` 18px, ...) +- Fixed `min()`, `max()` and `clamp()` being rejected in grid tracks and `background-size`/`mask-size` +- Fixed computing a `box-shadow` or `text-shadow` without a color throwing +- Added the default border of `iframe` and its `frameborder` attribute +- Added the presentational hints `cellspacing`, `cellpadding`, `border`, `align`, `valign`, `nowrap`, `background`, `hspace`, `vspace`, `size` and `face` of fonts and rules, `type` of lists, and the margin attributes of the body +- Added the quirks mode sheet of documents without a doctype (tables not inheriting font and alignment, the bottom margin of forms) and lengths without units and colors without a hash there +- Added `-webkit-center`, `-webkit-left` and `-webkit-right` for `text-align` (used for `
`) and `-webkit-baseline-middle` for `vertical-align` # 1.3.1 diff --git a/src/AngleSharp.Css.Tests/CssColorProperties.cs b/src/AngleSharp.Css.Tests/CssColorProperties.cs index 52b85334..fed56afe 100644 --- a/src/AngleSharp.Css.Tests/CssColorProperties.cs +++ b/src/AngleSharp.Css.Tests/CssColorProperties.cs @@ -1,3 +1,4 @@ +using System; namespace AngleSharp.Css.Tests { using AngleSharp.Css.Dom; @@ -58,6 +59,18 @@ public void CaretColorRgb() Assert.That(property.HasValue, Is.True); } + [TestCase("color-scheme: only dark", "only dark")] + [TestCase("color-scheme: dark only", "dark only")] + [TestCase("color-scheme: only light", "only light")] + [TestCase("color-scheme: light dark only", "light dark only")] + [TestCase("color-scheme: foo dark", "foo dark")] + public void CssColorSchemeAcceptsOnlyAndUnknownSchemes(String snippet, String expected) + { + var property = ParseDeclaration(snippet); + Assert.That(property.HasValue, Is.True); + Assert.That(property.Value, Is.EqualTo(expected)); + } + [Test] public void ColorSchemeNormal() { diff --git a/src/AngleSharp.Css.Tests/Declarations/CssBorderProperty.cs b/src/AngleSharp.Css.Tests/Declarations/CssBorderProperty.cs index 21247eb3..d4c74b7c 100644 --- a/src/AngleSharp.Css.Tests/Declarations/CssBorderProperty.cs +++ b/src/AngleSharp.Css.Tests/Declarations/CssBorderProperty.cs @@ -1,5 +1,6 @@ using AngleSharp.Css.Dom; using AngleSharp.Css.Parser; +using System; namespace AngleSharp.Css.Tests.Declarations { @@ -365,6 +366,17 @@ public void CssBorderLeftWidthThickLegal() Assert.AreEqual("5px", property.Value); } + [TestCase("border-width: max(1px, 2px)")] + [TestCase("border-top-width: min(1px, 2px)")] + [TestCase("border-width: clamp(1px, 2px, 3px)")] + [TestCase("border: max(1px, .0625rem) solid red")] + [TestCase("outline-width: max(1px, 2px)")] + public void CssLineWidthAcceptsComparisonFunctions(String snippet) + { + var property = ParseDeclaration(snippet); + Assert.IsTrue(property.HasValue); + } + [Test] public void CssBorderWidthMediumLegal() { diff --git a/src/AngleSharp.Css.Tests/Styling/Configuration.cs b/src/AngleSharp.Css.Tests/Styling/Configuration.cs index 75d297d2..0891fc5c 100644 --- a/src/AngleSharp.Css.Tests/Styling/Configuration.cs +++ b/src/AngleSharp.Css.Tests/Styling/Configuration.cs @@ -47,7 +47,10 @@ public void ObtainDefaultSheet() // 72, not 70: the UA stylesheet now also generates quotes for `q::before` and // `q::after`. // 73, not 72: the UA stylesheet now also gives `::placeholder` its default look. - Assert.AreEqual(73, sheet.Rules.Length); + // 80, not 73: the UA stylesheet now also has rules of its own for text areas, selects, + // list boxes, file, search and date/time inputs, progress bars and meters. + // 81, not 80: the UA stylesheet now also gives `iframe` its default border. + Assert.AreEqual(81, sheet.Rules.Length); } } } diff --git a/src/AngleSharp.Css.Tests/Styling/DefaultStyleSheetFormControlTests.cs b/src/AngleSharp.Css.Tests/Styling/DefaultStyleSheetFormControlTests.cs index 6a859b28..c10204f0 100644 --- a/src/AngleSharp.Css.Tests/Styling/DefaultStyleSheetFormControlTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/DefaultStyleSheetFormControlTests.cs @@ -47,23 +47,56 @@ private static void AssertPadding(ICssStyleDeclaration style, string vertical, s [TestCase("")] [TestCase("")] [TestCase("")] - [TestCase("")] public void TextFieldsHaveABorderPaddingAndAWhiteBackground(string html) { var style = ComputedStyle(html); AssertBorder(style, "1px", "solid", "rgba(118, 118, 118, 1)"); - AssertPadding(style, "2px", "4px"); + AssertPadding(style, "1px", "2px"); Assert.AreEqual("rgba(255, 255, 255, 1)", style.GetPropertyValue("background-color")); } + [Test] + public void TextAreaHasABorderPaddingAndAWhiteBackground() + { + var style = ComputedStyle(""); + + AssertBorder(style, "1px", "solid", "rgba(118, 118, 118, 1)"); + AssertPadding(style, "2px", "2px"); + Assert.AreEqual("rgba(255, 255, 255, 1)", style.GetPropertyValue("background-color")); + } + + [TestCase("")] + [TestCase("")] + [TestCase("")] + [TestCase("")] + public void ControlsDoNotInheritTheFontOfThePage(string html) + { + var style = ComputedStyle(html); + + Assert.AreEqual("13.3333px", style.GetPropertyValue("font-size")); + StringAssert.StartsWith("Arial", style.GetPropertyValue("font-family")); + } + + [TestCase("")] + [TestCase("")] + [TestCase("")] + [TestCase("")] + public void ControlsDoNotInheritTheLineHeightOfThePage(string html) + { + var style = ComputedStyle(html); + + Assert.AreEqual("normal", style.GetPropertyValue("line-height")); + } + [Test] public void SelectLooksLikeAButtonWithTextPadding() { var style = ComputedStyle(""); AssertBorder(style, "1px", "solid", "rgba(118, 118, 118, 1)"); - AssertPadding(style, "2px", "4px"); + AssertPadding(style, "0px", "0px"); + Assert.AreEqual("border-box", style.GetPropertyValue("box-sizing")); Assert.AreEqual("rgba(232, 232, 232, 1)", style.GetPropertyValue("background-color")); } @@ -71,24 +104,73 @@ public void SelectLooksLikeAButtonWithTextPadding() [TestCase("")] [TestCase("")] [TestCase("")] - [TestCase("")] public void ButtonsHaveABorderWidePaddingAndAGrayBackground(string html) { var style = ComputedStyle(html); AssertBorder(style, "1px", "solid", "rgba(118, 118, 118, 1)"); - AssertPadding(style, "2px", "10px"); + AssertPadding(style, "1px", "6px"); Assert.AreEqual("rgba(232, 232, 232, 1)", style.GetPropertyValue("background-color")); } + [Test] + public void FileInputIsATransparentBoxWithoutPadding() + { + var style = ComputedStyle(""); + + Assert.AreEqual("none", style.GetPropertyValue("border-top-style")); + AssertPadding(style, "0px", "0px"); + } + + [TestCase("")] + [TestCase("")] + public void ListBoxesAreWhite(string html) + { + Assert.AreEqual("rgba(255, 255, 255, 1)", ComputedStyle(html).GetPropertyValue("background-color")); + } + + [TestCase("")] + [TestCase("")] + public void ProgressAndMeterAreInlineBlocksInheritingTheFont(string html) + { + var style = ComputedStyle("" + html); + + Assert.AreEqual("inline-block", style.GetPropertyValue("display")); + Assert.AreEqual("border-box", style.GetPropertyValue("box-sizing")); + Assert.AreEqual("20px", style.GetPropertyValue("font-size")); + } + + [TestCase("")] + [TestCase("")] + [TestCase("")] + [TestCase("")] + [TestCase("")] + [TestCase("")] + public void ControlsDoNotInheritTheTextColorOfThePage(string html) + { + var style = ComputedStyle("" + html); + + Assert.AreEqual("rgba(0, 0, 0, 1)", style.GetPropertyValue("color")); + } + + [TestCase("")] + [TestCase("")] + [TestCase("")] + public void SomeControlsInheritTheTextColorOfThePage(string html) + { + var style = ComputedStyle("" + html); + + Assert.AreEqual("rgba(200, 0, 0, 1)", style.GetPropertyValue("color")); + } + [Test] public void ColorInputHasANarrowPadding() { var style = ComputedStyle(""); AssertBorder(style, "1px", "solid", "rgba(118, 118, 118, 1)"); - AssertPadding(style, "2px", "2px"); - Assert.AreEqual("rgba(255, 255, 255, 1)", style.GetPropertyValue("background-color")); + AssertPadding(style, "1px", "2px"); + Assert.AreEqual("rgba(232, 232, 232, 1)", style.GetPropertyValue("background-color")); } [TestCase("checkbox")] @@ -102,8 +184,8 @@ public void CheckboxesAndRadiosHaveABorderAndTheirOwnMargin(string type) Assert.AreEqual("rgba(255, 255, 255, 1)", style.GetPropertyValue("background-color")); Assert.AreEqual("3px", style.GetPropertyValue("margin-top")); Assert.AreEqual("3px", style.GetPropertyValue("margin-right")); - Assert.AreEqual("3px", style.GetPropertyValue("margin-bottom")); - Assert.AreEqual("4px", style.GetPropertyValue("margin-left")); + Assert.AreEqual(type == "radio" ? "0px" : "3px", style.GetPropertyValue("margin-bottom")); + Assert.AreEqual(type == "radio" ? "5px" : "4px", style.GetPropertyValue("margin-left")); } [Test] diff --git a/src/AngleSharp.Css.Tests/Styling/PresentationalHintTests.cs b/src/AngleSharp.Css.Tests/Styling/PresentationalHintTests.cs index 2986aa03..0dbfb101 100644 --- a/src/AngleSharp.Css.Tests/Styling/PresentationalHintTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/PresentationalHintTests.cs @@ -4,68 +4,118 @@ namespace AngleSharp.Css.Tests.Styling using AngleSharp.Css.Dom; using AngleSharp.Dom; using NUnit.Framework; - using System.Threading.Tasks; + using static CssConstructionFunctions; /// - /// Attributes like the width of an img were ignored, so images showed in their natural size. - /// Found on MDN. They map to CSS (HTML 15.3 - 15.4) like author rules of no specificity, - /// which precede all other author rules. + /// The attributes of HTML elements mapping to CSS (HTML 15.3), and the quirks mode sheet. /// [TestFixture] public class PresentationalHintTests { - private static async Task StyleOfAsync(string css, string html) + private static ICssStyleDeclaration Style(string html, string doctype = "") => + ParseDocument($"{doctype}{html}").GetElementById("t").ComputeCurrentStyle(); + + [TestCase("
", "border-spacing", "5px")] + [TestCase("
", "padding-left", "7px")] + [TestCase("
", "padding-left", "10px")] + [TestCase("
", "border-top-width", "3px")] + [TestCase("
", "border-top-style", "outset")] + [TestCase("
", "border-top-width", "1px")] + [TestCase("
", "border-top-style", "inset")] + [TestCase("
", "float", "right")] + [TestCase("
", "margin-left", "auto")] + [TestCase("
", "text-align", "-webkit-center")] + [TestCase("
", "vertical-align", "top")] + [TestCase("
", "vertical-align", "bottom")] + [TestCase("
", "white-space", "nowrap")] + [TestCase("
", "text-align", "-webkit-right")] + [TestCase("

", "text-align", "center")] + [TestCase("
", "text-align", "-webkit-center")] + [TestCase("", "float", "left")] + [TestCase("", "vertical-align", "top")] + [TestCase("", "vertical-align", "-webkit-baseline-middle")] + [TestCase("", "vertical-align", "middle")] + [TestCase("", "margin-right", "5px")] + [TestCase("", "margin-top", "7px")] + [TestCase("", "border-left-width", "2px")] + [TestCase("", "font-size", "10px")] + [TestCase("", "font-size", "24px")] + [TestCase("", "font-size", "18px")] + [TestCase("", "font-family", "monospace")] + [TestCase("
", "margin-left", "auto")] + [TestCase("
", "height", "3px")] + [TestCase("
    ", "list-style-type", "square")] + [TestCase("
      ", "list-style-type", "lower-alpha")] + public void AttributeMapsToProperty(string html, string property, string expected) { - var context = BrowsingContext.New(Configuration.Default.WithCss()); - var document = await context.OpenAsync(req => req.Content($"{html}")); - return document.DefaultView.GetComputedStyle(document.GetElementById("t")); + Assert.AreEqual(expected, Style(html).GetPropertyValue(property)); } - // an empty value means none was set - [TestCase("", "40px", "30px")] - [TestCase("", "40.5px", "30px")] - [TestCase("", "50%", "")] - [TestCase("", "", "")] - [TestCase("", "40px", "30px")] - [TestCase("", "40px", "30px")] - [TestCase("", "40px", "30px")] - [TestCase("", "", "")] - [TestCase("
      ", "", "")] - [TestCase("
      ", "", "30px")] - public async Task DimensionAttributesMapToTheirProperties(string html, string width, string height) + [TestCase("", "border-top-width", "2px")] + [TestCase("", "border-top-style", "inset")] + [TestCase("", "border-top-style", "none")] + [TestCase("", "width", "50px")] + public void IframeHasItsDefaultBorderAndHints(string html, string property, string expected) { - var style = await StyleOfAsync("", html); + Assert.AreEqual(expected, Style(html).GetPropertyValue(property)); + } - Assert.AreEqual(width, style.GetWidth()); - Assert.AreEqual(height, style.GetHeight()); + [TestCase("
      ", "box-shadow")] + [TestCase("
      ", "text-shadow")] + public void ShadowWithoutAColorCanBeComputed(string html, string property) + { + StringAssert.Contains("1px 2px", Style(html).GetPropertyValue(property)); } - [TestCase("img { width: 20px }", "20px")] - [TestCase("* { width: 20px }", "20px")] - [TestCase("", "40px")] - public async Task AuthorRulesOverrideTheHints(string css, string width) + [Test] + public void AuthorRulesWinOverHints() { - var style = await StyleOfAsync(css, ""); + Assert.AreEqual("1px", Style("
      ").GetPropertyValue("padding-left")); + } - Assert.AreEqual(width, style.GetWidth()); + [TestCase("
      ", "font-size", "16px")] + [TestCase("
      ", "text-align", "start")] + [TestCase("
      ", "white-space", "normal")] + [TestCase("
      ", "margin-bottom", "16px")] + [TestCase("", "box-sizing", "border-box")] + [TestCase("", "margin-right", "3px")] + public void QuirksModeHasItsOwnRules(string html, string property, string expected) + { + Assert.AreEqual(expected, Style(html, doctype: string.Empty).GetPropertyValue(property)); } [Test] - public async Task InlineStylesOverrideTheHints() + public void StandardsModeHasNoneOfThem() { - var style = await StyleOfAsync("", ""); + Assert.AreEqual("right", Style("
      ").GetPropertyValue("text-align")); + Assert.AreNotEqual("16px", Style("
      ").GetPropertyValue("margin-bottom")); + } + + [TestCase("
      ", "width", "100px")] + [TestCase("
      ", "margin-left", "20px")] + [TestCase("
      ", "color", "rgba(0, 255, 0, 1)")] + public void QuirksModeAllowsLengthsWithoutUnitsAndColorsWithoutHash(string html, string property, string expected) + { + var context = BrowsingContext.New(Configuration.Default.WithCss()); + var document = context.OpenAsync(request => request.Content($"{html}")).Result; - Assert.AreEqual("20px", style.GetWidth()); + Assert.AreEqual(expected, document.GetElementById("t").ComputeCurrentStyle().GetPropertyValue(property)); } - [TestCase("
      ")] - [TestCase("
      ")] - [TestCase("
      ")] - public async Task BackgroundColorAttributesMapToTheBackgroundColor(string html) + [TestCase("
      ", "grid-template-columns", "min(50%, 300px) 1fr")] + [TestCase("
      ", "grid-template-columns", "minmax(max(1px, 2%), 1fr)")] + [TestCase("
      ", "grid-template-columns", "clamp(10px, 1px + 5%, 100px) 1fr")] + [TestCase("
      ", "background-size", "18px")] + [TestCase("
      ", "mask-size", "10px")] + public void MathFunctionsAreSizes(string html, string property, string expected) { - var style = await StyleOfAsync("", html); + Assert.AreEqual(expected, Style(html).GetPropertyValue(property)); + } - Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetBackgroundColor()); + [Test] + public void StandardsModeRejectsThem() + { + Assert.AreNotEqual("100px", Style("
      ").GetPropertyValue("width")); } } } diff --git a/src/AngleSharp.Css.Tests/Styling/RelativeValueResolutionTests.cs b/src/AngleSharp.Css.Tests/Styling/RelativeValueResolutionTests.cs index fd459b7a..a7571ddd 100644 --- a/src/AngleSharp.Css.Tests/Styling/RelativeValueResolutionTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/RelativeValueResolutionTests.cs @@ -52,7 +52,9 @@ public void EmUsesTheComputedFontSizeOfTheElement(string declarations, string pr Assert.AreEqual(expected, ComputedInParent(declarations, property)); } - [TestCase("font: large serif", "font-size", "19.2px")] + [TestCase("font: large serif", "font-size", "18px")] + [TestCase("font-size: x-small", "font-size", "10px")] + [TestCase("font-size: small", "font-size", "13px")] [TestCase("font: larger serif", "font-size", "24px")] [TestCase("font-size: xx-large", "font-size", "32px")] public void FontSizeKeywordsComputeToLengths(string declarations, string property, string expected) diff --git a/src/AngleSharp.Css/Constants/Map.cs b/src/AngleSharp.Css/Constants/Map.cs index 23042066..4ae334a9 100644 --- a/src/AngleSharp.Css/Constants/Map.cs +++ b/src/AngleSharp.Css/Constants/Map.cs @@ -104,6 +104,9 @@ static class Map { CssKeywords.End, TextAlign.End }, { CssKeywords.JustifyAll, TextAlign.JustifyAll }, { CssKeywords.MatchParent, TextAlign.MatchParent }, + { "-webkit-center", TextAlign.WebkitCenter }, + { "-webkit-left", TextAlign.WebkitLeft }, + { "-webkit-right", TextAlign.WebkitRight }, }; /// @@ -309,11 +312,11 @@ static class Map /// public static readonly Dictionary FontSizes = new(StringComparer.OrdinalIgnoreCase) { - { CssKeywords.XxSmall, new CssLengthValue(0.6, CssLengthValue.Unit.Em) }, - { CssKeywords.XSmall, new CssLengthValue(0.75, CssLengthValue.Unit.Em) }, - { CssKeywords.Small, new CssLengthValue(8.0 / 9.0, CssLengthValue.Unit.Em) }, + { CssKeywords.XxSmall, new CssLengthValue(9.0 / 16.0, CssLengthValue.Unit.Em) }, + { CssKeywords.XSmall, new CssLengthValue(10.0 / 16.0, CssLengthValue.Unit.Em) }, + { CssKeywords.Small, new CssLengthValue(13.0 / 16.0, CssLengthValue.Unit.Em) }, { CssKeywords.Medium, new CssLengthValue(1.0, CssLengthValue.Unit.Em) }, - { CssKeywords.Large, new CssLengthValue(1.2, CssLengthValue.Unit.Em) }, + { CssKeywords.Large, new CssLengthValue(18.0 / 16.0, CssLengthValue.Unit.Em) }, { CssKeywords.XLarge, new CssLengthValue(1.5, CssLengthValue.Unit.Em) }, { CssKeywords.XxLarge, new CssLengthValue(2.0, CssLengthValue.Unit.Em) }, { CssKeywords.XxxLarge, new CssLengthValue(3.0, CssLengthValue.Unit.Em) }, diff --git a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs index f7946bc1..5ea4a117 100644 --- a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs +++ b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs @@ -119,24 +119,36 @@ private static ICssStyleSheet Parse(String source) kbd, samp { font-family: monospace } pre { white-space: pre } button, textarea, -input, select { display: inline-block } +input, select, +progress, meter { display: inline-block; font: 13.3333px/normal Arial, sans-serif } +progress, meter { box-sizing: border-box; vertical-align: -0.2em; font: inherit } input, textarea, -select, button { border: 1px solid rgb(118, 118, 118); padding: 2px 4px; background-color: rgb(255, 255, 255) } +select, button { border: 1px solid rgb(118, 118, 118); padding: 1px 2px; background-color: rgb(255, 255, 255); color: rgb(0, 0, 0) } +textarea { padding: 2px } +select { padding: 0px; box-sizing: border-box } select, button, input[type=button], input[type=submit], input[type=reset], -input[type=file] { background-color: rgb(232, 232, 232) } +input[type=color] { background-color: rgb(232, 232, 232) } +select[multiple], +select[size] { background-color: rgb(255, 255, 255) } button, input[type=button], input[type=submit], -input[type=reset], -input[type=file] { padding: 2px 10px } -input[type=color] { padding: 2px } +input[type=reset] { padding: 1px 6px; box-sizing: border-box } +input[type=file] { border: none; padding: 0px; background-color: transparent; color: inherit } +input[type=search] { box-sizing: border-box } +input[type=color] { padding: 1px 2px; box-sizing: border-box } +input[type=date], +input[type=time], +input[type=datetime-local], +input[type=month], +input[type=week] { padding: 0px 0px 0px 1px } input[type=checkbox], -input[type=radio] { padding: 0px; margin: 3px 3px 3px 4px } -input[type=radio] { border-radius: 50% } -input[type=range] { border: none; padding: 0px; background-color: transparent } +input[type=radio] { padding: 0px; box-sizing: border-box; margin: 3px 3px 3px 4px } +input[type=radio] { border-radius: 50%; margin: 3px 3px 0px 5px } +input[type=range] { border: none; padding: 0px; margin: 2px; background-color: transparent } input[type=hidden] { display: none } textarea { white-space: pre-wrap } ::placeholder { color: darkgray } @@ -144,6 +156,7 @@ private static ICssStyleSheet Parse(String source) small, sub, sup { font-size: .83em } sub { vertical-align: sub } sup { vertical-align: super } +iframe { border: 2px inset rgb(238, 238, 238) } table { border-spacing: 2px; box-sizing: border-box; text-indent: 0 } thead, tbody, tfoot { vertical-align: middle } @@ -164,7 +177,7 @@ private static ICssStyleSheet Parse(String source) q::before { content: open-quote } q::after { content: close-quote } *::before, *::after { display: inline } -center { text-align: center } +center { text-align: -webkit-center } :link { color: #0000ee } :visited { color: #551a8b } :link, :visited { text-decoration: underline } diff --git a/src/AngleSharp.Css/Declarations/VerticalAlignDeclaration.cs b/src/AngleSharp.Css/Declarations/VerticalAlignDeclaration.cs index 68cb8437..92d3a5c5 100644 --- a/src/AngleSharp.Css/Declarations/VerticalAlignDeclaration.cs +++ b/src/AngleSharp.Css/Declarations/VerticalAlignDeclaration.cs @@ -8,7 +8,7 @@ static class VerticalAlignDeclaration { public static String Name = PropertyNames.VerticalAlign; - public static IValueConverter Converter = Or(LengthOrPercentConverter, VerticalAlignmentConverter); + public static IValueConverter Converter = Or(LengthOrPercentConverter, VerticalAlignmentConverter, Assign("-webkit-baseline-middle", "-webkit-baseline-middle")); public static ICssValue InitialValue = InitialValues.VerticalAlignDecl; diff --git a/src/AngleSharp.Css/Dom/Internal/PresentationalHints.cs b/src/AngleSharp.Css/Dom/Internal/PresentationalHints.cs index 9da096dd..d6607579 100644 --- a/src/AngleSharp.Css/Dom/Internal/PresentationalHints.cs +++ b/src/AngleSharp.Css/Dom/Internal/PresentationalHints.cs @@ -19,65 +19,424 @@ static class PresentationalHints ///
      public static String? GetDeclarations(IElement element) { - if (element is not IHtmlElement || !element.HasAttributes()) + if (element is not IHtmlElement) { return null; } var hints = new StringBuilder(); + if (element.Owner?.CompatMode == "BackCompat") + { + AddQuirks(hints, element); + } + + // a cell gets its hints from the table, too + if (element.Attributes.Length == 0 && element.LocalName is not ("td" or "th")) + { + return hints.Length > 0 ? hints.ToString() : null; + } + switch (element.LocalName) { case "img": - case "video": case "embed": - case "iframe": case "object": AddDimension(hints, element, "width", "width", ignoreZero: false); AddDimension(hints, element, "height", "height", ignoreZero: false); + AddImageSpacing(hints, element); + AddImageAlign(hints, element); + break; + case "video": + case "iframe": + AddDimension(hints, element, "width", "width", ignoreZero: false); + AddDimension(hints, element, "height", "height", ignoreZero: false); + AddImageSpacing(hints, element); + + if (element.GetAttribute("frameborder")?.Trim() is "0" or "no") + { + hints.Append("border: 0;"); + } + break; case "input" when element.GetAttribute("type").Isi("image"): AddDimension(hints, element, "width", "width", ignoreZero: false); AddDimension(hints, element, "height", "height", ignoreZero: false); + AddImageSpacing(hints, element); + AddImageAlign(hints, element); break; case "table": AddDimension(hints, element, "width", "width", ignoreZero: true); AddDimension(hints, element, "height", "height", ignoreZero: false); AddColor(hints, element, "bgcolor", "background-color"); + AddBackground(hints, element); + AddTableAlign(hints, element); + AddLength(hints, element, "cellspacing", "border-spacing"); + AddTableBorder(hints, element); break; case "td": case "th": AddDimension(hints, element, "width", "width", ignoreZero: true); AddDimension(hints, element, "height", "height", ignoreZero: false); AddColor(hints, element, "bgcolor", "background-color"); + AddBackground(hints, element); + AddCellAlign(hints, element); + AddTableCellHints(hints, element); + + if (element.HasAttribute("nowrap")) + { + hints.Append("white-space: nowrap;"); + } + break; case "tr": AddDimension(hints, element, "height", "height", ignoreZero: false); AddColor(hints, element, "bgcolor", "background-color"); + AddBackground(hints, element); + AddCellAlign(hints, element); break; case "thead": case "tbody": case "tfoot": AddColor(hints, element, "bgcolor", "background-color"); + AddBackground(hints, element); + AddCellAlign(hints, element); break; case "col": case "colgroup": + AddDimension(hints, element, "width", "width", ignoreZero: false); + break; case "hr": AddDimension(hints, element, "width", "width", ignoreZero: false); + AddRuleHints(hints, element); break; case "body": AddColor(hints, element, "bgcolor", "background-color"); AddColor(hints, element, "text", "color"); + AddBackground(hints, element); + AddLength(hints, element, "marginheight", "margin-top"); + AddLength(hints, element, "marginheight", "margin-bottom"); + AddLength(hints, element, "marginwidth", "margin-left"); + AddLength(hints, element, "marginwidth", "margin-right"); + AddLength(hints, element, "topmargin", "margin-top"); + AddLength(hints, element, "bottommargin", "margin-bottom"); + AddLength(hints, element, "leftmargin", "margin-left"); + AddLength(hints, element, "rightmargin", "margin-right"); break; case "font": AddColor(hints, element, "color", "color"); + AddFontHints(hints, element); + break; + case "div": + AddBlockAlign(hints, element, moveBlocks: true); + break; + case "p": + case "h1": + case "h2": + case "h3": + case "h4": + case "h5": + case "h6": + AddBlockAlign(hints, element, moveBlocks: false); + break; + case "ul": + case "ol": + case "li": + AddListType(hints, element); break; } return hints.Length > 0 ? hints.ToString() : null; } - private static Boolean HasAttributes(this IElement element) => element.Attributes.Length > 0; + /// + /// The rules of the quirks mode sheet (HTML 15.3.10, 15.3.13), which come before the hints. + /// + private static void AddQuirks(StringBuilder hints, IElement element) + { + switch (element.LocalName) + { + case "table": + hints.Append("white-space: normal; line-height: normal; font-weight: normal; font-size: medium; font-variant: normal; font-style: normal; text-align: start;"); + AddColor(hints, element.Owner!.Body ?? element, "text", "color"); + break; + case "form": + hints.Append("margin-bottom: 1em;"); + break; + case "textarea": + case "input" when !element.GetAttribute("type").Isi("image"): + hints.Append("box-sizing: border-box;"); + break; + case "img" when element.GetAttribute("align").Isi("left"): + hints.Append("margin-right: 3px;"); + break; + case "img" when element.GetAttribute("align").Isi("right"): + hints.Append("margin-left: 3px;"); + break; + } + } + + /// + /// A whole number of pixels, or a percentage, as the property. + /// + private static void AddLength(StringBuilder hints, IElement element, String attribute, String property) + { + var length = ParseLength(element.GetAttribute(attribute)); + + if (length is not null) + { + hints.Append(property).Append(": ").Append(length).Append(';'); + } + } + + private static String? ParseLength(String? value) + { + value = value?.Trim(); + + if (String.IsNullOrEmpty(value)) + { + return null; + } + + var index = 0; + + while (index < value!.Length && value[index].IsDigit()) + { + index++; + } + + if (index == 0) + { + return null; + } + + return value.Substring(0, index) + (index < value.Length && value[index] == Symbols.Percent ? "%" : "px"); + } + + private static void AddBackground(StringBuilder hints, IElement element) + { + var value = element.GetAttribute("background")?.Trim(); + + if (value is { Length: > 0 } && value.IndexOfAny(new[] { '"', '\\', '\n', ';', '{', '}' }) < 0) + { + hints.Append("background-image: url(\"").Append(value).Append("\");"); + } + } + + private static void AddTableCellHints(StringBuilder hints, IElement cell) + { + var table = cell.ParentElement; + + while (table is not null && table.LocalName != "table") + { + table = table.ParentElement; + } + + if (table is null) + { + return; + } + + + // the attribute only knows pixels, whatever follows the number + if (ParseLength(table.GetAttribute("cellpadding")) is { } padding) + { + hints.Append("padding: ").Append(padding.TrimEnd('%', 'p', 'x')).Append("px;"); + } + + if (table.HasAttribute("border") && ParseLength(table.GetAttribute("border")) is not ("0px" or "0%")) + { + hints.Append("border: 1px inset ").Append(GetBorderColor(table)).Append(';'); + } + } + + private static void AddTableBorder(StringBuilder hints, IElement table) + { + if (table.HasAttribute("border")) + { + var length = ParseLength(table.GetAttribute("border")) ?? "1px"; + hints.Append("border: ").Append(length.EndsWith("%") ? "1px" : length).Append(" outset ").Append(GetBorderColor(table)).Append(';'); + } + } + + private static String GetBorderColor(IElement table) + { + var color = table.GetAttribute("bordercolor")?.Trim(); + return color is { Length: > 0 } && color.IndexOfAny(new[] { ';', '{', '}', '!' }) < 0 ? color : "gray"; + } + + private static void AddTableAlign(StringBuilder hints, IElement table) + { + switch (table.GetAttribute("align")?.Trim().ToLowerInvariant()) + { + case "left": + hints.Append("float: left;"); + break; + case "right": + hints.Append("float: right;"); + break; + case "center": + case "middle": + hints.Append("margin-left: auto; margin-right: auto;"); + break; + } + } + + private static void AddCellAlign(StringBuilder hints, IElement element) + { + AddBlockAlign(hints, element, moveBlocks: true); + var valign = element.GetAttribute("valign")?.Trim().ToLowerInvariant(); + + if (valign is "top" or "middle" or "bottom" or "baseline") + { + hints.Append("vertical-align: ").Append(valign).Append(';'); + } + } + + private static void AddBlockAlign(StringBuilder hints, IElement element, Boolean moveBlocks) + { + var prefix = moveBlocks ? "-webkit-" : String.Empty; + + switch (element.GetAttribute("align")?.Trim().ToLowerInvariant()) + { + case "left": + hints.Append("text-align: ").Append(prefix).Append("left;"); + break; + case "right": + hints.Append("text-align: ").Append(prefix).Append("right;"); + break; + case "center": + case "middle": + hints.Append("text-align: ").Append(prefix).Append("center;"); + break; + case "justify": + hints.Append("text-align: justify;"); + break; + } + } + + private static void AddImageSpacing(StringBuilder hints, IElement element) + { + AddLength(hints, element, "hspace", "margin-left"); + AddLength(hints, element, "hspace", "margin-right"); + AddLength(hints, element, "vspace", "margin-top"); + AddLength(hints, element, "vspace", "margin-bottom"); + + if (element.LocalName != "iframe" && ParseLength(element.GetAttribute("border")) is { } border && !border.EndsWith("%")) + { + hints.Append("border: ").Append(border).Append(" solid;"); + } + } + + private static void AddImageAlign(StringBuilder hints, IElement element) + { + switch (element.GetAttribute("align")?.Trim().ToLowerInvariant()) + { + case "left": + hints.Append("float: left;"); + break; + case "right": + hints.Append("float: right;"); + break; + case "top": + hints.Append("vertical-align: top;"); + break; + case "bottom": + case "baseline": + hints.Append("vertical-align: baseline;"); + break; + case "middle": + hints.Append("vertical-align: -webkit-baseline-middle;"); + break; + case "absmiddle": + hints.Append("vertical-align: middle;"); + break; + case "texttop": + hints.Append("vertical-align: text-top;"); + break; + case "absbottom": + hints.Append("vertical-align: bottom;"); + break; + } + } + + private static void AddRuleHints(StringBuilder hints, IElement rule) + { + switch (rule.GetAttribute("align")?.Trim().ToLowerInvariant()) + { + case "left": + hints.Append("margin-left: 0; margin-right: auto;"); + break; + case "right": + hints.Append("margin-left: auto; margin-right: 0;"); + break; + case "center": + hints.Append("margin-left: auto; margin-right: auto;"); + break; + } + + if (rule.HasAttribute("color")) + { + hints.Append("border-style: solid;"); + AddColor(hints, rule, "color", "color"); + AddColor(hints, rule, "color", "background-color"); + } + else if (rule.HasAttribute("noshade")) + { + hints.Append("border-style: solid; background-color: gray; border-color: gray;"); + } + + if (Int32.TryParse(rule.GetAttribute("size")?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var size) && size > 0) + { + // the 1px border on either side is part of its size + hints.Append(size == 1 ? "border-bottom-width: 0; height: 0;" : $"height: {size - 2}px;"); + } + } + + private static void AddFontHints(StringBuilder hints, IElement font) + { + var size = font.GetAttribute("size")?.Trim(); + + if (size is { Length: > 0 }) + { + var isRelative = size[0] == '+' || size[0] == '-'; + + if (Int32.TryParse(isRelative ? size.Substring(1) : size, NumberStyles.None, CultureInfo.InvariantCulture, out var number)) + { + var level = Math.Min(7, Math.Max(1, !isRelative ? number : size[0] == '+' ? 3 + number : 3 - number)); + hints.Append("font-size: ").Append(FontSizes[level - 1]).Append(';'); + } + } + + var face = font.GetAttribute("face")?.Trim(); + + if (face is { Length: > 0 } && face.IndexOfAny(new[] { ';', '{', '}', '!', '\\' }) < 0) + { + hints.Append("font-family: ").Append(face).Append(';'); + } + } + + // the sizes of the legacy font size attribute (HTML 15.3.4) + private static readonly String[] FontSizes = { "x-small", "small", "medium", "large", "x-large", "xx-large", "48px" }; + + private static void AddListType(StringBuilder hints, IElement element) + { + var value = element.GetAttribute("type")?.Trim(); + var type = value switch + { + "1" => "decimal", + "a" => "lower-alpha", + "A" => "upper-alpha", + "i" => "lower-roman", + "I" => "upper-roman", + _ => value?.ToLowerInvariant() is "circle" or "disc" or "square" or "none" ? value.ToLowerInvariant() : null, + }; + + if (type is not null) + { + hints.Append("list-style-type: ").Append(type).Append(';'); + } + } /// /// Maps a dimension value (e.g. "100" or "50%") to the property (HTML 2.4.4.4). diff --git a/src/AngleSharp.Css/Dom/TextAlign.cs b/src/AngleSharp.Css/Dom/TextAlign.cs index e2bb8d2c..db787967 100644 --- a/src/AngleSharp.Css/Dom/TextAlign.cs +++ b/src/AngleSharp.Css/Dom/TextAlign.cs @@ -40,5 +40,17 @@ public enum TextAlign: byte /// Similar to inherit, but the values start and end are calculated according to the parent's direction and are replaced by the appropriate left or right value. /// MatchParent, + /// + /// Centers the content, and the block-level boxes in it (-webkit-center). + /// + WebkitCenter, + /// + /// Aligns the content, and the block-level boxes in it, to the left (-webkit-left). + /// + WebkitLeft, + /// + /// Aligns the content, and the block-level boxes in it, to the right (-webkit-right). + /// + WebkitRight } } \ No newline at end of file diff --git a/src/AngleSharp.Css/Parser/CssBuilder.cs b/src/AngleSharp.Css/Parser/CssBuilder.cs index d412913d..3d91e52e 100644 --- a/src/AngleSharp.Css/Parser/CssBuilder.cs +++ b/src/AngleSharp.Css/Parser/CssBuilder.cs @@ -863,6 +863,11 @@ public void CreateDeclarationWith(ICssStyleSheet owner, ICssProperties propertie value = ResolveRelativeUrls(owner, value); } + if ((owner?.OwnerNode?.Owner ?? _context.Active)?.CompatMode == "BackCompat") + { + value = ApplyQuirks(name, value); + } + properties.SetProperty(name, value, important ? CssKeywords.Important : null); } } @@ -889,6 +894,31 @@ public void CreateDeclarationWith(ICssStyleSheet owner, ICssProperties propertie #region Helpers + /// + /// The quirks mode lets some properties have lengths without a unit and colors without a + /// hash (Quirks Mode Standard 3.3, 3.4). + /// + private String ApplyQuirks(String name, String value) + { + var isNumbers = Regex.IsMatch(value, @"^\s*[+-]?(\d+\.?\d*|\.\d+)(\s+[+-]?(\d+\.?\d*|\.\d+))*\s*$"); + var isHexColor = Regex.IsMatch(value, @"^\s*([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\s*$"); + + if ((isNumbers || isHexColor) && _context.CreateProperty(name) is CssProperty property) + { + if (isNumbers && property.CanBeUnitless) + { + return Regex.Replace(value, @"[+-]?(\d+\.?\d*|\.\d+)", "$0px"); + } + + if (isHexColor && property.CanBeHashless) + { + return "#" + value.Trim(); + } + } + + return value; + } + private void JumpToEnd(ref CssToken current) { while (current.IsNot(CssTokenType.EndOfFile, CssTokenType.Semicolon)) diff --git a/src/AngleSharp.Css/Parser/Micro/UnitParser.cs b/src/AngleSharp.Css/Parser/Micro/UnitParser.cs index 3353674f..dc492ba6 100644 --- a/src/AngleSharp.Css/Parser/Micro/UnitParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/UnitParser.cs @@ -65,6 +65,7 @@ public static ICssValue ParseBorderWidth(this StringSource source) => /// public static ICssValue ParseLineWidth(this StringSource source) => source.ParseLengthOrCalc() ?? + source.ParseMath() ?? source.ParseConstant(Map.BorderWidths); /// @@ -264,7 +265,7 @@ public static ICssValue ParseTrackBreadth(this StringSource source, Boolean flex } source.BackTo(pos); - return source.ParseCalc(); + return (ICssValue)source.ParseCalc() ?? source.ParseMath(); } /// @@ -609,7 +610,7 @@ private static ICssValue OrCalc(this T? value, StringSource source) return value.Value; } - return source.ParseCalc(); + return (ICssValue)source.ParseCalc() ?? source.ParseMath(); } } } diff --git a/src/AngleSharp.Css/ValueConverters.cs b/src/AngleSharp.Css/ValueConverters.cs index 2eded201..5b066089 100644 --- a/src/AngleSharp.Css/ValueConverters.cs +++ b/src/AngleSharp.Css/ValueConverters.cs @@ -270,7 +270,10 @@ static class ValueConverters WithAny( Or( Assign(CssKeywords.Light, CssKeywords.Light), - Assign(CssKeywords.Dark, CssKeywords.Dark) + Assign(CssKeywords.Dark, CssKeywords.Dark), + Assign(CssKeywords.Only, CssKeywords.Only), + // the name of a scheme this does not know, which is ignored + IdentifierConverter ) ).Many()); diff --git a/src/AngleSharp.Css/Values/Composites/CssShadowValue.cs b/src/AngleSharp.Css/Values/Composites/CssShadowValue.cs index adc09d00..a2e6274d 100644 --- a/src/AngleSharp.Css/Values/Composites/CssShadowValue.cs +++ b/src/AngleSharp.Css/Values/Composites/CssShadowValue.cs @@ -148,7 +148,8 @@ ICssValue ICssValue.Compute(ICssComputeContext context) var offsetY = _offsetY.Compute(context); var blurRadius = _blurRadius?.Compute(context); var spreadRadius = _spreadRadius?.Compute(context); - var color = (CssColorValue)((ICssValue)_color).Compute(context); + // a shadow without a color has the one of the text + var color = _color is { } own ? (CssColorValue?)(CssColorValue)((ICssValue)own).Compute(context) : null; return new CssShadowValue(_inset, offsetX, offsetY, blurRadius, spreadRadius, color); }