From c10002ca40b09ef202d2077cf87390d8c07809e5 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 11:16:18 +0100 Subject: [PATCH 01/12] Added typed OM #276 --- CHANGELOG.md | 6 + docs/README.md | 1 + docs/general/09-Typed-OM.md | 77 +++ src/AngleSharp.Css.Docs/package.json | 2 +- .../TypedOm/NumericValueTests.cs | 329 +++++++++++ .../TypedOm/ReificationTests.cs | 182 ++++++ .../TypedOm/StylePropertyMapTests.cs | 253 +++++++++ .../TypedOm/TransformValueTests.cs | 147 +++++ .../TypedOm/UnparsedValueTests.cs | 75 +++ src/AngleSharp.Css/Dom/CssHelpers.Units.cs | 517 ++++++++++++++++++ src/AngleSharp.Css/Dom/CssHelpers.cs | 2 +- .../Dom/Internal/CssStyleDeclaration.cs | 19 + src/AngleSharp.Css/TypedOm/CssImageValue.cs | 26 + src/AngleSharp.Css/TypedOm/CssKeywordValue.cs | 53 ++ src/AngleSharp.Css/TypedOm/CssMathClamp.cs | 78 +++ src/AngleSharp.Css/TypedOm/CssMathInvert.cs | 71 +++ src/AngleSharp.Css/TypedOm/CssMathMax.cs | 54 ++ src/AngleSharp.Css/TypedOm/CssMathMin.cs | 54 ++ src/AngleSharp.Css/TypedOm/CssMathNegate.cs | 66 +++ src/AngleSharp.Css/TypedOm/CssMathOperator.cs | 49 ++ src/AngleSharp.Css/TypedOm/CssMathProduct.cs | 96 ++++ src/AngleSharp.Css/TypedOm/CssMathSum.cs | 89 +++ src/AngleSharp.Css/TypedOm/CssMathValue.cs | 127 +++++ .../TypedOm/CssMatrixComponent.cs | 83 +++ src/AngleSharp.Css/TypedOm/CssNumericArray.cs | 44 ++ .../TypedOm/CssNumericBaseType.cs | 49 ++ src/AngleSharp.Css/TypedOm/CssNumericType.cs | 339 ++++++++++++ src/AngleSharp.Css/TypedOm/CssNumericValue.cs | 446 +++++++++++++++ src/AngleSharp.Css/TypedOm/CssPerspective.cs | 73 +++ .../TypedOm/CssPositionValue.cs | 65 +++ src/AngleSharp.Css/TypedOm/CssRotate.cs | 135 +++++ src/AngleSharp.Css/TypedOm/CssScale.cs | 83 +++ src/AngleSharp.Css/TypedOm/CssSkew.cs | 78 +++ src/AngleSharp.Css/TypedOm/CssSkewX.cs | 62 +++ src/AngleSharp.Css/TypedOm/CssSkewY.cs | 62 +++ src/AngleSharp.Css/TypedOm/CssStyleValue.cs | 89 +++ .../TypedOm/CssStyleValueReifier.cs | 400 ++++++++++++++ src/AngleSharp.Css/TypedOm/CssSumValue.cs | 144 +++++ .../TypedOm/CssTransformComponent.cs | 108 ++++ .../TypedOm/CssTransformValue.cs | 96 ++++ src/AngleSharp.Css/TypedOm/CssTranslate.cs | 83 +++ .../TypedOm/CssTypedOmExtensions.cs | 82 +++ src/AngleSharp.Css/TypedOm/CssUnitValue.cs | 85 +++ src/AngleSharp.Css/TypedOm/CssUnits.cs | 194 +++++++ .../TypedOm/CssUnparsedValue.cs | 331 +++++++++++ .../TypedOm/CssUnsupportedValue.cs | 28 + .../TypedOm/CssVariableReferenceValue.cs | 63 +++ .../ElementComputedStyleMapExtensions.cs | 28 + .../TypedOm/ElementStyleMapExtensions.cs | 25 + .../TypedOm/IStylePropertyMap.cs | 65 +++ .../TypedOm/IStylePropertyMapReadOnly.cs | 49 ++ .../TypedOm/StylePropertyMap.cs | 121 ++++ .../TypedOm/StylePropertyMapReadOnly.cs | 133 +++++ .../TypedOm/StyleRuleStyleMapExtensions.cs | 22 + .../TypedOm/TypedOmProperties.cs | 61 +++ src/Directory.Build.props | 2 +- 56 files changed, 6098 insertions(+), 3 deletions(-) create mode 100644 docs/general/09-Typed-OM.md create mode 100644 src/AngleSharp.Css.Tests/TypedOm/NumericValueTests.cs create mode 100644 src/AngleSharp.Css.Tests/TypedOm/ReificationTests.cs create mode 100644 src/AngleSharp.Css.Tests/TypedOm/StylePropertyMapTests.cs create mode 100644 src/AngleSharp.Css.Tests/TypedOm/TransformValueTests.cs create mode 100644 src/AngleSharp.Css.Tests/TypedOm/UnparsedValueTests.cs create mode 100644 src/AngleSharp.Css/Dom/CssHelpers.Units.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssImageValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssKeywordValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathClamp.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathInvert.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathMax.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathMin.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathNegate.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathOperator.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathProduct.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathSum.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMathValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssMatrixComponent.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssNumericArray.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssNumericBaseType.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssNumericType.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssNumericValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssPerspective.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssPositionValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssRotate.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssScale.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssSkew.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssSkewX.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssSkewY.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssStyleValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssSumValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssTransformComponent.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssTransformValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssTranslate.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssUnitValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssUnits.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssUnparsedValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssUnsupportedValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/CssVariableReferenceValue.cs create mode 100644 src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs create mode 100644 src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs create mode 100644 src/AngleSharp.Css/TypedOm/IStylePropertyMap.cs create mode 100644 src/AngleSharp.Css/TypedOm/IStylePropertyMapReadOnly.cs create mode 100644 src/AngleSharp.Css/TypedOm/StylePropertyMap.cs create mode 100644 src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs create mode 100644 src/AngleSharp.Css/TypedOm/StyleRuleStyleMapExtensions.cs create mode 100644 src/AngleSharp.Css/TypedOm/TypedOmProperties.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index cb80d2e8..af27d378 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 1.5.0 + +Released on tbd. + +- Added the CSS Typed OM (#276) in the `AngleSharp.Css.TypedOm` namespace: typed values (`CssUnitValue`, `CssKeywordValue`, `CssUnparsedValue`, the math values such as `CssMathSum`, `CssTransformValue`, `CssPositionValue`, `CssImageValue`) with unit-aware arithmetic and conversions, the `CSS.px()`-style factories on `CssHelpers`, and style property maps over declared (`attributeStyleMap`, `styleMap` of a rule) and computed (`computedStyleMap()`) styles, which read from and write to the existing declarations + # 1.4.2 Released on Friday, November 13 2026. diff --git a/docs/README.md b/docs/README.md index 5b458978..bc95429d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ We have more detailed information regarding the following subjects: - [Provided Services](general/06-Provided-Services.md) - [Supported At-Rules](general/07-Supported-At-Rules.md) - [Supported Declarations](general/08-Supported-Declarations.md) +- [Typed OM](general/09-Typed-OM.md) ## Tutorials diff --git a/docs/general/09-Typed-OM.md b/docs/general/09-Typed-OM.md new file mode 100644 index 00000000..bbcc91ee --- /dev/null +++ b/docs/general/09-Typed-OM.md @@ -0,0 +1,77 @@ +--- +title: "Typed OM" +section: "AngleSharp.Css" +--- +# Typed OM + +AngleSharp.Css implements the [CSS Typed Object Model Level 1](https://www.w3.org/TR/css-typed-om-1/) in the `AngleSharp.Css.TypedOm` namespace. Instead of strings, values are given as objects: a length is a `CssUnitValue` with a value and a unit, a `calc()` is a tree of math values, and a `transform` is a list of transform components. + +The Typed OM is a view of the CSSOM, not a copy of it. Typed values are created (reified) from the values the CSSOM already parsed whenever they are requested, and values written through a style map are validated and stored by the converter of the property, exactly as `SetProperty` does. The existing CSSOM interfaces are unchanged. + +## Style Property Maps + +```cs +using AngleSharp.Css.Dom; +using AngleSharp.Css.TypedOm; + +var element = document.QuerySelector("div"); + +// the inline style, i.e., the style attribute (attributeStyleMap) +var map = element.GetAttributeStyleMap(); +map.Set("width", CssHelpers.Px(100)); +map.Set("height", "calc(100% - 2em)"); +var width = (CssUnitValue)map.Get("width"); // 100, "px" + +// the declarations of a style rule (styleMap) +var ruleMap = styleRule.GetStyleMap(); + +// the computed style (computedStyleMap()), which is read-only +var computed = element.ComputedStyleMap(); +var fontSize = computed.Get("font-size"); +``` + +- `Get` gives the (first) value, `GetAll` all values of a list-valued property (e.g., the images of `background-image`), `Has` and `Size` tell what is declared. +- `Set` and `Append` take typed values or CSS text. Multiple values (and `Append`) are only allowed for list-valued properties. An invalid value throws an `ArgumentException` (the `TypeError` of the specification) and leaves the declarations unchanged. +- The priority (`!important`) of a declaration is kept when it is set. +- `GetStyleMap()` is available for any `ICssStyleDeclaration`, and `GetReadOnlyStyleMap()` gives a read-only view. + +## Values + +| CSS value | Typed value | +|-----------|-------------| +| `10px`, `50%`, `2`, `1s` | `CssUnitValue` | +| `calc()`, `min()`, `max()`, `clamp()` | `CssMathSum`, `CssMathProduct`, `CssMathNegate`, `CssMathInvert`, `CssMathMin`, `CssMathMax`, `CssMathClamp` | +| `auto`, `block`, `inherit` | `CssKeywordValue` | +| custom properties, values with `var()` | `CssUnparsedValue` (strings and `CssVariableReferenceValue`) | +| `transform` | `CssTransformValue` of `CssTranslate`, `CssRotate`, `CssScale`, `CssSkew`, `CssSkewX`, `CssSkewY`, `CssPerspective`, `CssMatrixComponent` | +| `url()`, gradients | `CssImageValue` | +| positions, e.g., of `object-position` | `CssPositionValue` | +| anything else, e.g., colors or shorthands | `CssStyleValue` | + +A value without a more specific representation is a plain `CssStyleValue`, which only knows its serialization and can only be set for the property it was obtained for. + +Values are parsed with `CssStyleValue.Parse(property, text)` / `ParseAll`, or `CssNumericValue.Parse(text)` for numeric values. An `ICssProperty` or `ICssValue` of the CSSOM is turned into a typed value with `ToStyleValue()`. Every typed value is serialized with `ToString()`. + +## Numeric Values + +The factories of the `CSS` namespace are on `CssHelpers`, e.g., `CssHelpers.Px(10)`, `CssHelpers.Percent(50)`, or `CssHelpers.Number(2)`. A `Double` converts implicitly to a number. + +```cs +var a = CssHelpers.Px(10).Add(CssHelpers.Px(5)); // 15px +var b = CssHelpers.Px(10).Add(CssHelpers.Em(1)); // calc(10px + 1em) +var c = CssHelpers.Px(10) * 2; // 20px +var d = CssHelpers.In(1).To("px"); // 96px +var e = CssNumericValue.Parse("calc(1in + 1em + 1px)").ToSum("px", "em"); // calc(97px + 1em) +var t = b.Type(); // length: 1 +``` + +- `Add`, `Sub`, `Mul`, `Div`, `Min`, and `Max` give a `CssUnitValue` when the units allow it, otherwise a math value. Incompatible types (e.g., a length and a time) throw an `ArgumentException`. +- `To` and `ToSum` convert between compatible absolute units (lengths, angles, times, frequencies, resolutions). Relative units such as `em`, `%`, or `vw` are kept as they are, as they can only be resolved during layout. +- `Equals` compares values structurally. +- `CssTransformValue.ToMatrix()` gives the `TransformMatrix` of a transform with absolute units. + +## Limitations + +- The computed style map is a snapshot of the computed style at the time of the call. +- Colors and other values beyond the Typed OM Level 1 are given as plain `CssStyleValue`. +- Registered custom properties (`@property`) are still given as `CssUnparsedValue`. diff --git a/src/AngleSharp.Css.Docs/package.json b/src/AngleSharp.Css.Docs/package.json index 514e8e1b..fb31480e 100644 --- a/src/AngleSharp.Css.Docs/package.json +++ b/src/AngleSharp.Css.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/css", - "version": "1.4.2", + "version": "1.5.0", "preview": true, "description": "The doclet for the AngleSharp.Css documentation.", "keywords": [ diff --git a/src/AngleSharp.Css.Tests/TypedOm/NumericValueTests.cs b/src/AngleSharp.Css.Tests/TypedOm/NumericValueTests.cs new file mode 100644 index 00000000..a4e6709d --- /dev/null +++ b/src/AngleSharp.Css.Tests/TypedOm/NumericValueTests.cs @@ -0,0 +1,329 @@ +#nullable disable +namespace AngleSharp.Css.Tests.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + + [TestFixture] + public class NumericValueTests + { + [Test] + public void UnitValuesSerializeWithTheirUnit() + { + Assert.AreEqual("10px", CssHelpers.Px(10).ToString()); + Assert.AreEqual("2", CssHelpers.Number(2).ToString()); + Assert.AreEqual("50%", CssHelpers.Percent(50).ToString()); + Assert.AreEqual("1.5em", CssHelpers.Em(1.5).ToString()); + Assert.AreEqual("2khz", CssHelpers.KHz(2).ToString()); + } + + [Test] + public void UnitIsNormalized() + { + var value = new CssUnitValue(1, "PX"); + Assert.AreEqual("px", value.Unit); + Assert.AreEqual("percent", new CssUnitValue(1, "%").Unit); + } + + [Test] + public void UnknownUnitIsRejected() + { + Assert.Throws(() => new CssUnitValue(1, "foo")); + } + + [Test] + public void TypeOfUnitValues() + { + Assert.AreEqual(1, CssHelpers.Px(1).Type().Length); + Assert.IsNull(CssHelpers.Px(1).Type().Angle); + Assert.AreEqual(1, CssHelpers.Deg(1).Type().Angle); + Assert.AreEqual(1, CssHelpers.Percent(1).Type().Percent); + Assert.AreEqual(1, CssHelpers.Fr(1).Type().Flex); + Assert.IsNull(CssHelpers.Number(1).Type().Length); + Assert.IsNull(CssHelpers.Number(1).Type().PercentHint); + } + + [Test] + public void AddingTheSameUnitsGivesAUnitValue() + { + var result = CssHelpers.Px(1).Add(CssHelpers.Px(2), CssHelpers.Px(3)); + Assert.IsInstanceOf(result); + Assert.AreEqual("6px", result.ToString()); + } + + [Test] + public void AddingDifferentUnitsGivesASum() + { + var result = CssHelpers.Px(1).Add(CssHelpers.Em(2)); + Assert.IsInstanceOf(result); + Assert.AreEqual("calc(1px + 2em)", result.ToString()); + Assert.AreEqual(1, result.Type().Length); + } + + [Test] + public void AddingAPercentageSetsThePercentHint() + { + var result = CssHelpers.Px(1).Add(CssHelpers.Percent(2)); + Assert.AreEqual("calc(1px + 2%)", result.ToString()); + Assert.AreEqual(1, result.Type().Length); + Assert.IsNull(result.Type().Percent); + Assert.AreEqual(CssNumericBaseType.Length, result.Type().PercentHint); + } + + [Test] + public void AddingIncompatibleTypesThrows() + { + Assert.Throws(() => CssHelpers.Px(1).Add(CssHelpers.Deg(1))); + Assert.Throws(() => CssHelpers.Px(1).Add(1)); + } + + [Test] + public void AddingASumFlattensIt() + { + var sum = CssHelpers.Px(1).Add(CssHelpers.Em(2)); + var result = sum.Add(CssHelpers.Vw(3)); + Assert.AreEqual("calc(1px + 2em + 3vw)", result.ToString()); + Assert.AreEqual(3, ((CssMathSum)result).Values.Length); + } + + [Test] + public void SubtractingNegatesUnitValuesDirectly() + { + // negating a unit value negates its value (CSS Typed OM 4.3.2) + var result = CssHelpers.Px(1).Sub(CssHelpers.Em(2)); + Assert.AreEqual("calc(1px + -2em)", result.ToString()); + Assert.IsInstanceOf(((CssMathSum)result).Values[1]); + } + + [Test] + public void SubtractingAMathValueGivesASumWithANegation() + { + var result = CssHelpers.Px(1).Sub(CssHelpers.Em(2).Mul(CssHelpers.Px(1)).Div(CssHelpers.Px(1))); + Assert.AreEqual("calc(1px - (2em * 1px / 1px))", result.ToString()); + Assert.IsInstanceOf(((CssMathSum)result).Values[1]); + Assert.IsInstanceOf(((CssMathSum)CssNumericValue.Parse("calc(1px - 2em)")).Values[1]); + } + + [Test] + public void SubtractingTheSameUnits() + { + Assert.AreEqual("-1px", CssHelpers.Px(1).Sub(CssHelpers.Px(2)).ToString()); + } + + [Test] + public void MultiplyingWithNumbersGivesAUnitValue() + { + Assert.AreEqual("6px", CssHelpers.Px(2).Mul(3).ToString()); + Assert.AreEqual("6", CssHelpers.Number(2).Mul(3).ToString()); + } + + [Test] + public void MultiplyingTwoDimensionsGivesAProduct() + { + var result = CssHelpers.Px(2).Mul(CssHelpers.Em(3)); + Assert.IsInstanceOf(result); + Assert.AreEqual("calc(2px * 3em)", result.ToString()); + Assert.AreEqual(2, result.Type().Length); + } + + [Test] + public void DividingByANumber() + { + Assert.AreEqual("5px", CssHelpers.Px(10).Div(2).ToString()); + } + + [Test] + public void DividingByADimensionGivesAProductWithAnInversion() + { + var result = CssHelpers.Px(1).Div(CssHelpers.Em(2)); + Assert.AreEqual("calc(1px / 2em)", result.ToString()); + Assert.IsNull(result.Type().Length); + } + + [Test] + public void DividingByZeroThrows() + { + Assert.Throws(() => CssHelpers.Px(1).Div(0)); + } + + [Test] + public void MinAndMaxOfTheSameUnits() + { + Assert.AreEqual("1px", CssHelpers.Px(1).Min(CssHelpers.Px(3)).ToString()); + Assert.AreEqual("3px", CssHelpers.Px(1).Max(CssHelpers.Px(3)).ToString()); + } + + [Test] + public void MinAndMaxOfDifferentUnits() + { + Assert.AreEqual("min(1px, 2em)", CssHelpers.Px(1).Min(CssHelpers.Em(2)).ToString()); + Assert.AreEqual("max(1px, 2em)", CssHelpers.Px(1).Max(CssHelpers.Em(2)).ToString()); + Assert.Throws(() => CssHelpers.Px(1).Min(CssHelpers.S(2))); + } + + [Test] + public void ClampSerializes() + { + var clamp = new CssMathClamp(CssHelpers.Px(1), CssHelpers.Em(2), CssHelpers.Px(3)); + Assert.AreEqual("clamp(1px, 2em, 3px)", clamp.ToString()); + Assert.AreEqual(CssMathOperator.Clamp, clamp.Operator); + Assert.Throws(() => new CssMathClamp(CssHelpers.Px(1), CssHelpers.Deg(2), CssHelpers.Px(3))); + } + + [Test] + public void EmptySumIsASyntaxError() + { + var ex = Assert.Throws(() => new CssMathSum()); + Assert.AreEqual((Int32)DomError.Syntax, ex.Code); + } + + [Test] + public void NestedExpressionsSerializeWithParentheses() + { + var sum = new CssMathSum(CssHelpers.Px(1), new CssMathProduct(CssHelpers.Em(2), 3)); + Assert.AreEqual("calc(1px + (2em * 3))", sum.ToString()); + Assert.AreEqual("calc(-1px)", new CssMathNegate(CssHelpers.Px(1)).ToString()); + Assert.AreEqual("calc(1 / 2px)", new CssMathInvert(CssHelpers.Px(2)).ToString()); + Assert.AreEqual("min(1px + 2em, 3px)", new CssMathMin(new CssMathSum(CssHelpers.Px(1), CssHelpers.Em(2)), CssHelpers.Px(3)).ToString()); + } + + [Test] + public void OperatorsMapToTheMethods() + { + var a = CssHelpers.Px(1); + var b = CssHelpers.Px(2); + Assert.AreEqual("3px", (a + b).ToString()); + Assert.AreEqual("-1px", (a - b).ToString()); + Assert.AreEqual("4px", (b * 2).ToString()); + Assert.AreEqual("0.5px", (a / 2).ToString()); + Assert.AreEqual("-1px", (-a).ToString()); + } + + [Test] + public void ConvertingAbsoluteUnits() + { + Assert.AreEqual(96.0, CssHelpers.In(1).To("px").Value, 1e-9); + Assert.AreEqual(1.0, CssHelpers.Px(96).To("in").Value, 1e-9); + Assert.AreEqual(10.0, CssHelpers.Cm(1).To("mm").Value, 1e-9); + Assert.AreEqual(180.0, CssHelpers.Turn(0.5).To("deg").Value, 1e-9); + Assert.AreEqual(Math.PI, CssHelpers.Deg(180).To("rad").Value, 1e-9); + Assert.AreEqual(1500.0, CssHelpers.S(1.5).To("ms").Value, 1e-9); + Assert.AreEqual(2000.0, CssHelpers.KHz(2).To("hz").Value, 1e-9); + Assert.AreEqual(1.0, CssHelpers.Dpi(96).To("dppx").Value, 1e-9); + } + + [Test] + public void ConvertingRelativeUnitsThrows() + { + Assert.Throws(() => CssHelpers.Em(1).To("px")); + Assert.Throws(() => CssHelpers.Px(1).To("deg")); + Assert.Throws(() => CssHelpers.Px(1).Add(CssHelpers.Em(1)).To("px")); + } + + [Test] + public void ConvertingToAnUnknownUnitIsASyntaxError() + { + Assert.Throws(() => CssHelpers.Px(1).To("foo")); + } + + [Test] + public void ConvertingMathExpressions() + { + Assert.AreEqual(97.0, CssNumericValue.Parse("calc(1px + 1in)").To("px").Value, 1e-9); + Assert.AreEqual(1.5, CssNumericValue.Parse("calc(1s + 500ms)").To("s").Value, 1e-9); + Assert.AreEqual(5.0, CssNumericValue.Parse("calc(10px / 2)").To("px").Value, 1e-9); + Assert.AreEqual(1.0, CssNumericValue.Parse("min(1px, 2px, 1in)").To("px").Value, 1e-9); + Assert.AreEqual(2.0, CssNumericValue.Parse("clamp(1px, 2px, 3px)").To("px").Value, 1e-9); + Assert.AreEqual(3.0, CssNumericValue.Parse("clamp(1px, 5px, 3px)").To("px").Value, 1e-9); + } + + [Test] + public void ToSumWithoutUnitsGivesTheCanonicalUnits() + { + var sum = CssNumericValue.Parse("calc(1in + 1em + 1px)").ToSum(); + Assert.AreEqual("calc(1em + 97px)", sum.ToString()); + } + + [Test] + public void ToSumWithUnits() + { + var sum = CssNumericValue.Parse("calc(1in + 1em + 1px)").ToSum("px", "em"); + Assert.AreEqual("calc(97px + 1em)", sum.ToString()); + Assert.Throws(() => CssNumericValue.Parse("calc(1in + 1em)").ToSum("px")); + } + + [Test] + public void ToSumOfAProductOfUnitsThrows() + { + Assert.Throws(() => CssHelpers.Px(1).Mul(CssHelpers.Px(1)).ToSum()); + } + + [Test] + public void StructuralEquality() + { + Assert.IsTrue(CssHelpers.Px(1).Equals(CssHelpers.Px(1))); + Assert.IsFalse(CssHelpers.Px(1).Equals(CssHelpers.Px(2))); + Assert.IsFalse(CssHelpers.Px(1).Equals(CssHelpers.Em(1))); + Assert.IsTrue(CssNumericValue.Parse("calc(1px + 2em)").Equals(CssHelpers.Px(1).Add(CssHelpers.Em(2)))); + Assert.IsTrue(CssHelpers.Px(1).Equals(CssHelpers.Px(1), CssHelpers.Px(1))); + Assert.IsFalse(CssHelpers.Px(1).Equals(CssHelpers.Px(1), CssHelpers.Px(2))); + Assert.AreEqual(CssHelpers.Px(1).GetHashCode(), CssHelpers.Px(1).GetHashCode()); + } + + [TestCase("10px")] + [TestCase("-2.5em")] + [TestCase("50%")] + [TestCase("3")] + [TestCase("45deg")] + [TestCase("calc(1px + 2em)")] + [TestCase("calc(1px - 2em)")] + [TestCase("calc(2 * 1em)")] + [TestCase("calc(1px / 2)")] + [TestCase("calc(1px + (2em * 3))")] + [TestCase("calc((1px + 2em) * 3)")] + [TestCase("min(1px, 2em)")] + [TestCase("max(1px, 2em, 3vw)")] + [TestCase("clamp(1px, 2em, 3px)")] + [TestCase("min(1px + 2em, 3px)")] + public void ParseRoundTrips(String text) + { + Assert.AreEqual(text, CssNumericValue.Parse(text).ToString()); + } + + [Test] + public void ParseKeepsTheStructure() + { + Assert.IsInstanceOf(CssNumericValue.Parse("10px")); + Assert.IsInstanceOf(CssNumericValue.Parse("calc(1px + 2px)")); + Assert.IsInstanceOf(CssNumericValue.Parse("calc(1px * 2)")); + Assert.IsInstanceOf(CssNumericValue.Parse("min(1px, 2em)")); + Assert.IsInstanceOf(CssNumericValue.Parse("max(1px, 2em)")); + Assert.IsInstanceOf(CssNumericValue.Parse("clamp(1px, 2em, 3px)")); + } + + [Test] + public void ParseOfCalcAroundASingleValueIsASum() + { + var value = CssNumericValue.Parse("calc(10px)"); + Assert.IsInstanceOf(value); + Assert.AreEqual("calc(10px)", value.ToString()); + } + + [Test] + public void ParseOfInvalidTextIsASyntaxError() + { + Assert.Throws(() => CssNumericValue.Parse("foo")); + Assert.Throws(() => CssNumericValue.Parse("10px 20px")); + Assert.Throws(() => CssNumericValue.Parse("calc(1px +)")); + } + + [Test] + public void ParseOfIncompatibleTypesIsASyntaxError() + { + Assert.Throws(() => CssNumericValue.Parse("calc(1px + 1s)")); + } + } +} diff --git a/src/AngleSharp.Css.Tests/TypedOm/ReificationTests.cs b/src/AngleSharp.Css.Tests/TypedOm/ReificationTests.cs new file mode 100644 index 00000000..21347401 --- /dev/null +++ b/src/AngleSharp.Css.Tests/TypedOm/ReificationTests.cs @@ -0,0 +1,182 @@ +#nullable disable +namespace AngleSharp.Css.Tests.TypedOm +{ + using AngleSharp.Css.TypedOm; + using NUnit.Framework; + using System; + using static CssConstructionFunctions; + + [TestFixture] + public class ReificationTests + { + [Test] + public void LengthIsAUnitValue() + { + var value = CssStyleValue.Parse("width", "10px"); + Assert.IsInstanceOf(value); + Assert.AreEqual(10.0, ((CssUnitValue)value).Value); + Assert.AreEqual("px", ((CssUnitValue)value).Unit); + } + + [Test] + public void PercentageIsAUnitValue() + { + var value = (CssUnitValue)CssStyleValue.Parse("width", "50%"); + Assert.AreEqual("percent", value.Unit); + Assert.AreEqual("50%", value.ToString()); + } + + [Test] + public void UnitlessZeroIsAPixelValue() + { + var value = (CssUnitValue)CssStyleValue.Parse("width", "0"); + Assert.AreEqual(0.0, value.Value); + Assert.AreEqual("px", value.Unit); + } + + [Test] + public void NumbersAndIntegersAreUnitValues() + { + Assert.AreEqual("number", ((CssUnitValue)CssStyleValue.Parse("opacity", "0.5")).Unit); + Assert.AreEqual("number", ((CssUnitValue)CssStyleValue.Parse("z-index", "3")).Unit); + Assert.AreEqual("s", ((CssUnitValue)CssStyleValue.Parse("transition-duration", "2s")).Unit); + } + + [Test] + public void KeywordsAreKeywordValues() + { + Assert.AreEqual("auto", ((CssKeywordValue)CssStyleValue.Parse("width", "auto")).Value); + Assert.AreEqual("block", ((CssKeywordValue)CssStyleValue.Parse("display", "block")).Value); + Assert.AreEqual("bold", ((CssKeywordValue)CssStyleValue.Parse("font-weight", "bold")).Value); + Assert.AreEqual("none", ((CssKeywordValue)CssStyleValue.Parse("transform", "none")).Value); + } + + [Test] + public void CssWideKeywordsAreKeywordValues() + { + Assert.AreEqual("inherit", ((CssKeywordValue)CssStyleValue.Parse("width", "inherit")).Value); + Assert.AreEqual("initial", ((CssKeywordValue)CssStyleValue.Parse("color", "initial")).Value); + Assert.AreEqual("unset", ((CssKeywordValue)CssStyleValue.Parse("display", "unset")).Value); + } + + [Test] + public void CalcIsAMathValue() + { + var value = CssStyleValue.Parse("width", "calc(10px + 5%)"); + Assert.IsInstanceOf(value); + Assert.AreEqual("calc(10px + 5%)", value.ToString()); + } + + [Test] + public void ComparisonFunctionsAreMathValues() + { + Assert.IsInstanceOf(CssStyleValue.Parse("width", "min(10px, 2em)")); + Assert.IsInstanceOf(CssStyleValue.Parse("width", "clamp(1px, 2em, 3px)")); + } + + [Test] + public void ImagesAreImageValues() + { + var values = CssStyleValue.ParseAll("background-image", "url(a.png), url(b.png)"); + Assert.AreEqual(2, values.Count); + Assert.IsInstanceOf(values[0]); + Assert.AreEqual("url(\"a.png\")", values[0].ToString()); + Assert.AreEqual("url(\"b.png\")", values[1].ToString()); + } + + [Test] + public void GradientsAreImageValues() + { + var value = CssStyleValue.Parse("background-image", "linear-gradient(red, blue)"); + Assert.IsInstanceOf(value); + } + + [Test] + public void ParseReturnsTheFirstOfAList() + { + var value = CssStyleValue.Parse("transition-duration", "1s, 2s"); + Assert.AreEqual("1s", value.ToString()); + Assert.AreEqual(2, CssStyleValue.ParseAll("transition-duration", "1s, 2s").Count); + } + + [Test] + public void PositionIsAPositionValue() + { + var value = CssStyleValue.Parse("object-position", "10px 20%"); + Assert.IsInstanceOf(value); + var position = (CssPositionValue)value; + Assert.AreEqual("10px", position.X.ToString()); + Assert.AreEqual("20%", position.Y.ToString()); + Assert.AreEqual("10px 20%", position.ToString()); + } + + [Test] + public void CustomPropertyIsAnUnparsedValue() + { + var value = CssStyleValue.Parse("--foo", "bar baz"); + Assert.IsInstanceOf(value); + Assert.AreEqual("bar baz", value.ToString()); + } + + [Test] + public void ValueWithAReferenceIsAnUnparsedValue() + { + var value = CssStyleValue.Parse("width", "var(--x)"); + Assert.IsInstanceOf(value); + var unparsed = (CssUnparsedValue)value; + Assert.AreEqual(1, unparsed.Length); + Assert.AreEqual("--x", ((CssVariableReferenceValue)unparsed[0]).Variable); + } + + [Test] + public void TransformIsATransformValue() + { + var value = CssStyleValue.Parse("transform", "translate(10px, 20px) rotate(45deg)"); + Assert.IsInstanceOf(value); + var transform = (CssTransformValue)value; + Assert.AreEqual(2, transform.Length); + Assert.IsInstanceOf(transform[0]); + Assert.IsInstanceOf(transform[1]); + } + + [Test] + public void ValuesWithoutATypedRepresentationAreStyleValues() + { + var color = CssStyleValue.Parse("color", "red"); + Assert.AreEqual(typeof(CssStyleValue), color.GetType().BaseType); + Assert.IsNotInstanceOf(color); + Assert.AreEqual("rgba(255, 0, 0, 1)", color.ToString()); + + var margin = CssStyleValue.Parse("margin", "1px 2px"); + Assert.AreEqual("1px 2px", margin.ToString()); + } + + [Test] + public void InvalidValuesThrow() + { + Assert.Throws(() => CssStyleValue.Parse("width", "red")); + } + + [Test] + public void UnknownPropertiesThrow() + { + Assert.Throws(() => CssStyleValue.Parse("foo-bar", "10px")); + } + + [Test] + public void PropertyNamesAreCaseInsensitive() + { + Assert.AreEqual("10px", CssStyleValue.Parse("WIDTH", "10px").ToString()); + } + + [Test] + public void ReifiesTheValueOfADeclaration() + { + var property = ParseDeclaration("width: calc(1px + 2em)"); + var value = property.ToStyleValue(); + Assert.IsInstanceOf(value); + Assert.AreEqual("calc(1px + 2em)", value.ToString()); + Assert.AreEqual("calc(1px + 2em)", property.RawValue.ToStyleValue("width").ToString()); + } + } +} diff --git a/src/AngleSharp.Css.Tests/TypedOm/StylePropertyMapTests.cs b/src/AngleSharp.Css.Tests/TypedOm/StylePropertyMapTests.cs new file mode 100644 index 00000000..3bf75834 --- /dev/null +++ b/src/AngleSharp.Css.Tests/TypedOm/StylePropertyMapTests.cs @@ -0,0 +1,253 @@ +#nullable disable +namespace AngleSharp.Css.Tests.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Parser; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Linq; + using static CssConstructionFunctions; + + [TestFixture] + public class StylePropertyMapTests + { + private static IElement CreateElement(String style) + { + var document = ParseDocument($"
"); + return document.GetElementById("target"); + } + + [Test] + public void GetsTheTypedValuesOfTheInlineStyle() + { + var element = CreateElement("width: 10px; background-image: url(a.png), url(b.png); --foo: bar"); + var map = element.GetAttributeStyleMap(); + + Assert.AreEqual("10px", ((CssUnitValue)map.Get("width")).ToString()); + Assert.AreEqual(2, map.GetAll("background-image").Count); + Assert.IsInstanceOf(map.Get("--foo")); + Assert.AreEqual(3, map.Size); + } + + [Test] + public void MissingPropertiesHaveNoValue() + { + var map = CreateElement("width: 10px").GetAttributeStyleMap(); + + Assert.IsFalse(map.Has("height")); + Assert.IsNull(map.Get("height")); + Assert.AreEqual(0, map.GetAll("height").Count); + Assert.IsTrue(map.Has("WIDTH")); + } + + [Test] + public void UnknownPropertiesThrow() + { + var map = CreateElement("width: 10px").GetAttributeStyleMap(); + Assert.Throws(() => map.Get("foo-bar")); + Assert.Throws(() => map.Set("foo-bar", CssHelpers.Px(1))); + } + + [Test] + public void IsTheSameObject() + { + var element = CreateElement("width: 10px"); + Assert.AreSame(element.GetAttributeStyleMap(), element.GetAttributeStyleMap()); + } + + [Test] + public void ReflectsChangesOfTheStyle() + { + var element = CreateElement("width: 10px"); + var map = element.GetAttributeStyleMap(); + element.GetStyle().SetProperty("width", "20em"); + Assert.AreEqual("20em", map.Get("width").ToString()); + } + + [Test] + public void SetUpdatesTheStyleAttribute() + { + var element = CreateElement("width: 10px"); + var map = element.GetAttributeStyleMap(); + map.Set("width", CssHelpers.Px(20).Add(CssHelpers.Em(1))); + + Assert.AreEqual("calc(20px + 1em)", element.GetStyle().GetPropertyValue("width")); + Assert.AreEqual("width: calc(20px + 1em)", element.GetAttribute("style")); + } + + [Test] + public void SetAcceptsText() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + map.Set("height", "5vh"); + + Assert.AreEqual("5vh", element.GetStyle().GetPropertyValue("height")); + Assert.IsInstanceOf(map.Get("height")); + } + + [Test] + public void SetOfAnInvalidValueThrowsAndKeepsTheStyle() + { + var element = CreateElement("width: 10px"); + var map = element.GetAttributeStyleMap(); + + Assert.Throws(() => map.Set("width", CssHelpers.Deg(1))); + Assert.Throws(() => map.Set("width", "red")); + Assert.AreEqual("10px", element.GetStyle().GetPropertyValue("width")); + } + + [Test] + public void SetOfMultipleValuesRequiresAListValuedProperty() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + + Assert.Throws(() => map.Set("width", CssHelpers.Px(1), CssHelpers.Px(2))); + map.Set("transition-duration", CssHelpers.S(1), CssHelpers.Ms(200)); + Assert.AreEqual("1s, 200ms", element.GetStyle().GetPropertyValue("transition-duration")); + } + + [Test] + public void AppendAddsToAListValuedProperty() + { + var element = CreateElement("background-image: url(a.png)"); + var map = element.GetAttributeStyleMap(); + map.Append("background-image", "url(b.png)"); + map.Append("background-image", map.Get("background-image")); + + Assert.AreEqual(3, map.GetAll("background-image").Count); + Assert.AreEqual("url(\"a.png\"), url(\"b.png\"), url(\"a.png\")", element.GetStyle().GetPropertyValue("background-image")); + } + + [Test] + public void AppendToAPropertyThatIsNotListValuedThrows() + { + var map = CreateElement("width: 10px").GetAttributeStyleMap(); + Assert.Throws(() => map.Append("width", CssHelpers.Px(1))); + } + + [Test] + public void ValuesWithoutATypedRepresentationOnlyFitTheirProperty() + { + var element = CreateElement("color: red"); + var map = element.GetAttributeStyleMap(); + var color = map.Get("color"); + + Assert.Throws(() => map.Set("background-color", color)); + map.Set("color", color); + Assert.AreEqual("rgba(255, 0, 0, 1)", element.GetStyle().GetPropertyValue("color")); + } + + [Test] + public void SetKeepsThePriority() + { + var element = CreateElement("width: 10px !important"); + var map = element.GetAttributeStyleMap(); + map.Set("width", CssHelpers.Px(20)); + + Assert.AreEqual("important", element.GetStyle().GetPropertyPriority("width")); + Assert.AreEqual("20px", element.GetStyle().GetPropertyValue("width")); + } + + [Test] + public void SetOfAShorthand() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + map.Set("margin", "1px 2px"); + + Assert.AreEqual("2px", element.GetStyle().GetPropertyValue("margin-left")); + Assert.AreEqual("1px 2px", map.Get("margin").ToString()); + Assert.AreEqual("2px", map.Get("margin-left").ToString()); + } + + [Test] + public void SetOfACustomProperty() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + map.Set("--foo", new CssUnparsedValue(new Object[] { "1px ", new CssVariableReferenceValue("--bar") })); + + Assert.AreEqual("1px var(--bar)", element.GetStyle().GetPropertyValue("--foo")); + Assert.Throws(() => map.Append("--foo", "2px")); + } + + [Test] + public void SetOfAReference() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + map.Set("width", new CssUnparsedValue(new Object[] { new CssVariableReferenceValue("--w") })); + + Assert.AreEqual("var(--w)", element.GetStyle().GetPropertyValue("width")); + } + + [Test] + public void DeleteAndClear() + { + var element = CreateElement("width: 10px; height: 20px"); + var map = element.GetAttributeStyleMap(); + + map.Delete("width"); + Assert.IsFalse(map.Has("width")); + Assert.AreEqual("20px", element.GetStyle().GetPropertyValue("height")); + + map.Clear(); + Assert.AreEqual(0, map.Size); + Assert.AreEqual(0, element.GetStyle().Length); + } + + [Test] + public void IteratesTheDeclarationsInOrder() + { + var map = CreateElement("width: 10px; --foo: bar; height: auto").GetAttributeStyleMap(); + var names = map.Select(m => m.Key).ToArray(); + CollectionAssert.AreEqual(new[] { "width", "--foo", "height" }, names); + Assert.IsInstanceOf(map.Single(m => m.Key == "height").Value[0]); + } + + [Test] + public void StyleMapOfARule() + { + var parser = new CssParser(); + var sheet = parser.ParseStyleSheet(".a { width: 10px; transform: rotate(45deg) }"); + var rule = (ICssStyleRule)sheet.Rules[0]; + var map = rule.GetStyleMap(); + + Assert.IsInstanceOf(map.Get("transform")); + map.Set("width", CssHelpers.Percent(50)); + Assert.AreEqual("50%", rule.Style.GetPropertyValue("width")); + Assert.AreSame(map, rule.GetStyleMap()); + } + + [Test] + public void ComputedStyleMap() + { + var document = ParseDocument("
"); + var element = document.GetElementById("target"); + var map = element.ComputedStyleMap(); + + Assert.IsNotInstanceOf(map); + Assert.AreEqual("50px", map.Get("width").ToString()); + Assert.AreEqual("7px", map.Get("height").ToString()); + Assert.AreEqual("20px", map.Get("padding-left").ToString()); + Assert.IsInstanceOf(map.Get("--x")); + Assert.IsInstanceOf(map.Get("transform")); + Assert.AreEqual("block", ((CssKeywordValue)map.Get("display")).Value); + } + + [Test] + public void ComputedStyleMapIsSortedWithCustomPropertiesLast() + { + var document = ParseDocument("
"); + var names = document.GetElementById("target").ComputedStyleMap().Select(m => m.Key).ToList(); + var custom = names.Where(m => m.StartsWith("--")).ToList(); + + CollectionAssert.AreEqual(new[] { "--a", "--b" }, custom); + CollectionAssert.AreEqual(names.Where(m => !m.StartsWith("--")).OrderBy(m => m, StringComparer.Ordinal), names.Take(names.Count - 2)); + } + } +} diff --git a/src/AngleSharp.Css.Tests/TypedOm/TransformValueTests.cs b/src/AngleSharp.Css.Tests/TypedOm/TransformValueTests.cs new file mode 100644 index 00000000..d7146dac --- /dev/null +++ b/src/AngleSharp.Css.Tests/TypedOm/TransformValueTests.cs @@ -0,0 +1,147 @@ +#nullable disable +namespace AngleSharp.Css.Tests.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.TypedOm; + using AngleSharp.Css.Values; + using NUnit.Framework; + using System; + using static CssConstructionFunctions; + + [TestFixture] + public class TransformValueTests + { + private static CssTransformValue Parse(String text) => (CssTransformValue)CssStyleValue.Parse("transform", text); + + [TestCase("translate(10px, 20px) rotate(45deg)")] + [TestCase("translate3d(1px, 2px, 3px)")] + [TestCase("rotate3d(1, 0, 0, 45deg)")] + [TestCase("scale(2, 3)")] + [TestCase("scale3d(1, 2, 3)")] + [TestCase("skew(10deg, 20deg)")] + [TestCase("skewX(10deg)")] + [TestCase("skewY(10deg)")] + [TestCase("perspective(100px)")] + [TestCase("matrix(1, 2, 3, 4, 5, 6)")] + [TestCase("translate(calc(1px + 2em), 50%)")] + public void RoundTrips(String text) + { + Assert.AreEqual(text, Parse(text).ToString()); + } + + [Test] + public void ShortFormsAreExpanded() + { + Assert.AreEqual("translate(10px, 0px)", Parse("translateX(10px)").ToString()); + Assert.AreEqual("translate(0px, 10px)", Parse("translateY(10px)").ToString()); + Assert.AreEqual("translate3d(0px, 0px, 10px)", Parse("translateZ(10px)").ToString()); + Assert.AreEqual("scale(2, 2)", Parse("scale(2)").ToString()); + Assert.AreEqual("scale(2, 1)", Parse("scaleX(2)").ToString()); + Assert.AreEqual("rotate3d(1, 0, 0, 10deg)", Parse("rotateX(10deg)").ToString()); + Assert.AreEqual("skew(10deg)", Parse("skew(10deg)").ToString()); + } + + [Test] + public void Is2D() + { + Assert.IsTrue(Parse("translate(10px, 20px) rotate(45deg)").Is2D); + Assert.IsFalse(Parse("translate(10px, 20px) translateZ(5px)").Is2D); + } + + [Test] + public void ComponentsExposeTheirValues() + { + var transform = Parse("translate(10px, 20px) rotate(45deg) scale(2, 3)"); + var translate = (CssTranslate)transform[0]; + var rotate = (CssRotate)transform[1]; + var scale = (CssScale)transform[2]; + Assert.AreEqual("10px", translate.X.ToString()); + Assert.AreEqual("20px", translate.Y.ToString()); + Assert.AreEqual("45deg", rotate.Angle.ToString()); + Assert.AreEqual("3", scale.Y.ToString()); + } + + [TestCase("translate(10px, 20px)")] + [TestCase("translate3d(10px, 20px, 30px)")] + [TestCase("rotate(30deg)")] + [TestCase("rotate3d(1, 2, 3, 30deg)")] + [TestCase("scale(2, 3)")] + [TestCase("skew(10deg, 20deg)")] + [TestCase("perspective(100px)")] + [TestCase("matrix(1, 2, 3, 4, 5, 6)")] + public void ToMatrixAgreesWithTheCssom(String text) + { + var raw = (CssTupleValue)ParseDeclaration("transform: " + text).RawValue; + var expected = ((ICssTransformFunctionValue)raw.Items[0]).ComputeMatrix(null); + var actual = Parse(text).ToMatrix(); + AssertMatrix(expected, actual); + } + + [Test] + public void ToMatrixComposesTheTransforms() + { + var matrix = Parse("translate(10px, 0px) scale(2)").ToMatrix(); + Assert.AreEqual(2.0, matrix[0, 0], 1e-9); + Assert.AreEqual(2.0, matrix[1, 1], 1e-9); + Assert.AreEqual(10.0, matrix[0, 3], 1e-9); + } + + [Test] + public void ToMatrixConvertsAbsoluteUnits() + { + var matrix = Parse("translate(1in, 0px)").ToMatrix(); + Assert.AreEqual(96.0, matrix[0, 3], 1e-9); + } + + [Test] + public void ToMatrixOfRelativeUnitsThrows() + { + Assert.Throws(() => Parse("translate(1em, 0px)").ToMatrix()); + Assert.Throws(() => Parse("translate(50%, 0px)").ToMatrix()); + } + + [Test] + public void ComponentsValidateTheirTypes() + { + Assert.Throws(() => new CssTranslate(CssHelpers.Deg(1), CssHelpers.Px(1))); + Assert.Throws(() => new CssRotate(CssHelpers.Px(1))); + Assert.Throws(() => new CssScale(CssHelpers.Px(1), 1)); + Assert.Throws(() => new CssPerspective(CssHelpers.Deg(1))); + Assert.Throws(() => new CssTransformValue(Array.Empty())); + } + + [Test] + public void TransformCanBeBuilt() + { + var transform = new CssTransformValue(new CssTransformComponent[] + { + new CssTranslate(CssHelpers.Px(10), CssHelpers.Percent(50)), + new CssRotate(CssHelpers.Turn(0.5)), + new CssPerspective(new CssKeywordValue("none")), + }); + Assert.AreEqual("translate(10px, 50%) rotate(0.5turn) perspective(none)", transform.ToString()); + Assert.IsFalse(transform.Is2D); + } + + [Test] + public void TranslateCanBeMade2D() + { + var translate = new CssTranslate(CssHelpers.Px(1), CssHelpers.Px(2), CssHelpers.Px(3)); + Assert.AreEqual("translate3d(1px, 2px, 3px)", translate.ToString()); + translate.Is2D = true; + Assert.AreEqual("translate(1px, 2px)", translate.ToString()); + Assert.AreEqual(0.0, translate.ToMatrix()[2, 3]); + } + + private static void AssertMatrix(TransformMatrix expected, TransformMatrix actual) + { + for (var row = 0; row < 4; row++) + { + for (var col = 0; col < 4; col++) + { + Assert.AreEqual(expected[row, col], actual[row, col], 1e-9, $"[{row}, {col}]"); + } + } + } + } +} diff --git a/src/AngleSharp.Css.Tests/TypedOm/UnparsedValueTests.cs b/src/AngleSharp.Css.Tests/TypedOm/UnparsedValueTests.cs new file mode 100644 index 00000000..018770f5 --- /dev/null +++ b/src/AngleSharp.Css.Tests/TypedOm/UnparsedValueTests.cs @@ -0,0 +1,75 @@ +#nullable disable +namespace AngleSharp.Css.Tests.TypedOm +{ + using AngleSharp.Css.TypedOm; + using NUnit.Framework; + using System; + + [TestFixture] + public class UnparsedValueTests + { + [Test] + public void SplitsTextAndReferences() + { + var value = (CssUnparsedValue)CssStyleValue.Parse("--foo", "1px var(--a) solid"); + Assert.AreEqual(3, value.Length); + Assert.AreEqual("1px ", value[0]); + Assert.AreEqual("--a", ((CssVariableReferenceValue)value[1]).Variable); + Assert.IsNull(((CssVariableReferenceValue)value[1]).Fallback); + Assert.AreEqual(" solid", value[2]); + Assert.AreEqual("1px var(--a) solid", value.ToString()); + } + + [Test] + public void ParsesNestedFallbacks() + { + var value = (CssUnparsedValue)CssStyleValue.Parse("--foo", "var(--a, var(--b, 1px))"); + var outer = (CssVariableReferenceValue)value[0]; + Assert.AreEqual("--a", outer.Variable); + var inner = (CssVariableReferenceValue)outer.Fallback[1]; + Assert.AreEqual("--b", inner.Variable); + Assert.AreEqual(" 1px", inner.Fallback.ToString()); + Assert.AreEqual("var(--a, var(--b, 1px))", value.ToString()); + } + + [Test] + public void IgnoresReferencesInStrings() + { + var value = (CssUnparsedValue)CssStyleValue.Parse("--foo", "'var(--x)' var(--y)"); + Assert.AreEqual(2, value.Length); + Assert.AreEqual("'var(--x)' ", value[0]); + Assert.AreEqual("--y", ((CssVariableReferenceValue)value[1]).Variable); + } + + [Test] + public void IgnoresOtherFunctionsEndingInVar() + { + var value = (CssUnparsedValue)CssStyleValue.Parse("--foo", "myvar(--x)"); + Assert.AreEqual(1, value.Length); + Assert.AreEqual("myvar(--x)", value[0]); + } + + [Test] + public void CanBeConstructedFromSegments() + { + var value = new CssUnparsedValue(new Object[] { "1px ", new CssVariableReferenceValue("--a", new CssUnparsedValue(new Object[] { "red" })) }); + Assert.AreEqual("1px var(--a,red)", value.ToString()); + } + + [Test] + public void SegmentsCanBeReplacedAndAppended() + { + var value = new CssUnparsedValue(new Object[] { "a" }); + value[0] = "b"; + value[1] = new CssVariableReferenceValue("--c"); + Assert.AreEqual("bvar(--c)", value.ToString()); + } + + [Test] + public void RejectsInvalidSegments() + { + Assert.Throws(() => new CssUnparsedValue(new Object[] { 5 })); + Assert.Throws(() => new CssVariableReferenceValue("foo")); + } + } +} diff --git a/src/AngleSharp.Css/Dom/CssHelpers.Units.cs b/src/AngleSharp.Css/Dom/CssHelpers.Units.cs new file mode 100644 index 00000000..2fa0b49c --- /dev/null +++ b/src/AngleSharp.Css/Dom/CssHelpers.Units.cs @@ -0,0 +1,517 @@ +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Attributes; + using AngleSharp.Css.TypedOm; + using System; + + /// + /// The factory functions of numeric values (CSS Typed OM), e.g., CSS.px(10). + /// https://www.w3.org/TR/css-typed-om-1/#numeric-factory + /// + public static partial class CssHelpers + { + /// + /// Creates a plain number, e.g., CSS.number(1). + /// + /// The value. + /// The unit value. + [DomName("number")] + public static CssUnitValue Number(Double value) => new(value, "number"); + + /// + /// Creates a percentage, e.g., CSS.percent(1). + /// + /// The value. + /// The unit value. + [DomName("percent")] + public static CssUnitValue Percent(Double value) => new(value, "percent"); + + /// + /// Creates a value in em, e.g., CSS.em(1). + /// + /// The value. + /// The unit value. + [DomName("em")] + public static CssUnitValue Em(Double value) => new(value, "em"); + + /// + /// Creates a value in rem, e.g., CSS.rem(1). + /// + /// The value. + /// The unit value. + [DomName("rem")] + public static CssUnitValue Rem(Double value) => new(value, "rem"); + + /// + /// Creates a value in ex, e.g., CSS.ex(1). + /// + /// The value. + /// The unit value. + [DomName("ex")] + public static CssUnitValue Ex(Double value) => new(value, "ex"); + + /// + /// Creates a value in rex, e.g., CSS.rex(1). + /// + /// The value. + /// The unit value. + [DomName("rex")] + public static CssUnitValue Rex(Double value) => new(value, "rex"); + + /// + /// Creates a value in cap, e.g., CSS.cap(1). + /// + /// The value. + /// The unit value. + [DomName("cap")] + public static CssUnitValue Cap(Double value) => new(value, "cap"); + + /// + /// Creates a value in rcap, e.g., CSS.rcap(1). + /// + /// The value. + /// The unit value. + [DomName("rcap")] + public static CssUnitValue Rcap(Double value) => new(value, "rcap"); + + /// + /// Creates a value in ch, e.g., CSS.ch(1). + /// + /// The value. + /// The unit value. + [DomName("ch")] + public static CssUnitValue Ch(Double value) => new(value, "ch"); + + /// + /// Creates a value in rch, e.g., CSS.rch(1). + /// + /// The value. + /// The unit value. + [DomName("rch")] + public static CssUnitValue Rch(Double value) => new(value, "rch"); + + /// + /// Creates a value in ic, e.g., CSS.ic(1). + /// + /// The value. + /// The unit value. + [DomName("ic")] + public static CssUnitValue Ic(Double value) => new(value, "ic"); + + /// + /// Creates a value in ric, e.g., CSS.ric(1). + /// + /// The value. + /// The unit value. + [DomName("ric")] + public static CssUnitValue Ric(Double value) => new(value, "ric"); + + /// + /// Creates a value in lh, e.g., CSS.lh(1). + /// + /// The value. + /// The unit value. + [DomName("lh")] + public static CssUnitValue Lh(Double value) => new(value, "lh"); + + /// + /// Creates a value in rlh, e.g., CSS.rlh(1). + /// + /// The value. + /// The unit value. + [DomName("rlh")] + public static CssUnitValue Rlh(Double value) => new(value, "rlh"); + + /// + /// Creates a value in vw, e.g., CSS.vw(1). + /// + /// The value. + /// The unit value. + [DomName("vw")] + public static CssUnitValue Vw(Double value) => new(value, "vw"); + + /// + /// Creates a value in vh, e.g., CSS.vh(1). + /// + /// The value. + /// The unit value. + [DomName("vh")] + public static CssUnitValue Vh(Double value) => new(value, "vh"); + + /// + /// Creates a value in vi, e.g., CSS.vi(1). + /// + /// The value. + /// The unit value. + [DomName("vi")] + public static CssUnitValue Vi(Double value) => new(value, "vi"); + + /// + /// Creates a value in vb, e.g., CSS.vb(1). + /// + /// The value. + /// The unit value. + [DomName("vb")] + public static CssUnitValue Vb(Double value) => new(value, "vb"); + + /// + /// Creates a value in vmin, e.g., CSS.vmin(1). + /// + /// The value. + /// The unit value. + [DomName("vmin")] + public static CssUnitValue Vmin(Double value) => new(value, "vmin"); + + /// + /// Creates a value in vmax, e.g., CSS.vmax(1). + /// + /// The value. + /// The unit value. + [DomName("vmax")] + public static CssUnitValue Vmax(Double value) => new(value, "vmax"); + + /// + /// Creates a value in svw, e.g., CSS.svw(1). + /// + /// The value. + /// The unit value. + [DomName("svw")] + public static CssUnitValue Svw(Double value) => new(value, "svw"); + + /// + /// Creates a value in svh, e.g., CSS.svh(1). + /// + /// The value. + /// The unit value. + [DomName("svh")] + public static CssUnitValue Svh(Double value) => new(value, "svh"); + + /// + /// Creates a value in svi, e.g., CSS.svi(1). + /// + /// The value. + /// The unit value. + [DomName("svi")] + public static CssUnitValue Svi(Double value) => new(value, "svi"); + + /// + /// Creates a value in svb, e.g., CSS.svb(1). + /// + /// The value. + /// The unit value. + [DomName("svb")] + public static CssUnitValue Svb(Double value) => new(value, "svb"); + + /// + /// Creates a value in svmin, e.g., CSS.svmin(1). + /// + /// The value. + /// The unit value. + [DomName("svmin")] + public static CssUnitValue Svmin(Double value) => new(value, "svmin"); + + /// + /// Creates a value in svmax, e.g., CSS.svmax(1). + /// + /// The value. + /// The unit value. + [DomName("svmax")] + public static CssUnitValue Svmax(Double value) => new(value, "svmax"); + + /// + /// Creates a value in lvw, e.g., CSS.lvw(1). + /// + /// The value. + /// The unit value. + [DomName("lvw")] + public static CssUnitValue Lvw(Double value) => new(value, "lvw"); + + /// + /// Creates a value in lvh, e.g., CSS.lvh(1). + /// + /// The value. + /// The unit value. + [DomName("lvh")] + public static CssUnitValue Lvh(Double value) => new(value, "lvh"); + + /// + /// Creates a value in lvi, e.g., CSS.lvi(1). + /// + /// The value. + /// The unit value. + [DomName("lvi")] + public static CssUnitValue Lvi(Double value) => new(value, "lvi"); + + /// + /// Creates a value in lvb, e.g., CSS.lvb(1). + /// + /// The value. + /// The unit value. + [DomName("lvb")] + public static CssUnitValue Lvb(Double value) => new(value, "lvb"); + + /// + /// Creates a value in lvmin, e.g., CSS.lvmin(1). + /// + /// The value. + /// The unit value. + [DomName("lvmin")] + public static CssUnitValue Lvmin(Double value) => new(value, "lvmin"); + + /// + /// Creates a value in lvmax, e.g., CSS.lvmax(1). + /// + /// The value. + /// The unit value. + [DomName("lvmax")] + public static CssUnitValue Lvmax(Double value) => new(value, "lvmax"); + + /// + /// Creates a value in dvw, e.g., CSS.dvw(1). + /// + /// The value. + /// The unit value. + [DomName("dvw")] + public static CssUnitValue Dvw(Double value) => new(value, "dvw"); + + /// + /// Creates a value in dvh, e.g., CSS.dvh(1). + /// + /// The value. + /// The unit value. + [DomName("dvh")] + public static CssUnitValue Dvh(Double value) => new(value, "dvh"); + + /// + /// Creates a value in dvi, e.g., CSS.dvi(1). + /// + /// The value. + /// The unit value. + [DomName("dvi")] + public static CssUnitValue Dvi(Double value) => new(value, "dvi"); + + /// + /// Creates a value in dvb, e.g., CSS.dvb(1). + /// + /// The value. + /// The unit value. + [DomName("dvb")] + public static CssUnitValue Dvb(Double value) => new(value, "dvb"); + + /// + /// Creates a value in dvmin, e.g., CSS.dvmin(1). + /// + /// The value. + /// The unit value. + [DomName("dvmin")] + public static CssUnitValue Dvmin(Double value) => new(value, "dvmin"); + + /// + /// Creates a value in dvmax, e.g., CSS.dvmax(1). + /// + /// The value. + /// The unit value. + [DomName("dvmax")] + public static CssUnitValue Dvmax(Double value) => new(value, "dvmax"); + + /// + /// Creates a value in cqw, e.g., CSS.cqw(1). + /// + /// The value. + /// The unit value. + [DomName("cqw")] + public static CssUnitValue Cqw(Double value) => new(value, "cqw"); + + /// + /// Creates a value in cqh, e.g., CSS.cqh(1). + /// + /// The value. + /// The unit value. + [DomName("cqh")] + public static CssUnitValue Cqh(Double value) => new(value, "cqh"); + + /// + /// Creates a value in cqi, e.g., CSS.cqi(1). + /// + /// The value. + /// The unit value. + [DomName("cqi")] + public static CssUnitValue Cqi(Double value) => new(value, "cqi"); + + /// + /// Creates a value in cqb, e.g., CSS.cqb(1). + /// + /// The value. + /// The unit value. + [DomName("cqb")] + public static CssUnitValue Cqb(Double value) => new(value, "cqb"); + + /// + /// Creates a value in cqmin, e.g., CSS.cqmin(1). + /// + /// The value. + /// The unit value. + [DomName("cqmin")] + public static CssUnitValue Cqmin(Double value) => new(value, "cqmin"); + + /// + /// Creates a value in cqmax, e.g., CSS.cqmax(1). + /// + /// The value. + /// The unit value. + [DomName("cqmax")] + public static CssUnitValue Cqmax(Double value) => new(value, "cqmax"); + + /// + /// Creates a value in cm, e.g., CSS.cm(1). + /// + /// The value. + /// The unit value. + [DomName("cm")] + public static CssUnitValue Cm(Double value) => new(value, "cm"); + + /// + /// Creates a value in mm, e.g., CSS.mm(1). + /// + /// The value. + /// The unit value. + [DomName("mm")] + public static CssUnitValue Mm(Double value) => new(value, "mm"); + + /// + /// Creates a value in Q, e.g., CSS.Q(1). + /// + /// The value. + /// The unit value. + [DomName("Q")] + public static CssUnitValue Q(Double value) => new(value, "q"); + + /// + /// Creates a value in in, e.g., CSS.in(1). + /// + /// The value. + /// The unit value. + [DomName("in")] + public static CssUnitValue In(Double value) => new(value, "in"); + + /// + /// Creates a value in pt, e.g., CSS.pt(1). + /// + /// The value. + /// The unit value. + [DomName("pt")] + public static CssUnitValue Pt(Double value) => new(value, "pt"); + + /// + /// Creates a value in pc, e.g., CSS.pc(1). + /// + /// The value. + /// The unit value. + [DomName("pc")] + public static CssUnitValue Pc(Double value) => new(value, "pc"); + + /// + /// Creates a value in px, e.g., CSS.px(1). + /// + /// The value. + /// The unit value. + [DomName("px")] + public static CssUnitValue Px(Double value) => new(value, "px"); + + /// + /// Creates a value in deg, e.g., CSS.deg(1). + /// + /// The value. + /// The unit value. + [DomName("deg")] + public static CssUnitValue Deg(Double value) => new(value, "deg"); + + /// + /// Creates a value in grad, e.g., CSS.grad(1). + /// + /// The value. + /// The unit value. + [DomName("grad")] + public static CssUnitValue Grad(Double value) => new(value, "grad"); + + /// + /// Creates a value in rad, e.g., CSS.rad(1). + /// + /// The value. + /// The unit value. + [DomName("rad")] + public static CssUnitValue Rad(Double value) => new(value, "rad"); + + /// + /// Creates a value in turn, e.g., CSS.turn(1). + /// + /// The value. + /// The unit value. + [DomName("turn")] + public static CssUnitValue Turn(Double value) => new(value, "turn"); + + /// + /// Creates a value in s, e.g., CSS.s(1). + /// + /// The value. + /// The unit value. + [DomName("s")] + public static CssUnitValue S(Double value) => new(value, "s"); + + /// + /// Creates a value in ms, e.g., CSS.ms(1). + /// + /// The value. + /// The unit value. + [DomName("ms")] + public static CssUnitValue Ms(Double value) => new(value, "ms"); + + /// + /// Creates a value in Hz, e.g., CSS.Hz(1). + /// + /// The value. + /// The unit value. + [DomName("Hz")] + public static CssUnitValue Hz(Double value) => new(value, "hz"); + + /// + /// Creates a value in kHz, e.g., CSS.kHz(1). + /// + /// The value. + /// The unit value. + [DomName("kHz")] + public static CssUnitValue KHz(Double value) => new(value, "khz"); + + /// + /// Creates a value in dpi, e.g., CSS.dpi(1). + /// + /// The value. + /// The unit value. + [DomName("dpi")] + public static CssUnitValue Dpi(Double value) => new(value, "dpi"); + + /// + /// Creates a value in dpcm, e.g., CSS.dpcm(1). + /// + /// The value. + /// The unit value. + [DomName("dpcm")] + public static CssUnitValue Dpcm(Double value) => new(value, "dpcm"); + + /// + /// Creates a value in dppx, e.g., CSS.dppx(1). + /// + /// The value. + /// The unit value. + [DomName("dppx")] + public static CssUnitValue Dppx(Double value) => new(value, "dppx"); + + /// + /// Creates a value in fr, e.g., CSS.fr(1). + /// + /// The value. + /// The unit value. + [DomName("fr")] + public static CssUnitValue Fr(Double value) => new(value, "fr"); + } +} diff --git a/src/AngleSharp.Css/Dom/CssHelpers.cs b/src/AngleSharp.Css/Dom/CssHelpers.cs index ada96498..24b3d1c4 100644 --- a/src/AngleSharp.Css/Dom/CssHelpers.cs +++ b/src/AngleSharp.Css/Dom/CssHelpers.cs @@ -12,7 +12,7 @@ namespace AngleSharp.Css.Dom /// [DomName("CSS")] [DomExposed("Window")] - public static class CssHelpers + public static partial class CssHelpers { /// /// Returns a string containing the escaped string passed as parameter, diff --git a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs index d2180d34..b9db64be 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs @@ -153,6 +153,11 @@ public Int32 Length /// internal Double? RootFontSize { get; set; } + /// + /// Gets the browsing context of the declarations, if any. + /// + internal IBrowsingContext Context => _context; + #endregion #region Methods @@ -527,6 +532,20 @@ public void SetProperty(String propertyName, String propertyValue, String priori } } + /// + /// Sets a property that has already been parsed, e.g., by the Typed OM, as + /// SetProperty does with the text of a value. + /// + internal void SetParsedProperty(ICssProperty property) + { + if (IsReadOnly) + throw new DomException(DomError.NoModificationAllowed); + + Materialize(); + SetProperty(property); + RaiseChanged(); + } + public void AddProperty(ICssProperty declaration) { EnsureWritable(); diff --git a/src/AngleSharp.Css/TypedOm/CssImageValue.cs b/src/AngleSharp.Css/TypedOm/CssImageValue.cs new file mode 100644 index 00000000..a99abfae --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssImageValue.cs @@ -0,0 +1,26 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + + /// + /// Represents an image, e.g., url(a.png) or a gradient. The value is opaque, i.e., + /// it only knows its serialization. + /// https://www.w3.org/TR/css-typed-om-1/#cssimagevalue + /// + [DomName("CSSImageValue")] + public sealed class CssImageValue : CssStyleValue + { + private readonly String _text; + + internal CssImageValue(String text) + { + _text = text; + } + + /// + /// Serializes the image. + /// + public override String ToString() => _text; + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssKeywordValue.cs b/src/AngleSharp.Css/TypedOm/CssKeywordValue.cs new file mode 100644 index 00000000..4b647b30 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssKeywordValue.cs @@ -0,0 +1,53 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Dom; + using System; + + /// + /// Represents a keyword, e.g., auto, block, or inherit. + /// https://www.w3.org/TR/css-typed-om-1/#csskeywordvalue + /// + [DomName("CSSKeywordValue")] + public sealed class CssKeywordValue : CssStyleValue + { + private String _value; + + /// + /// Creates a new keyword value. + /// + /// The keyword, e.g., auto. + /// The keyword is empty. + [DomConstructor] + public CssKeywordValue(String value) + { + _value = Validate(value); + } + + /// + /// Gets or sets the keyword. + /// + /// The keyword is empty. + [DomName("value")] + public String Value + { + get => _value; + set => _value = Validate(value); + } + + /// + /// Serializes the keyword as an identifier. + /// + public override String ToString() => CssHelpers.Escape(_value); + + private static String Validate(String value) + { + if (String.IsNullOrEmpty(value)) + { + throw new ArgumentException("A keyword must not be empty.", nameof(value)); + } + + return value; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathClamp.cs b/src/AngleSharp.Css/TypedOm/CssMathClamp.cs new file mode 100644 index 00000000..c4bf75c7 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathClamp.cs @@ -0,0 +1,78 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents a numeric value clamped between a lower and an upper bound, i.e., clamp(). + /// https://drafts.css-houdini.org/css-typed-om-1/#cssmathclamp + /// + [DomName("CSSMathClamp")] + public sealed class CssMathClamp : CssMathValue + { + private readonly CssNumericValue _lower; + private readonly CssNumericValue _value; + private readonly CssNumericValue _upper; + + /// + /// Creates a new clamped value. + /// + /// The lower bound. + /// The preferred value. + /// The upper bound. + /// The types of the values cannot be compared. + [DomConstructor] + public CssMathClamp(CssNumericValue lower, CssNumericValue value, CssNumericValue upper) + : base(AddTypes(lower, value, upper)) + { + _lower = lower; + _value = value; + _upper = upper; + } + + /// + /// Gets the lower bound. + /// + [DomName("lower")] + public CssNumericValue Lower => _lower; + + /// + /// Gets the preferred value. + /// + [DomName("value")] + public CssNumericValue Value => _value; + + /// + /// Gets the upper bound. + /// + [DomName("upper")] + public CssNumericValue Upper => _upper; + + /// + /// Gets the clamp operator. + /// + public override CssMathOperator Operator => CssMathOperator.Clamp; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) => + SerializeFunction(sb, "clamp", new[] { _lower, _value, _upper }); + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathClamp clamp && _lower.IsEqualTo(clamp._lower) && _value.IsEqualTo(clamp._value) && _upper.IsEqualTo(clamp._upper); + + internal override List? ToSumValue() + { + var items = CssSumValueItem.GetComparableItems(new[] { _lower, _value, _upper }); + + if (items is null) + { + return null; + } + + var result = items[1]; + result.Value = Math.Max(items[0].Value, Math.Min(items[1].Value, items[2].Value)); + return new List { result }; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathInvert.cs b/src/AngleSharp.Css/TypedOm/CssMathInvert.cs new file mode 100644 index 00000000..2ece0dc1 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathInvert.cs @@ -0,0 +1,71 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents the reciprocal of a numeric value, e.g., the divisor of + /// calc(1px / 2). + /// https://www.w3.org/TR/css-typed-om-1/#cssmathinvert + /// + [DomName("CSSMathInvert")] + public sealed class CssMathInvert : CssMathValue + { + private readonly CssNumericValue _value; + + /// + /// Creates a new reciprocal of the given value. + /// + /// The value to invert. + [DomConstructor] + public CssMathInvert(CssNumericValue value) + : base((value ?? throw new ArgumentNullException(nameof(value))).NumericType.Invert()) + { + _value = value; + } + + /// + /// Gets the inverted value. + /// + [DomName("value")] + public CssNumericValue Value => _value; + + /// + /// Gets the invert operator. + /// + public override CssMathOperator Operator => CssMathOperator.Invert; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) + { + Open(sb, nested, parenless); + sb.Append("1 / "); + _value.Serialize(sb, true, false); + Close(sb, parenless); + } + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathInvert invert && _value.IsEqualTo(invert._value); + + internal override List? ToSumValue() + { + var sum = _value.ToSumValue(); + + if (sum is null || sum.Count != 1) + { + return null; + } + + var item = sum[0]; + var units = new SortedDictionary(StringComparer.Ordinal); + + foreach (var entry in item.Units) + { + units[entry.Key] = -entry.Value; + } + + return new List { new(1.0 / item.Value, units) }; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathMax.cs b/src/AngleSharp.Css/TypedOm/CssMathMax.cs new file mode 100644 index 00000000..b8ea24f4 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathMax.cs @@ -0,0 +1,54 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + /// + /// Represents the maximum of numeric values, i.e., max(). + /// https://www.w3.org/TR/css-typed-om-1/#cssmathmax + /// + [DomName("CSSMathMax")] + public sealed class CssMathMax : CssMathValue + { + private readonly CssNumericArray _values; + + /// + /// Creates a new maximum of the given values. + /// + /// The values to compare, at least one. + /// No value is given. + /// The types of the values cannot be compared. + [DomConstructor] + public CssMathMax(params CssNumericValue[] values) + : base(AddTypes(values)) + { + _values = new CssNumericArray(CheckArguments(values)); + } + + /// + /// Gets the values to compare. + /// + [DomName("values")] + public CssNumericArray Values => _values; + + /// + /// Gets the max operator. + /// + public override CssMathOperator Operator => CssMathOperator.Max; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) => + SerializeFunction(sb, "max", _values); + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathMax value && AreEqual(_values, value._values); + + internal override List? ToSumValue() + { + var items = CssSumValueItem.GetComparableItems(_values); + return items is null ? null : new List { items.OrderBy(m => m.Value).Last() }; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathMin.cs b/src/AngleSharp.Css/TypedOm/CssMathMin.cs new file mode 100644 index 00000000..447bd395 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathMin.cs @@ -0,0 +1,54 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + /// + /// Represents the minimum of numeric values, i.e., min(). + /// https://www.w3.org/TR/css-typed-om-1/#cssmathmin + /// + [DomName("CSSMathMin")] + public sealed class CssMathMin : CssMathValue + { + private readonly CssNumericArray _values; + + /// + /// Creates a new minimum of the given values. + /// + /// The values to compare, at least one. + /// No value is given. + /// The types of the values cannot be compared. + [DomConstructor] + public CssMathMin(params CssNumericValue[] values) + : base(AddTypes(values)) + { + _values = new CssNumericArray(CheckArguments(values)); + } + + /// + /// Gets the values to compare. + /// + [DomName("values")] + public CssNumericArray Values => _values; + + /// + /// Gets the min operator. + /// + public override CssMathOperator Operator => CssMathOperator.Min; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) => + SerializeFunction(sb, "min", _values); + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathMin value && AreEqual(_values, value._values); + + internal override List? ToSumValue() + { + var items = CssSumValueItem.GetComparableItems(_values); + return items is null ? null : new List { items.OrderBy(m => m.Value).First() }; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathNegate.cs b/src/AngleSharp.Css/TypedOm/CssMathNegate.cs new file mode 100644 index 00000000..f7b586d6 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathNegate.cs @@ -0,0 +1,66 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents the negation of a numeric value, e.g., the subtracted value of + /// calc(1px - 2em). + /// https://www.w3.org/TR/css-typed-om-1/#cssmathnegate + /// + [DomName("CSSMathNegate")] + public sealed class CssMathNegate : CssMathValue + { + private readonly CssNumericValue _value; + + /// + /// Creates a new negation of the given value. + /// + /// The value to negate. + [DomConstructor] + public CssMathNegate(CssNumericValue value) + : base((value ?? throw new ArgumentNullException(nameof(value))).NumericType) + { + _value = value; + } + + /// + /// Gets the negated value. + /// + [DomName("value")] + public CssNumericValue Value => _value; + + /// + /// Gets the negate operator. + /// + public override CssMathOperator Operator => CssMathOperator.Negate; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) + { + Open(sb, nested, parenless); + sb.Append('-'); + _value.Serialize(sb, true, false); + Close(sb, parenless); + } + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathNegate negate && _value.IsEqualTo(negate._value); + + internal override List? ToSumValue() + { + var sum = _value.ToSumValue(); + + if (sum is not null) + { + foreach (var item in sum) + { + item.Value = -item.Value; + } + } + + return sum; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathOperator.cs b/src/AngleSharp.Css/TypedOm/CssMathOperator.cs new file mode 100644 index 00000000..aa7405a2 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathOperator.cs @@ -0,0 +1,49 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + + /// + /// The operators of math values. + /// https://www.w3.org/TR/css-typed-om-1/#enumdef-cssmathoperator + /// + [DomName("CSSMathOperator")] + [DomLiterals] + public enum CssMathOperator : byte + { + /// + /// The sum of the values. + /// + [DomName("sum")] + Sum, + /// + /// The product of the values. + /// + [DomName("product")] + Product, + /// + /// The negation of a value. + /// + [DomName("negate")] + Negate, + /// + /// The reciprocal of a value. + /// + [DomName("invert")] + Invert, + /// + /// The minimum of the values. + /// + [DomName("min")] + Min, + /// + /// The maximum of the values. + /// + [DomName("max")] + Max, + /// + /// A value clamped between a lower and an upper bound. + /// + [DomName("clamp")] + Clamp, + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathProduct.cs b/src/AngleSharp.Css/TypedOm/CssMathProduct.cs new file mode 100644 index 00000000..dbf4dc32 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathProduct.cs @@ -0,0 +1,96 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents a product of numeric values, e.g., calc(2 * 1em). A division is + /// the product with an inverted value. + /// https://www.w3.org/TR/css-typed-om-1/#cssmathproduct + /// + [DomName("CSSMathProduct")] + public sealed class CssMathProduct : CssMathValue + { + private readonly CssNumericArray _values; + + /// + /// Creates a new product of the given values. + /// + /// The values to multiply, at least one. + /// No value is given. + /// The types of the values cannot be multiplied. + [DomConstructor] + public CssMathProduct(params CssNumericValue[] values) + : base(MultiplyTypes(values)) + { + _values = new CssNumericArray(CheckArguments(values)); + } + + /// + /// Gets the values to multiply. + /// + [DomName("values")] + public CssNumericArray Values => _values; + + /// + /// Gets the product operator. + /// + public override CssMathOperator Operator => CssMathOperator.Product; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) + { + Open(sb, nested, parenless); + _values[0].Serialize(sb, true, false); + + for (var i = 1; i < _values.Length; i++) + { + if (_values[i] is CssMathInvert invert) + { + sb.Append(" / "); + invert.Value.Serialize(sb, true, false); + } + else + { + sb.Append(" * "); + _values[i].Serialize(sb, true, false); + } + } + + Close(sb, parenless); + } + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathProduct product && AreEqual(_values, product._values); + + internal override List? ToSumValue() + { + var result = new List { CssSumValueItem.Create(1.0, CssUnits.Number) }; + + foreach (var value in _values) + { + var sum = value.ToSumValue(); + + if (sum is null) + { + return null; + } + + var temp = new List(); + + foreach (var a in result) + { + foreach (var b in sum) + { + CssSumValueItem.AddTo(temp, CssSumValueItem.Multiply(a, b)); + } + } + + result = temp; + } + + return result; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathSum.cs b/src/AngleSharp.Css/TypedOm/CssMathSum.cs new file mode 100644 index 00000000..0292aab9 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathSum.cs @@ -0,0 +1,89 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents a sum of numeric values, e.g., calc(1px + 2em). A subtraction is + /// the sum with a negated value. + /// https://www.w3.org/TR/css-typed-om-1/#cssmathsum + /// + [DomName("CSSMathSum")] + public sealed class CssMathSum : CssMathValue + { + private readonly CssNumericArray _values; + + /// + /// Creates a new sum of the given values. + /// + /// The values to add, at least one. + /// No value is given. + /// The types of the values cannot be added. + [DomConstructor] + public CssMathSum(params CssNumericValue[] values) + : base(AddTypes(values)) + { + _values = new CssNumericArray(CheckArguments(values)); + } + + /// + /// Gets the values to add. + /// + [DomName("values")] + public CssNumericArray Values => _values; + + /// + /// Gets the sum operator. + /// + public override CssMathOperator Operator => CssMathOperator.Sum; + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) + { + Open(sb, nested, parenless); + _values[0].Serialize(sb, true, false); + + for (var i = 1; i < _values.Length; i++) + { + if (_values[i] is CssMathNegate negate) + { + sb.Append(" - "); + negate.Value.Serialize(sb, true, false); + } + else + { + sb.Append(" + "); + _values[i].Serialize(sb, true, false); + } + } + + Close(sb, parenless); + } + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssMathSum sum && AreEqual(_values, sum._values); + + internal override List? ToSumValue() + { + var result = new List(); + + foreach (var value in _values) + { + var sum = value.ToSumValue(); + + if (sum is null) + { + return null; + } + + foreach (var item in sum) + { + CssSumValueItem.AddTo(result, item); + } + } + + return result; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMathValue.cs b/src/AngleSharp.Css/TypedOm/CssMathValue.cs new file mode 100644 index 00000000..9bb044a3 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMathValue.cs @@ -0,0 +1,127 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// The base class of math expressions, e.g., calc(1px + 2em) or min(1px, 2em). + /// https://www.w3.org/TR/css-typed-om-1/#cssmathvalue + /// + [DomName("CSSMathValue")] + public abstract class CssMathValue : CssNumericValue + { + #region ctor + + internal CssMathValue(CssNumericType type) + : base(type) + { + } + + #endregion + + #region Properties + + /// + /// Gets the operator of the expression. + /// + [DomName("operator")] + public abstract CssMathOperator Operator { get; } + + #endregion + + #region Helpers + + internal static CssNumericValue[] CheckArguments(CssNumericValue[] values) + { + if (Check(values).Length == 0) + { + throw new DomException(DomError.Syntax); + } + + return (CssNumericValue[])values.Clone(); + } + + /// + /// Gets the type of the sum of the given values, e.g., for calc(), min(), or clamp(). + /// + internal static CssNumericType AddTypes(params CssNumericValue[] values) => + CombineTypes(values, CssNumericType.Add); + + /// + /// Gets the type of the product of the given values. + /// + internal static CssNumericType MultiplyTypes(params CssNumericValue[] values) => + CombineTypes(values, CssNumericType.Multiply); + + private static CssNumericType CombineTypes(CssNumericValue[] values, Func combine) + { + var type = CheckArguments(values)[0].NumericType; + + for (var i = 1; i < values.Length; i++) + { + type = combine(type, values[i].NumericType) ?? + throw new ArgumentException("The types of the values are not compatible.", nameof(values)); + } + + return type; + } + + internal static Boolean AreEqual(CssNumericArray a, CssNumericArray b) + { + if (a.Length != b.Length) + { + return false; + } + + for (var i = 0; i < a.Length; i++) + { + if (!a[i].IsEqualTo(b[i])) + { + return false; + } + } + + return true; + } + + internal static void SerializeFunction(StringBuilder sb, String name, IEnumerable values) + { + var first = true; + sb.Append(name).Append('('); + + foreach (var value in values) + { + if (!first) + { + sb.Append(", "); + } + + value.Serialize(sb, true, true); + first = false; + } + + sb.Append(')'); + } + + internal static void Open(StringBuilder sb, Boolean nested, Boolean parenless) + { + if (!parenless) + { + sb.Append(nested ? "(" : "calc("); + } + } + + internal static void Close(StringBuilder sb, Boolean parenless) + { + if (!parenless) + { + sb.Append(')'); + } + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssMatrixComponent.cs b/src/AngleSharp.Css/TypedOm/CssMatrixComponent.cs new file mode 100644 index 00000000..84c678d2 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssMatrixComponent.cs @@ -0,0 +1,83 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + using System.Linq; + + /// + /// Represents an explicit transformation matrix, i.e., matrix() or matrix3d(). + /// https://www.w3.org/TR/css-typed-om-1/#cssmatrixcomponent + /// + [DomName("CSSMatrixComponent")] + public sealed class CssMatrixComponent : CssTransformComponent + { + private TransformMatrix _matrix; + + /// + /// Creates a new matrix component. + /// + /// The transformation matrix. + /// If the matrix is a 2D matrix, i.e., matrix(). + [DomConstructor] + public CssMatrixComponent(TransformMatrix matrix, Boolean is2D = false) + : base(is2D) + { + _matrix = matrix ?? throw new ArgumentNullException(nameof(matrix)); + } + + /// + /// Gets or sets the transformation matrix. + /// + [DomName("matrix")] + public TransformMatrix Matrix + { + get => _matrix; + set => _matrix = value ?? throw new ArgumentNullException(nameof(value)); + } + + /// + /// Gets the matrix, reduced to its 2D part if the component is 2D. + /// + public override TransformMatrix ToMatrix() + { + if (!Is2D) + { + return _matrix; + } + + var m = Identity(); + m[0, 0] = _matrix[0, 0]; + m[0, 1] = _matrix[0, 1]; + m[1, 0] = _matrix[1, 0]; + m[1, 1] = _matrix[1, 1]; + m[0, 3] = _matrix[0, 3]; + m[1, 3] = _matrix[1, 3]; + return CreateMatrix(m); + } + + /// + /// Serializes the matrix, i.e., matrix(a, b, c, d, e, f) or matrix3d(...). + /// + public override String ToString() + { + if (Is2D) + { + var values = new[] { _matrix[0, 0], _matrix[1, 0], _matrix[0, 1], _matrix[1, 1], _matrix[0, 3], _matrix[1, 3] }; + return String.Concat("matrix(", String.Join(", ", values.Select(m => m.CssStringify())), ")"); + } + + var all = new Double[16]; + + for (var col = 0; col < 4; col++) + { + for (var row = 0; row < 4; row++) + { + all[col * 4 + row] = _matrix[row, col]; + } + } + + return String.Concat("matrix3d(", String.Join(", ", all.Select(m => m.CssStringify())), ")"); + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssNumericArray.cs b/src/AngleSharp.Css/TypedOm/CssNumericArray.cs new file mode 100644 index 00000000..16c4ac69 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssNumericArray.cs @@ -0,0 +1,44 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections; + using System.Collections.Generic; + + /// + /// A read-only list of numeric values, e.g., the arguments of a math value. + /// https://www.w3.org/TR/css-typed-om-1/#cssnumericarray + /// + [DomName("CSSNumericArray")] + public sealed class CssNumericArray : IReadOnlyList + { + private readonly CssNumericValue[] _values; + + internal CssNumericArray(CssNumericValue[] values) + { + _values = values; + } + + /// + /// Gets the value at the given index. + /// + [DomName("item")] + [DomAccessor(Accessors.Getter)] + public CssNumericValue this[Int32 index] => _values[index]; + + /// + /// Gets the number of values. + /// + [DomName("length")] + public Int32 Length => _values.Length; + + Int32 IReadOnlyCollection.Count => _values.Length; + + /// + /// Gets an enumerator over the values. + /// + public IEnumerator GetEnumerator() => ((IEnumerable)_values).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssNumericBaseType.cs b/src/AngleSharp.Css/TypedOm/CssNumericBaseType.cs new file mode 100644 index 00000000..df3d5c7b --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssNumericBaseType.cs @@ -0,0 +1,49 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + + /// + /// The base types of a numeric value. + /// https://www.w3.org/TR/css-typed-om-1/#enumdef-cssnumericbasetype + /// + [DomName("CSSNumericBaseType")] + [DomLiterals] + public enum CssNumericBaseType : byte + { + /// + /// A length, e.g., px or em. + /// + [DomName("length")] + Length, + /// + /// An angle, e.g., deg or rad. + /// + [DomName("angle")] + Angle, + /// + /// A time, e.g., s or ms. + /// + [DomName("time")] + Time, + /// + /// A frequency, e.g., hz or khz. + /// + [DomName("frequency")] + Frequency, + /// + /// A resolution, e.g., dpi or dppx. + /// + [DomName("resolution")] + Resolution, + /// + /// A flexible length, i.e., fr. + /// + [DomName("flex")] + Flex, + /// + /// A percentage. + /// + [DomName("percent")] + Percent, + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssNumericType.cs b/src/AngleSharp.Css/TypedOm/CssNumericType.cs new file mode 100644 index 00000000..265d130d --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssNumericType.cs @@ -0,0 +1,339 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + + /// + /// Represents the type of a numeric value, i.e., the exponents of its base types. + /// https://www.w3.org/TR/css-typed-om-1/#dictdef-cssnumerictype + /// + [DomName("CSSNumericType")] + public sealed class CssNumericType : IEquatable + { + #region Fields + + private const Int32 BaseTypeCount = 7; + + private readonly Int32[] _exponents; + private CssNumericBaseType? _percentHint; + + #endregion + + #region ctor + + private CssNumericType(Int32[] exponents, CssNumericBaseType? percentHint) + { + _exponents = exponents; + _percentHint = percentHint; + } + + internal static CssNumericType Empty() => new(new Int32[BaseTypeCount], null); + + /// + /// Creates the type of a (normalized and known) unit. + /// + internal static CssNumericType ForUnit(String unit) + { + var type = Empty(); + var baseType = CssUnits.GetBaseType(unit); + + if (baseType.HasValue) + { + type._exponents[(Int32)baseType.Value] = 1; + } + + return type; + } + + #endregion + + #region Properties + + /// + /// Gets the exponent of the length base type, if any. + /// + [DomName("length")] + public Int32? Length => Get(CssNumericBaseType.Length); + + /// + /// Gets the exponent of the angle base type, if any. + /// + [DomName("angle")] + public Int32? Angle => Get(CssNumericBaseType.Angle); + + /// + /// Gets the exponent of the time base type, if any. + /// + [DomName("time")] + public Int32? Time => Get(CssNumericBaseType.Time); + + /// + /// Gets the exponent of the frequency base type, if any. + /// + [DomName("frequency")] + public Int32? Frequency => Get(CssNumericBaseType.Frequency); + + /// + /// Gets the exponent of the resolution base type, if any. + /// + [DomName("resolution")] + public Int32? Resolution => Get(CssNumericBaseType.Resolution); + + /// + /// Gets the exponent of the flex base type, if any. + /// + [DomName("flex")] + public Int32? Flex => Get(CssNumericBaseType.Flex); + + /// + /// Gets the exponent of the percent base type, if any. + /// + [DomName("percent")] + public Int32? Percent => Get(CssNumericBaseType.Percent); + + /// + /// Gets the base type percentages resolve against, if any. + /// + [DomName("percentHint")] + public CssNumericBaseType? PercentHint => _percentHint; + + #endregion + + #region Methods + + /// + /// Gets the exponent of the given base type, if it is not zero. + /// + /// The base type to look up. + /// The exponent or null. + public Int32? Get(CssNumericBaseType baseType) + { + var exponent = _exponents[(Int32)baseType]; + return exponent != 0 ? exponent : null; + } + + /// + /// Checks if the type describes a plain number. + /// + internal Boolean IsNumber => _percentHint is null && IsEmpty(); + + /// + /// Checks if the type matches the given base type with an exponent of 1, e.g., + /// <length> or <angle>. + /// + internal Boolean Matches(CssNumericBaseType baseType) => + Matches(baseType, ignoreHint: baseType == CssNumericBaseType.Percent); + + /// + /// Checks if the type matches a <length-percentage>, which includes a length + /// combined with a percentage, e.g., calc(1px + 10%). + /// + internal Boolean MatchesLengthPercentage() => + Matches(CssNumericBaseType.Percent) || + Matches(CssNumericBaseType.Length, ignoreHint: _percentHint is null || _percentHint == CssNumericBaseType.Length); + + private Boolean Matches(CssNumericBaseType baseType, Boolean ignoreHint) + { + for (var i = 0; i < BaseTypeCount; i++) + { + if (_exponents[i] != (i == (Int32)baseType ? 1 : 0)) + { + return false; + } + } + + return ignoreHint || _percentHint is null; + } + + /// + /// Adds two types. + /// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-add-two-types + /// + /// The resulting type or null in case of a failure. + internal static CssNumericType? Add(CssNumericType first, CssNumericType second) + { + var a = first.Clone(); + var b = second.Clone(); + + if (a._percentHint.HasValue && b._percentHint.HasValue && a._percentHint != b._percentHint) + { + return null; + } + else if (a._percentHint.HasValue) + { + b.ApplyPercentHint(a._percentHint.Value); + } + else if (b._percentHint.HasValue) + { + a.ApplyPercentHint(b._percentHint.Value); + } + + if (a.HasSameExponents(b)) + { + return a; + } + + var hasPercent = a.Has(CssNumericBaseType.Percent) || b.Has(CssNumericBaseType.Percent); + var hasOther = a.HasOtherThanPercent() || b.HasOtherThanPercent(); + + if (hasPercent && hasOther) + { + for (var i = 0; i < BaseTypeCount; i++) + { + var hint = (CssNumericBaseType)i; + + if (hint != CssNumericBaseType.Percent) + { + var x = a.Clone(); + var y = b.Clone(); + x.ApplyPercentHint(hint); + y.ApplyPercentHint(hint); + + if (x.HasSameExponents(y)) + { + return x; + } + } + } + } + + return null; + } + + /// + /// Multiplies two types. + /// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-multiply-two-types + /// + /// The resulting type or null in case of a failure. + internal static CssNumericType? Multiply(CssNumericType first, CssNumericType second) + { + var a = first.Clone(); + var b = second.Clone(); + + if (a._percentHint.HasValue && b._percentHint.HasValue && a._percentHint != b._percentHint) + { + return null; + } + else if (a._percentHint.HasValue) + { + b.ApplyPercentHint(a._percentHint.Value); + } + else if (b._percentHint.HasValue) + { + a.ApplyPercentHint(b._percentHint.Value); + } + + for (var i = 0; i < BaseTypeCount; i++) + { + a._exponents[i] += b._exponents[i]; + } + + return a; + } + + /// + /// Inverts the type, i.e., negates all exponents. + /// + internal CssNumericType Invert() + { + var result = Clone(); + + for (var i = 0; i < BaseTypeCount; i++) + { + result._exponents[i] = -result._exponents[i]; + } + + return result; + } + + /// + /// Checks if both types are equal. + /// + /// The type to compare to. + /// True if both are equal, otherwise false. + public Boolean Equals(CssNumericType? other) => + other is not null && other._percentHint == _percentHint && HasSameExponents(other); + + /// + /// Checks if both types are equal. + /// + public override Boolean Equals(Object? obj) => Equals(obj as CssNumericType); + + /// + /// Gets the hash code of the type. + /// + public override Int32 GetHashCode() + { + var hash = _percentHint.HasValue ? (Int32)_percentHint.Value + 1 : 0; + + for (var i = 0; i < BaseTypeCount; i++) + { + hash = hash * 31 + _exponents[i]; + } + + return hash; + } + + #endregion + + #region Helpers + + private CssNumericType Clone() => new((Int32[])_exponents.Clone(), _percentHint); + + private Boolean Has(CssNumericBaseType baseType) => _exponents[(Int32)baseType] != 0; + + private Boolean IsEmpty() + { + for (var i = 0; i < BaseTypeCount; i++) + { + if (_exponents[i] != 0) + { + return false; + } + } + + return true; + } + + private Boolean HasOtherThanPercent() + { + for (var i = 0; i < BaseTypeCount; i++) + { + if (i != (Int32)CssNumericBaseType.Percent && _exponents[i] != 0) + { + return true; + } + } + + return false; + } + + private Boolean HasSameExponents(CssNumericType other) + { + for (var i = 0; i < BaseTypeCount; i++) + { + if (_exponents[i] != other._exponents[i]) + { + return false; + } + } + + return true; + } + + private void ApplyPercentHint(CssNumericBaseType hint) + { + var percent = (Int32)CssNumericBaseType.Percent; + + if (hint != CssNumericBaseType.Percent) + { + _exponents[(Int32)hint] += _exponents[percent]; + _exponents[percent] = 0; + } + + _percentHint = hint; + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssNumericValue.cs b/src/AngleSharp.Css/TypedOm/CssNumericValue.cs new file mode 100644 index 00000000..cc01259b --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssNumericValue.cs @@ -0,0 +1,446 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Parser; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using AngleSharp.Text; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + /// + /// The base class of numeric values, i.e., of units and math expressions. + /// https://www.w3.org/TR/css-typed-om-1/#numeric-value + /// + [DomName("CSSNumericValue")] + public abstract class CssNumericValue : CssStyleValue, IEquatable + { + #region Fields + + private readonly CssNumericType _type; + + #endregion + + #region ctor + + internal CssNumericValue(CssNumericType type) + { + _type = type; + } + + #endregion + + #region Operators + + /// + /// Converts a plain number to a numeric value with the unit "number". + /// + /// The number. + public static implicit operator CssNumericValue(Double value) => new CssUnitValue(value, CssUnits.Number); + + /// + /// Adds two numeric values. + /// + public static CssNumericValue operator +(CssNumericValue a, CssNumericValue b) => a.Add(b); + + /// + /// Subtracts two numeric values. + /// + public static CssNumericValue operator -(CssNumericValue a, CssNumericValue b) => a.Sub(b); + + /// + /// Multiplies two numeric values. + /// + public static CssNumericValue operator *(CssNumericValue a, CssNumericValue b) => a.Mul(b); + + /// + /// Divides two numeric values. + /// + public static CssNumericValue operator /(CssNumericValue a, CssNumericValue b) => a.Div(b); + + /// + /// Negates a numeric value. + /// + public static CssNumericValue operator -(CssNumericValue a) => Negate(a); + + #endregion + + #region Methods + + /// + /// Adds the given values to the current one. + /// + /// The values to add. + /// The sum, which is a unit value if all units are the same. + /// The types of the values cannot be added. + [DomName("add")] + public CssNumericValue Add(params CssNumericValue[] values) + { + var items = Flatten(values, sum => sum.Values); + + if (TryGetCommonUnit(items, out var unit)) + { + return new CssUnitValue(items.Sum(m => ((CssUnitValue)m).Value), unit); + } + + return new CssMathSum(items.ToArray()); + } + + /// + /// Subtracts the given values from the current one. + /// + /// The values to subtract. + /// The difference, which is a unit value if all units are the same. + /// The types of the values cannot be added. + [DomName("sub")] + public CssNumericValue Sub(params CssNumericValue[] values) => + Add(Check(values).Select(Negate).ToArray()); + + /// + /// Multiplies the current value with the given ones. + /// + /// The values to multiply with. + /// The product, which is a unit value if at most one value is not a number. + /// The types of the values cannot be multiplied. + [DomName("mul")] + public CssNumericValue Mul(params CssNumericValue[] values) + { + var items = Flatten(values, product => product.Values); + + if (items.All(m => m is CssUnitValue)) + { + var units = items.Cast().ToArray(); + var dimensions = units.Where(m => m.Unit != CssUnits.Number).ToArray(); + + if (dimensions.Length <= 1) + { + var value = units.Aggregate(1.0, (product, item) => product * item.Value); + return new CssUnitValue(value, dimensions.Length == 1 ? dimensions[0].Unit : CssUnits.Number); + } + } + + return new CssMathProduct(items.ToArray()); + } + + /// + /// Divides the current value by the given ones. + /// + /// The values to divide by. + /// The quotient. + /// The types of the values cannot be multiplied. + /// A value is the number 0. + [DomName("div")] + public CssNumericValue Div(params CssNumericValue[] values) + { + var inverted = Check(values).Select(value => + { + if (value is CssUnitValue unit && unit.Unit == CssUnits.Number && unit.Value == 0.0) + { + throw new ArgumentOutOfRangeException(nameof(values), "Cannot divide by zero."); + } + + return Invert(value); + }); + + return Mul(inverted.ToArray()); + } + + /// + /// Gets the minimum of the current and the given values. + /// + /// The other values. + /// The minimum, which is a unit value if all units are the same. + /// The types of the values cannot be compared. + [DomName("min")] + public CssNumericValue Min(params CssNumericValue[] values) + { + var items = new[] { this }.Concat(Check(values)).ToArray(); + + if (TryGetCommonUnit(items, out var unit)) + { + return new CssUnitValue(items.Min(m => ((CssUnitValue)m).Value), unit); + } + + return new CssMathMin(items); + } + + /// + /// Gets the maximum of the current and the given values. + /// + /// The other values. + /// The maximum, which is a unit value if all units are the same. + /// The types of the values cannot be compared. + [DomName("max")] + public CssNumericValue Max(params CssNumericValue[] values) + { + var items = new[] { this }.Concat(Check(values)).ToArray(); + + if (TryGetCommonUnit(items, out var unit)) + { + return new CssUnitValue(items.Max(m => ((CssUnitValue)m).Value), unit); + } + + return new CssMathMax(items); + } + + /// + /// Checks if the current value is structurally equal to all the given values. + /// + /// The values to compare to. + /// True if all are equal, otherwise false. + [DomName("equals")] + public Boolean Equals(params CssNumericValue[] values) => Check(values).All(IsEqualTo); + + /// + /// Checks if the current value is structurally equal to the given value. + /// + /// The value to compare to. + /// True if both are equal, otherwise false. + public Boolean Equals(CssNumericValue? other) => other is not null && IsEqualTo(other); + + /// + /// Checks if the current value is structurally equal to the given object. + /// + public override Boolean Equals(Object? obj) => obj is CssNumericValue other && IsEqualTo(other); + + /// + /// Gets the hash code, which is derived from the serialization. + /// + public override Int32 GetHashCode() => StringComparer.Ordinal.GetHashCode(ToString()); + + /// + /// Converts the value to a single unit value of the given unit, e.g., + /// 1in to 96px or calc(1s + 500ms) to 1.5s. + /// + /// The target unit, e.g., px. + /// The converted value. + /// The unit is unknown. + /// The value cannot be converted to the unit. + [DomName("to")] + public CssUnitValue To(String unit) + { + var target = ValidateUnit(unit); + var sum = ToSumValue(); + + if (sum is not null && sum.Count == 1) + { + var item = sum[0]; + var source = item.GetSingleUnit(); + + if (source is not null && CssUnits.TryConvert(item.Value, source, target, out var result)) + { + return new CssUnitValue(result, target); + } + } + + throw new ArgumentException($"The value '{this}' cannot be converted to '{target}'.", nameof(unit)); + } + + /// + /// Converts the value to a sum of unit values, e.g., calc(1in + 1em + 1px) + /// to calc(1em + 97px). If units are given, the sum contains exactly one + /// value of each of the given units, in their order. + /// + /// The optional units to use. + /// The sum of unit values. + /// A unit is unknown. + /// The value cannot be converted. + [DomName("toSum")] + public CssMathSum ToSum(params String[] units) + { + var targets = (units ?? Array.Empty()).Select(ValidateUnit).ToArray(); + var sum = ToSumValue() ?? throw new ArgumentException($"The value '{this}' cannot be converted to a sum."); + var items = new List>(); + + foreach (var item in sum) + { + var unit = item.GetSingleUnit() ?? throw new ArgumentException($"The value '{this}' contains a product of units."); + items.Add(new KeyValuePair(unit, item.Value)); + } + + if (targets.Length == 0) + { + var values = items + .OrderBy(m => m.Key, StringComparer.Ordinal) + .Select(m => (CssNumericValue)new CssUnitValue(m.Value, m.Key)) + .ToArray(); + return new CssMathSum(values); + } + + var result = new List(); + + foreach (var target in targets) + { + var total = 0.0; + + for (var i = items.Count - 1; i >= 0; i--) + { + if (CssUnits.TryConvert(items[i].Value, items[i].Key, target, out var converted)) + { + total += converted; + items.RemoveAt(i); + } + } + + result.Add(new CssUnitValue(total, target)); + } + + if (items.Count > 0) + { + throw new ArgumentException($"The value '{this}' cannot be expressed in the given units.", nameof(units)); + } + + return new CssMathSum(result.ToArray()); + } + + /// + /// Gets the type of the value, i.e., the exponents of its base types. + /// + /// The numeric type. + [DomName("type")] + public CssNumericType Type() => _type; + + /// + /// Parses the given text as a numeric value, i.e., a number, a percentage, a + /// dimension, or a math function such as calc(). + /// + /// The text to parse, e.g., calc(1px + 2em). + /// The numeric value. + /// The text is not a valid numeric value. + [DomName("parse")] + public static CssNumericValue Parse(String cssText) + { + if (cssText is null) + throw new ArgumentNullException(nameof(cssText)); + + var source = new StringSource(cssText); + source.SkipSpacesAndComments(); + var value = source.ParseCalc() ?? source.ParseMath() ?? source.ParseAtomicExpression(); + source.SkipSpacesAndComments(); + + if (value is not null && source.IsDone) + { + var result = CssStyleValueReifier.ReifyNumeric(value); + + if (result is not null) + { + return result; + } + } + + throw new DomException(DomError.Syntax); + } + + /// + /// Serializes the value. + /// https://www.w3.org/TR/css-typed-om-1/#serialize-a-cssnumericvalue + /// + public override String ToString() + { + var sb = new StringBuilder(); + Serialize(sb, false, false); + return sb.ToString(); + } + + #endregion + + #region Internal Methods + + internal CssNumericType NumericType => _type; + + internal abstract void Serialize(StringBuilder sb, Boolean nested, Boolean parenless); + + internal abstract Boolean IsEqualTo(CssNumericValue other); + + /// + /// Creates the sum value, or null in case of a failure, e.g., for min(1px, 1em). + /// https://www.w3.org/TR/css-typed-om-1/#create-a-sum-value + /// + internal abstract List? ToSumValue(); + + internal static CssNumericValue Negate(CssNumericValue value) => value switch + { + CssMathNegate negate => negate.Value, + CssUnitValue unit => new CssUnitValue(-unit.Value, unit.Unit), + _ => new CssMathNegate(value), + }; + + internal static CssNumericValue Invert(CssNumericValue value) => value switch + { + CssMathInvert invert => invert.Value, + CssUnitValue unit when unit.Unit == CssUnits.Number => new CssUnitValue(1.0 / unit.Value, CssUnits.Number), + _ => new CssMathInvert(value), + }; + + internal static CssNumericValue[] Check(CssNumericValue[] values) + { + if (values is null) + throw new ArgumentNullException(nameof(values)); + + foreach (var value in values) + { + if (value is null) + throw new ArgumentNullException(nameof(values)); + } + + return values; + } + + internal static String ValidateUnit(String unit) + { + var normalized = CssUnits.Normalize(unit); + + if (!CssUnits.IsKnown(normalized)) + { + throw new DomException(DomError.Syntax); + } + + return normalized; + } + + #endregion + + #region Helpers + + private List Flatten(CssNumericValue[] values, Func> getValues) + where T : CssNumericValue + { + var items = new List(); + + foreach (var value in new[] { this }.Concat(Check(values))) + { + if (value is T composite) + { + items.AddRange(getValues(composite)); + } + else + { + items.Add(value); + } + } + + return items; + } + + private static Boolean TryGetCommonUnit(IEnumerable values, out String unit) + { + unit = String.Empty; + + foreach (var value in values) + { + if (value is not CssUnitValue item || (unit.Length > 0 && item.Unit != unit)) + { + return false; + } + + unit = item.Unit; + } + + return unit.Length > 0; + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssPerspective.cs b/src/AngleSharp.Css/TypedOm/CssPerspective.cs new file mode 100644 index 00000000..9dd5d3f3 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssPerspective.cs @@ -0,0 +1,73 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a perspective, i.e., perspective(). + /// https://www.w3.org/TR/css-typed-om-1/#cssperspective + /// + [DomName("CSSPerspective")] + public sealed class CssPerspective : CssTransformComponent + { + private CssStyleValue _length; + + /// + /// Creates a new perspective. + /// + /// The distance, i.e., a length or the keyword none. + /// The value is neither a length nor none. + [DomConstructor] + public CssPerspective(CssStyleValue length) + : base(false) + { + _length = Validate(length, nameof(length)); + } + + /// + /// Gets or sets the distance, i.e., a length or the keyword none. + /// + [DomName("length")] + public CssStyleValue Length + { + get => _length; + set => _length = Validate(value, nameof(value)); + } + + /// + /// Computes the matrix of the perspective, which is the identity in 2D or for none. + /// + public override TransformMatrix ToMatrix() + { + var m = Identity(); + + if (!Is2D && _length is CssNumericValue length) + { + var distance = Math.Max(length.To("px").Value, 1.0); + m[3, 2] = -1.0 / distance; + } + + return CreateMatrix(m); + } + + /// + /// Serializes the perspective. + /// + public override String ToString() => String.Concat("perspective(", _length.ToString(), ")"); + + private static CssStyleValue Validate(CssStyleValue value, String name) + { + if (value is null) + throw new ArgumentNullException(name); + + if (value is CssKeywordValue keyword && keyword.Value.Equals("none", StringComparison.OrdinalIgnoreCase)) + return value; + + if (value is CssNumericValue numeric && IsLength(numeric.NumericType)) + return value; + + throw new ArgumentException("The value has to be a length or none.", name); + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssPositionValue.cs b/src/AngleSharp.Css/TypedOm/CssPositionValue.cs new file mode 100644 index 00000000..f057fd5f --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssPositionValue.cs @@ -0,0 +1,65 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + + /// + /// Represents a position, e.g., of object-position, given by two offsets. + /// https://www.w3.org/TR/css-typed-om-1/#positionvalue-objects + /// + [DomName("CSSPositionValue")] + public sealed class CssPositionValue : CssStyleValue + { + private CssNumericValue _x; + private CssNumericValue _y; + + /// + /// Creates a new position. + /// + /// The offset from the left edge. + /// The offset from the top edge. + /// An offset is not a length-percentage. + [DomConstructor] + public CssPositionValue(CssNumericValue x, CssNumericValue y) + { + _x = Validate(x, nameof(x)); + _y = Validate(y, nameof(y)); + } + + /// + /// Gets or sets the offset from the left edge. + /// + [DomName("x")] + public CssNumericValue X + { + get => _x; + set => _x = Validate(value, nameof(value)); + } + + /// + /// Gets or sets the offset from the top edge. + /// + [DomName("y")] + public CssNumericValue Y + { + get => _y; + set => _y = Validate(value, nameof(value)); + } + + /// + /// Serializes the position, e.g., 10px 50%. + /// + public override String ToString() => String.Concat(_x.ToString(), " ", _y.ToString()); + + private static CssNumericValue Validate(CssNumericValue value, String name) + { + if (value is null) + throw new ArgumentNullException(name); + + if (!value.NumericType.MatchesLengthPercentage()) + throw new ArgumentException("The offset has to be a length or percentage.", name); + + return value; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssRotate.cs b/src/AngleSharp.Css/TypedOm/CssRotate.cs new file mode 100644 index 00000000..95499d2e --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssRotate.cs @@ -0,0 +1,135 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a rotation, i.e., rotate() or rotate3d(). + /// https://www.w3.org/TR/css-typed-om-1/#cssrotate + /// + [DomName("CSSRotate")] + public sealed class CssRotate : CssTransformComponent + { + private CssNumericValue _x; + private CssNumericValue _y; + private CssNumericValue _z; + private CssNumericValue _angle; + + /// + /// Creates a new 2D rotation. + /// + /// The angle of the rotation. + /// The value is not an angle. + [DomConstructor] + public CssRotate(CssNumericValue angle) + : base(true) + { + _x = 0.0; + _y = 0.0; + _z = 1.0; + _angle = Require(angle, nameof(angle), IsAngle, "an angle"); + } + + /// + /// Creates a new 3D rotation around the given vector. + /// + /// The x-component of the rotation axis. + /// The y-component of the rotation axis. + /// The z-component of the rotation axis. + /// The angle of the rotation. + /// A value has the wrong type. + [DomConstructor] + public CssRotate(CssNumericValue x, CssNumericValue y, CssNumericValue z, CssNumericValue angle) + : base(false) + { + _x = Require(x, nameof(x), IsNumber, "a number"); + _y = Require(y, nameof(y), IsNumber, "a number"); + _z = Require(z, nameof(z), IsNumber, "a number"); + _angle = Require(angle, nameof(angle), IsAngle, "an angle"); + } + + /// + /// Gets or sets the x-component of the rotation axis. + /// + [DomName("x")] + public CssNumericValue X + { + get => _x; + set => _x = Require(value, nameof(value), IsNumber, "a number"); + } + + /// + /// Gets or sets the y-component of the rotation axis. + /// + [DomName("y")] + public CssNumericValue Y + { + get => _y; + set => _y = Require(value, nameof(value), IsNumber, "a number"); + } + + /// + /// Gets or sets the z-component of the rotation axis. + /// + [DomName("z")] + public CssNumericValue Z + { + get => _z; + set => _z = Require(value, nameof(value), IsNumber, "a number"); + } + + /// + /// Gets or sets the angle of the rotation. + /// + [DomName("angle")] + public CssNumericValue Angle + { + get => _angle; + set => _angle = Require(value, nameof(value), IsAngle, "an angle"); + } + + /// + /// Computes the matrix of the rotation. + /// + public override TransformMatrix ToMatrix() + { + var alpha = _angle.To("rad").Value; + var x = Is2D ? 0.0 : _x.To("number").Value; + var y = Is2D ? 0.0 : _y.To("number").Value; + var z = Is2D ? 1.0 : _z.To("number").Value; + var length = Math.Sqrt(x * x + y * y + z * z); + + if (length == 0.0) + { + // a rotation around no axis does not rotate + return CreateMatrix(Identity()); + } + + var l = x / length; + var m = y / length; + var n = z / length; + var sin = Math.Sin(alpha); + var cos = Math.Cos(alpha); + var omc = 1.0 - cos; + var matrix = Identity(); + matrix[0, 0] = l * l * omc + cos; + matrix[0, 1] = m * l * omc - n * sin; + matrix[0, 2] = n * l * omc + m * sin; + matrix[1, 0] = l * m * omc + n * sin; + matrix[1, 1] = m * m * omc + cos; + matrix[1, 2] = n * m * omc - l * sin; + matrix[2, 0] = l * n * omc - m * sin; + matrix[2, 1] = m * n * omc + l * sin; + matrix[2, 2] = n * n * omc + cos; + return CreateMatrix(matrix); + } + + /// + /// Serializes the rotation. + /// + public override String ToString() => Is2D ? + String.Concat("rotate(", _angle.ToString(), ")") : + String.Concat("rotate3d(", Join(_x, _y, _z, _angle), ")"); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssScale.cs b/src/AngleSharp.Css/TypedOm/CssScale.cs new file mode 100644 index 00000000..ba11f825 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssScale.cs @@ -0,0 +1,83 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a scaling, i.e., scale() or scale3d(). + /// https://www.w3.org/TR/css-typed-om-1/#cssscale + /// + [DomName("CSSScale")] + public sealed class CssScale : CssTransformComponent + { + private CssNumericValue _x; + private CssNumericValue _y; + private CssNumericValue _z; + + /// + /// Creates a new scaling. Without a z value it is a 2D scaling. + /// + /// The factor along the x-axis. + /// The factor along the y-axis. + /// The optional factor along the z-axis. + /// A value is not a number. + [DomConstructor] + public CssScale(CssNumericValue x, CssNumericValue y, CssNumericValue? z = null) + : base(z is null) + { + _x = Require(x, nameof(x), IsNumber, "a number"); + _y = Require(y, nameof(y), IsNumber, "a number"); + _z = z is null ? 1.0 : Require(z, nameof(z), IsNumber, "a number"); + } + + /// + /// Gets or sets the factor along the x-axis. + /// + [DomName("x")] + public CssNumericValue X + { + get => _x; + set => _x = Require(value, nameof(value), IsNumber, "a number"); + } + + /// + /// Gets or sets the factor along the y-axis. + /// + [DomName("y")] + public CssNumericValue Y + { + get => _y; + set => _y = Require(value, nameof(value), IsNumber, "a number"); + } + + /// + /// Gets or sets the factor along the z-axis. + /// + [DomName("z")] + public CssNumericValue Z + { + get => _z; + set => _z = Require(value, nameof(value), IsNumber, "a number"); + } + + /// + /// Computes the matrix of the scaling. + /// + public override TransformMatrix ToMatrix() + { + var m = Identity(); + m[0, 0] = _x.To("number").Value; + m[1, 1] = _y.To("number").Value; + m[2, 2] = Is2D ? 1.0 : _z.To("number").Value; + return CreateMatrix(m); + } + + /// + /// Serializes the scaling. + /// + public override String ToString() => Is2D ? + String.Concat("scale(", Join(_x, _y), ")") : + String.Concat("scale3d(", Join(_x, _y, _z), ")"); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssSkew.cs b/src/AngleSharp.Css/TypedOm/CssSkew.cs new file mode 100644 index 00000000..7e0d5450 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssSkew.cs @@ -0,0 +1,78 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a skewing along both axes, i.e., skew(). + /// https://www.w3.org/TR/css-typed-om-1/#cssskew + /// + [DomName("CSSSkew")] + public sealed class CssSkew : CssTransformComponent + { + private CssNumericValue _ax; + private CssNumericValue _ay; + + /// + /// Creates a new skewing. + /// + /// The angle along the x-axis. + /// The angle along the y-axis. + /// A value is not an angle. + [DomConstructor] + public CssSkew(CssNumericValue ax, CssNumericValue ay) + : base(true) + { + _ax = Require(ax, nameof(ax), IsAngle, "an angle"); + _ay = Require(ay, nameof(ay), IsAngle, "an angle"); + } + + /// + /// Gets or sets the angle along the x-axis. + /// + [DomName("ax")] + public CssNumericValue Ax + { + get => _ax; + set => _ax = Require(value, nameof(value), IsAngle, "an angle"); + } + + /// + /// Gets or sets the angle along the y-axis. + /// + [DomName("ay")] + public CssNumericValue Ay + { + get => _ay; + set => _ay = Require(value, nameof(value), IsAngle, "an angle"); + } + + /// + /// Gets if the skewing is 2D, which it always is. + /// + public override Boolean Is2D + { + get => true; + set { } + } + + /// + /// Computes the matrix of the skewing. + /// + public override TransformMatrix ToMatrix() + { + var m = Identity(); + m[0, 1] = Math.Tan(_ax.To("rad").Value); + m[1, 0] = Math.Tan(_ay.To("rad").Value); + return CreateMatrix(m); + } + + /// + /// Serializes the skewing, omitting a zero angle along the y-axis. + /// + public override String ToString() => _ay is CssUnitValue unit && unit.Value == 0.0 ? + String.Concat("skew(", _ax.ToString(), ")") : + String.Concat("skew(", Join(_ax, _ay), ")"); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssSkewX.cs b/src/AngleSharp.Css/TypedOm/CssSkewX.cs new file mode 100644 index 00000000..ed0a4eb0 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssSkewX.cs @@ -0,0 +1,62 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a skewing along the x-axis, i.e., skewX(). + /// https://www.w3.org/TR/css-typed-om-1/#cssskewx + /// + [DomName("CSSSkewX")] + public sealed class CssSkewX : CssTransformComponent + { + private CssNumericValue _ax; + + /// + /// Creates a new skewing along the x-axis. + /// + /// The angle along the x-axis. + /// The value is not an angle. + [DomConstructor] + public CssSkewX(CssNumericValue ax) + : base(true) + { + _ax = Require(ax, nameof(ax), IsAngle, "an angle"); + } + + /// + /// Gets or sets the angle along the x-axis. + /// + [DomName("ax")] + public CssNumericValue Ax + { + get => _ax; + set => _ax = Require(value, nameof(value), IsAngle, "an angle"); + } + + /// + /// Gets if the skewing is 2D, which it always is. + /// + public override Boolean Is2D + { + get => true; + set { } + } + + /// + /// Computes the matrix of the skewing. + /// + public override TransformMatrix ToMatrix() + { + var m = Identity(); + m[0, 1] = Math.Tan(_ax.To("rad").Value); + return CreateMatrix(m); + } + + /// + /// Serializes the skewing. + /// + public override String ToString() => String.Concat("skewX(", _ax.ToString(), ")"); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssSkewY.cs b/src/AngleSharp.Css/TypedOm/CssSkewY.cs new file mode 100644 index 00000000..961ff843 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssSkewY.cs @@ -0,0 +1,62 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a skewing along the y-axis, i.e., skewY(). + /// https://www.w3.org/TR/css-typed-om-1/#cssskewy + /// + [DomName("CSSSkewY")] + public sealed class CssSkewY : CssTransformComponent + { + private CssNumericValue _ay; + + /// + /// Creates a new skewing along the y-axis. + /// + /// The angle along the y-axis. + /// The value is not an angle. + [DomConstructor] + public CssSkewY(CssNumericValue ay) + : base(true) + { + _ay = Require(ay, nameof(ay), IsAngle, "an angle"); + } + + /// + /// Gets or sets the angle along the y-axis. + /// + [DomName("ay")] + public CssNumericValue Ay + { + get => _ay; + set => _ay = Require(value, nameof(value), IsAngle, "an angle"); + } + + /// + /// Gets if the skewing is 2D, which it always is. + /// + public override Boolean Is2D + { + get => true; + set { } + } + + /// + /// Computes the matrix of the skewing. + /// + public override TransformMatrix ToMatrix() + { + var m = Identity(); + m[1, 0] = Math.Tan(_ay.To("rad").Value); + return CreateMatrix(m); + } + + /// + /// Serializes the skewing. + /// + public override String ToString() => String.Concat("skewY(", _ay.ToString(), ")"); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssStyleValue.cs b/src/AngleSharp.Css/TypedOm/CssStyleValue.cs new file mode 100644 index 00000000..211546f7 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssStyleValue.cs @@ -0,0 +1,89 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + + /// + /// The base class of all values of the CSS Typed OM. A value that has no more + /// specific representation (e.g., a color) is given as an instance of this + /// class, which only knows its serialization. + /// https://www.w3.org/TR/css-typed-om-1/#cssstylevalue + /// + [DomName("CSSStyleValue")] + public abstract class CssStyleValue + { + #region ctor + + internal CssStyleValue() + { + } + + #endregion + + #region Methods + + /// + /// Parses the given text as a value of the given property and returns the + /// first of the resulting values. + /// + /// The name of the property, e.g., width. + /// The text to parse, e.g., 10px. + /// The typed value. + /// The property is unknown or the text is not valid for it. + [DomName("parse")] + public static CssStyleValue Parse(String property, String cssText) => Parse(property, cssText, null); + + /// + /// Parses the given text as a value of the given property and returns the + /// first of the resulting values. + /// + /// The name of the property, e.g., width. + /// The text to parse, e.g., 10px. + /// The browsing context determining the known properties, if any. + /// The typed value. + /// The property is unknown or the text is not valid for it. + public static CssStyleValue Parse(String property, String cssText, IBrowsingContext? context) => + ParseAll(property, cssText, context)[0]; + + /// + /// Parses the given text as a value of the given property and returns all the + /// resulting values, e.g., the single images of a background-image. + /// + /// The name of the property, e.g., background-image. + /// The text to parse, e.g., url(a.png), url(b.png). + /// The typed values. + /// The property is unknown or the text is not valid for it. + [DomName("parseAll")] + public static IReadOnlyList ParseAll(String property, String cssText) => ParseAll(property, cssText, null); + + /// + /// Parses the given text as a value of the given property and returns all the + /// resulting values, e.g., the single images of a background-image. + /// + /// The name of the property, e.g., background-image. + /// The text to parse, e.g., url(a.png), url(b.png). + /// The browsing context determining the known properties, if any. + /// The typed values. + /// The property is unknown or the text is not valid for it. + public static IReadOnlyList ParseAll(String property, String cssText, IBrowsingContext? context) + { + if (property is null) + throw new ArgumentNullException(nameof(property)); + + if (cssText is null) + throw new ArgumentNullException(nameof(cssText)); + + var declaration = TypedOmProperties.Parse(context, property, cssText); + return CssStyleValueReifier.ReifyAll(declaration.Name, declaration.RawValue); + } + + /// + /// Serializes the value, i.e., gets its CSS text representation. + /// + /// The CSS text of the value. + public abstract override String ToString(); + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs b/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs new file mode 100644 index 00000000..df58f7e9 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs @@ -0,0 +1,400 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Values; + using AngleSharp.Text; + using System; + using System.Collections.Generic; + using System.Linq; + using MathFunction = AngleSharp.Css.Values.CssMathValue; + + /// + /// Turns the values of the CSSOM into values of the Typed OM. + /// https://www.w3.org/TR/css-typed-om-1/#reify-stylevalue + /// + static class CssStyleValueReifier + { + #region Values + + /// + /// Reifies the value of the given property, which yields one item per entry + /// of a comma separated list, e.g., of background-image. + /// + public static IReadOnlyList ReifyAll(String property, ICssValue? value) + { + if (value is null) + { + return Array.Empty(); + } + + if (!TypedOmProperties.IsCustom(property) && value is CssListValue list) + { + return list.Items.Select(item => Reify(property, item)).ToArray(); + } + + return new[] { Reify(property, value) }; + } + + /// + /// Reifies a single value of the given property. + /// + public static CssStyleValue Reify(String property, ICssValue value) + { + if (TypedOmProperties.IsCustom(property)) + { + return CssUnparsedValue.FromText(value.CssText); + } + + switch (value) + { + case CssReferenceValue: + case CssAnyValue: + return CssUnparsedValue.FromText(value.CssText); + case ICssSpecialValue: + return new CssKeywordValue(value.CssText); + case CssPoint2D point: + return ReifyPosition(point) ?? Unsupported(property, value); + case ICssImageValue: + return new CssImageValue(value.CssText); + case ICssTransformFunctionValue transform: + return ReifyTransform(new ICssValue[] { transform }) ?? Unsupported(property, value); + case CssTupleValue tuple when tuple.Count > 0 && tuple.Items.All(m => m is ICssTransformFunctionValue): + return ReifyTransform(tuple.Items) ?? Unsupported(property, value); + } + + var numeric = ReifyNumeric(value); + + if (numeric is not null) + { + return numeric; + } + + if (value is ICssPrimitiveValue && IsIdentifier(value.CssText)) + { + return new CssKeywordValue(value.CssText); + } + + return Unsupported(property, value); + } + + private static CssStyleValue Unsupported(String property, ICssValue value) => + new CssUnsupportedValue(property, value.CssText); + + private static Boolean IsIdentifier(String text) + { + if (String.IsNullOrEmpty(text)) + { + return false; + } + + var start = text[0] == Symbols.Minus ? 1 : 0; + + if (start == text.Length || !(text[start].IsNameStart() || (start == 1 && text[1] == Symbols.Minus))) + { + return false; + } + + for (var i = start + 1; i < text.Length; i++) + { + if (!text[i].IsName()) + { + return false; + } + } + + return true; + } + + #endregion + + #region Numeric Values + + /// + /// Reifies a numeric value, i.e., a number, a dimension, or a math function. Returns null + /// for values that are not numeric. + /// + public static CssNumericValue? ReifyNumeric(ICssValue value) + { + try + { + return ReifyNumericCore(value); + } + catch (ArgumentException) + { + // e.g., an expression with incompatible types, which the parser accepted + return null; + } + } + + private static CssNumericValue? ReifyNumericCore(ICssValue? value) + { + switch (value) + { + case null: + return null; + case CssLengthValue length: + if (Double.IsNaN(length.Value)) + { + // a keyword, e.g., auto + return null; + } + + return ReifyUnit(length.Value, length.Type == CssLengthValue.Unit.None ? String.Empty : length.UnitString); + case ICssMetricValue metric: + return Double.IsNaN(metric.Value) ? null : ReifyUnit(metric.Value, metric.UnitString); + case CssCalcValue calc: + { + // calc() is always a math value, even around a single value + var expression = ReifyExpression(calc.Expression); + return expression is null or CssMathValue ? expression : new CssMathSum(expression); + } + case MathFunction math: + return ReifyMathFunction(math); + default: + return null; + } + } + + private static CssUnitValue? ReifyUnit(Double value, String unitString) + { + var unit = unitString.Length == 0 ? CssUnits.Number : CssUnits.Normalize(unitString); + return CssUnits.IsKnown(unit) ? new CssUnitValue(value, unit) : null; + } + + private static CssNumericValue? ReifyExpression(ICssValue value) + { + switch (value) + { + case CssCalcAddExpression: + case CssCalcSubExpression: + { + var items = new List(); + return CollectSum(value, items) ? new CssMathSum(items.ToArray()) : null; + } + case CssCalcMulExpression: + case CssCalcDivExpression: + { + var items = new List(); + return CollectProduct(value, items) ? new CssMathProduct(items.ToArray()) : null; + } + case CssCalcBracketExpression bracket: + return ReifyExpression(bracket.Value); + default: + return ReifyNumericCore(value); + } + } + + // a + b - c is a single sum, but a bracket, e.g., a + (b + c), stays a nested sum + private static Boolean CollectSum(ICssValue value, List items) + { + if (value is CssCalcAddExpression add) + { + return CollectSum(add.Left, items) && Add(items, ReifyExpression(add.Right)); + } + else if (value is CssCalcSubExpression sub) + { + var right = ReifyExpression(sub.Right); + return CollectSum(sub.Left, items) && Add(items, right is null ? null : new CssMathNegate(right)); + } + + return Add(items, ReifyExpression(value)); + } + + private static Boolean CollectProduct(ICssValue value, List items) + { + if (value is CssCalcMulExpression mul) + { + return CollectProduct(mul.Left, items) && Add(items, ReifyExpression(mul.Right)); + } + else if (value is CssCalcDivExpression div) + { + var right = ReifyExpression(div.Right); + return CollectProduct(div.Left, items) && Add(items, right is null ? null : new CssMathInvert(right)); + } + + return Add(items, ReifyExpression(value)); + } + + private static Boolean Add(List items, CssNumericValue? item) + { + if (item is null) + { + return false; + } + + items.Add(item); + return true; + } + + private static CssNumericValue? ReifyMathFunction(MathFunction math) + { + var arguments = new CssNumericValue[math.Arguments.Length]; + + for (var i = 0; i < arguments.Length; i++) + { + var argument = ReifyExpression(math.Arguments[i]); + + if (argument is null) + { + return null; + } + + arguments[i] = argument; + } + + if (math.Name.Isi(FunctionNames.Min)) + { + return new CssMathMin(arguments); + } + else if (math.Name.Isi(FunctionNames.Max)) + { + return new CssMathMax(arguments); + } + else if (math.Name.Isi(FunctionNames.Clamp) && arguments.Length == 3) + { + return new CssMathClamp(arguments[0], arguments[1], arguments[2]); + } + + return null; + } + + #endregion + + #region Positions + + private static CssPositionValue? ReifyPosition(CssPoint2D point) + { + var x = ReifyNumeric(point.X); + var y = ReifyNumeric(point.Y); + + if (x is not null && y is not null && x.NumericType.MatchesLengthPercentage() && y.NumericType.MatchesLengthPercentage()) + { + return new CssPositionValue(x, y); + } + + return null; + } + + #endregion + + #region Transforms + + private static CssTransformValue? ReifyTransform(IEnumerable functions) + { + var components = new List(); + + try + { + foreach (var function in functions) + { + var component = ReifyTransformFunction(function); + + if (component is null) + { + return null; + } + + components.Add(component); + } + } + catch (ArgumentException) + { + // e.g., a translation by an angle, which the typed component rejects + return null; + } + + return new CssTransformValue(components); + } + + private static CssTransformComponent? ReifyTransformFunction(ICssValue function) + { + switch (function) + { + case CssTranslateValue translate: + { + var x = ReifyOptional(translate.ShiftX, Px(0.0)); + var y = ReifyOptional(translate.ShiftY, Px(0.0)); + var z = translate.ShiftZ is null ? null : ReifyNumeric(translate.ShiftZ); + + if (x is null || y is null || (translate.ShiftZ is not null && z is null)) + { + return null; + } + + return new CssTranslate(x, y, z); + } + case CssRotateValue rotate: + { + var angle = ReifyNumeric(rotate.Angle); + + if (angle is null) + { + return null; + } + + if (rotate.X is null && rotate.Y is null && rotate.Z is null) + { + return new CssRotate(angle); + } + + var x = ReifyOptional(rotate.X, 0.0); + var y = ReifyOptional(rotate.Y, 0.0); + var z = ReifyOptional(rotate.Z, 0.0); + return x is null || y is null || z is null ? null : new CssRotate(x, y, z, angle); + } + case CssScaleValue scale: + { + var x = ReifyOptional(scale.ScaleX, 1.0); + var y = ReifyOptional(scale.ScaleY, 1.0); + var z = scale.ScaleZ is null ? null : ReifyNumeric(scale.ScaleZ); + + if (x is null || y is null || (scale.ScaleZ is not null && z is null)) + { + return null; + } + + return new CssScale(x, y, z); + } + case CssSkewValue skew: + { + var name = skew.Name; + + if (name.Is(FunctionNames.SkewX)) + { + var ax = ReifyNumeric(skew.Alpha); + return ax is null ? null : new CssSkewX(ax); + } + else if (name.Is(FunctionNames.SkewY)) + { + var ay = ReifyNumeric(skew.Beta); + return ay is null ? null : new CssSkewY(ay); + } + else + { + var ax = ReifyOptional(skew.Alpha, Deg(0.0)); + var ay = ReifyOptional(skew.Beta, Deg(0.0)); + return ax is null || ay is null ? null : new CssSkew(ax, ay); + } + } + case CssPerspectiveValue perspective: + { + var length = ReifyNumeric(perspective.Distance); + return length is null ? null : new CssPerspective(length); + } + case CssMatrixValue matrix: + return new CssMatrixComponent(matrix.ComputeMatrix(null!), matrix.Arguments.Length == 6); + default: + return null; + } + } + + private static CssNumericValue? ReifyOptional(ICssValue? value, CssNumericValue fallback) => + value is null ? fallback : ReifyNumeric(value); + + private static CssNumericValue Px(Double value) => new CssUnitValue(value, "px"); + + private static CssNumericValue Deg(Double value) => new CssUnitValue(value, "deg"); + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssSumValue.cs b/src/AngleSharp.Css/TypedOm/CssSumValue.cs new file mode 100644 index 00000000..dca39f6c --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssSumValue.cs @@ -0,0 +1,144 @@ +namespace AngleSharp.Css.TypedOm +{ + using System; + using System.Collections.Generic; + + /// + /// A term of a sum value, i.e., a value with a map of units and their exponents. + /// The units of absolute values are canonical (px, deg, ms, hz, dppx). + /// https://www.w3.org/TR/css-typed-om-1/#create-a-sum-value + /// + sealed class CssSumValueItem + { + public CssSumValueItem(Double value, SortedDictionary units) + { + Value = value; + Units = units; + } + + public Double Value { get; set; } + + public SortedDictionary Units { get; } + + public static CssSumValueItem Create(Double value, String unit) + { + var units = new SortedDictionary(StringComparer.Ordinal); + + if (unit != CssUnits.Number) + { + units[unit] = 1; + } + + return new CssSumValueItem(value, units); + } + + public CssSumValueItem Clone() => new(Value, new SortedDictionary(Units, StringComparer.Ordinal)); + + public Boolean HasSameUnits(CssSumValueItem other) + { + if (Units.Count != other.Units.Count) + { + return false; + } + + foreach (var entry in Units) + { + if (!other.Units.TryGetValue(entry.Key, out var exponent) || exponent != entry.Value) + { + return false; + } + } + + return true; + } + + /// + /// Gets the single unit with an exponent of 1 (or number), if the item has one. + /// + public String? GetSingleUnit() + { + if (Units.Count == 0) + { + return CssUnits.Number; + } + + if (Units.Count == 1) + { + foreach (var entry in Units) + { + if (entry.Value == 1) + { + return entry.Key; + } + } + } + + return null; + } + + /// + /// Adds the item to the list, merging it into an item with the same units. + /// + public static void AddTo(List items, CssSumValueItem item) + { + foreach (var existing in items) + { + if (existing.HasSameUnits(item)) + { + existing.Value += item.Value; + return; + } + } + + items.Add(item); + } + + /// + /// Multiplies two items, i.e., multiplies the values and adds the exponents. + /// + public static CssSumValueItem Multiply(CssSumValueItem a, CssSumValueItem b) + { + var units = new SortedDictionary(a.Units, StringComparer.Ordinal); + + foreach (var entry in b.Units) + { + units.TryGetValue(entry.Key, out var exponent); + exponent += entry.Value; + + if (exponent == 0) + { + units.Remove(entry.Key); + } + else + { + units[entry.Key] = exponent; + } + } + + return new CssSumValueItem(a.Value * b.Value, units); + } + + /// + /// Gets the single items of the given sums, if they all have exactly one item + /// and all items have the same units, as required for min(), max(), and clamp(). + /// + public static List? GetComparableItems(IEnumerable values) + { + var items = new List(); + + foreach (var value in values) + { + var sum = value.ToSumValue(); + + if (sum is null || sum.Count != 1 || (items.Count > 0 && !items[0].HasSameUnits(sum[0]))) + { + return null; + } + + items.Add(sum[0]); + } + + return items; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssTransformComponent.cs b/src/AngleSharp.Css/TypedOm/CssTransformComponent.cs new file mode 100644 index 00000000..cc903dd3 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssTransformComponent.cs @@ -0,0 +1,108 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// The base class of the single functions of a transform, e.g., translate(). + /// https://www.w3.org/TR/css-typed-om-1/#csstransformcomponent + /// + [DomName("CSSTransformComponent")] + public abstract class CssTransformComponent + { + internal CssTransformComponent(Boolean is2D) + { + Is2D = is2D; + } + + /// + /// Gets or sets if the component is a 2D transformation, which ignores + /// the components of the third dimension. + /// + [DomName("is2D")] + public virtual Boolean Is2D { get; set; } + + /// + /// Computes the matrix of the transformation. + /// + /// The transformation matrix. + /// A value cannot be converted to an absolute unit, e.g., em or %. + [DomName("toMatrix")] + public abstract TransformMatrix ToMatrix(); + + /// + /// Serializes the transformation, e.g., translate(10px, 20px). + /// + public abstract override String ToString(); + + internal static CssNumericValue Require(CssNumericValue value, String name, Func matches, String expected) + { + if (value is null) + throw new ArgumentNullException(name); + + if (!matches(value.NumericType)) + throw new ArgumentException($"The value has to be {expected}.", name); + + return value; + } + + internal static Boolean IsLengthPercentage(CssNumericType type) => type.MatchesLengthPercentage(); + + internal static Boolean IsLength(CssNumericType type) => type.Matches(CssNumericBaseType.Length); + + internal static Boolean IsAngle(CssNumericType type) => type.Matches(CssNumericBaseType.Angle); + + internal static Boolean IsNumber(CssNumericType type) => type.IsNumber; + + internal static String Join(params CssNumericValue[] values) => String.Join(", ", (Object[])values); + + /// + /// Creates the matrix from the given (row-major) values. + /// + internal static TransformMatrix CreateMatrix(Double[,] m) + { + var values = new Double[16]; + + for (var col = 0; col < 4; col++) + { + for (var row = 0; row < 4; row++) + { + values[col * 4 + row] = m[row, col]; + } + } + + return new TransformMatrix(values); + } + + internal static Double[,] Identity() => new Double[,] + { + { 1.0, 0.0, 0.0, 0.0 }, + { 0.0, 1.0, 0.0, 0.0 }, + { 0.0, 0.0, 1.0, 0.0 }, + { 0.0, 0.0, 0.0, 1.0 }, + }; + + internal static TransformMatrix Multiply(TransformMatrix a, TransformMatrix b) + { + var m = new Double[4, 4]; + + for (var row = 0; row < 4; row++) + { + for (var col = 0; col < 4; col++) + { + var sum = 0.0; + + for (var k = 0; k < 4; k++) + { + sum += a[row, k] * b[k, col]; + } + + m[row, col] = sum; + } + } + + return CreateMatrix(m); + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssTransformValue.cs b/src/AngleSharp.Css/TypedOm/CssTransformValue.cs new file mode 100644 index 00000000..ac9f2f32 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssTransformValue.cs @@ -0,0 +1,96 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + /// + /// Represents a list of transformations, i.e., the value of transform. + /// https://www.w3.org/TR/css-typed-om-1/#csstransformvalue + /// + [DomName("CSSTransformValue")] + public sealed class CssTransformValue : CssStyleValue, IReadOnlyList + { + private readonly List _transforms; + + /// + /// Creates a new list of transformations. + /// + /// The transformations, at least one. + /// No transformation is given. + [DomConstructor] + public CssTransformValue(IEnumerable transforms) + { + _transforms = (transforms ?? throw new ArgumentNullException(nameof(transforms))).ToList(); + + if (_transforms.Count == 0) + throw new ArgumentException("At least one transformation is required.", nameof(transforms)); + + if (_transforms.Any(m => m is null)) + throw new ArgumentNullException(nameof(transforms)); + } + + /// + /// Gets or sets the transformation at the given index. Setting the index right + /// after the last transformation appends one. + /// + [DomName("item")] + public CssTransformComponent this[Int32 index] + { + get => _transforms[index]; + set + { + if (value is null) + throw new ArgumentNullException(nameof(value)); + + if (index == _transforms.Count) + { + _transforms.Add(value); + } + else + { + _transforms[index] = value; + } + } + } + + /// + /// Gets the number of transformations. + /// + [DomName("length")] + public Int32 Length => _transforms.Count; + + Int32 IReadOnlyCollection.Count => _transforms.Count; + + /// + /// Gets if all the transformations are 2D. + /// + [DomName("is2D")] + public Boolean Is2D => _transforms.All(m => m.Is2D); + + /// + /// Computes the matrix of all transformations, applied in their order. + /// + /// The resulting transformation matrix. + /// A value cannot be converted to an absolute unit, e.g., em or %. + [DomName("toMatrix")] + public TransformMatrix ToMatrix() => _transforms + .Select(m => m.ToMatrix()) + .Aggregate(CssTransformComponent.Multiply); + + /// + /// Gets an enumerator over the transformations. + /// + public IEnumerator GetEnumerator() => _transforms.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + /// Serializes the transformations, e.g., translate(10px, 20px) rotate(45deg). + /// + public override String ToString() => String.Join(" ", _transforms.Select(m => m.ToString())); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssTranslate.cs b/src/AngleSharp.Css/TypedOm/CssTranslate.cs new file mode 100644 index 00000000..6989cbef --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssTranslate.cs @@ -0,0 +1,83 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using System; + + /// + /// Represents a translation, i.e., translate() or translate3d(). + /// https://www.w3.org/TR/css-typed-om-1/#csstranslate + /// + [DomName("CSSTranslate")] + public sealed class CssTranslate : CssTransformComponent + { + private CssNumericValue _x; + private CssNumericValue _y; + private CssNumericValue _z; + + /// + /// Creates a new translation. Without a z value it is a 2D translation. + /// + /// The shift along the x-axis (length or percentage). + /// The shift along the y-axis (length or percentage). + /// The optional shift along the z-axis (length). + /// A value has the wrong type. + [DomConstructor] + public CssTranslate(CssNumericValue x, CssNumericValue y, CssNumericValue? z = null) + : base(z is null) + { + _x = Require(x, nameof(x), IsLengthPercentage, "a length or percentage"); + _y = Require(y, nameof(y), IsLengthPercentage, "a length or percentage"); + _z = z is null ? new CssUnitValue(0.0, "px") : Require(z, nameof(z), IsLength, "a length"); + } + + /// + /// Gets or sets the shift along the x-axis. + /// + [DomName("x")] + public CssNumericValue X + { + get => _x; + set => _x = Require(value, nameof(value), IsLengthPercentage, "a length or percentage"); + } + + /// + /// Gets or sets the shift along the y-axis. + /// + [DomName("y")] + public CssNumericValue Y + { + get => _y; + set => _y = Require(value, nameof(value), IsLengthPercentage, "a length or percentage"); + } + + /// + /// Gets or sets the shift along the z-axis. + /// + [DomName("z")] + public CssNumericValue Z + { + get => _z; + set => _z = Require(value, nameof(value), IsLength, "a length"); + } + + /// + /// Computes the matrix of the translation. + /// + public override TransformMatrix ToMatrix() + { + var m = Identity(); + m[0, 3] = _x.To("px").Value; + m[1, 3] = _y.To("px").Value; + m[2, 3] = Is2D ? 0.0 : _z.To("px").Value; + return CreateMatrix(m); + } + + /// + /// Serializes the translation. + /// + public override String ToString() => Is2D ? + String.Concat("translate(", Join(_x, _y), ")") : + String.Concat("translate3d(", Join(_x, _y, _z), ")"); + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs b/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs new file mode 100644 index 00000000..89dfd249 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs @@ -0,0 +1,82 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Css.Dom; + using System; + using System.Collections.Generic; + using System.Runtime.CompilerServices; + + /// + /// Extensions to get typed values (CSS Typed OM) from the CSSOM. + /// + public static class CssTypedOmExtensions + { + private static readonly ConditionalWeakTable Maps = new(); + + /// + /// Gets the typed view of the given declarations. Changes made via the map are + /// applied to the declarations, and vice versa. + /// + /// The declarations, e.g., the style of a rule. + /// The (always same) map of the declarations. + public static IStylePropertyMap GetStyleMap(this ICssStyleDeclaration declaration) + { + if (declaration is null) + throw new ArgumentNullException(nameof(declaration)); + + return Maps.GetValue(declaration, m => new StylePropertyMap(m, null)); + } + + /// + /// Gets a read-only typed view of the given declarations, e.g., of a computed style. + /// The entries are sorted by name, with the custom properties last. + /// + /// The declarations, e.g., a computed style. + /// The read-only map of the declarations. + public static IStylePropertyMapReadOnly GetReadOnlyStyleMap(this ICssStyleDeclaration declaration) + { + if (declaration is null) + throw new ArgumentNullException(nameof(declaration)); + + return new StylePropertyMapReadOnly(declaration, null, true); + } + + /// + /// Gets the typed values of the given declaration, which are multiple for a + /// list-valued property, e.g., background-image. + /// + /// The declaration. + /// The typed values, which are empty if the declaration has no value. + public static IReadOnlyList ToStyleValues(this ICssProperty property) + { + if (property is null) + throw new ArgumentNullException(nameof(property)); + + return CssStyleValueReifier.ReifyAll(property.Name, property.RawValue); + } + + /// + /// Gets the (first) typed value of the given declaration. + /// + /// The declaration. + /// The typed value or null if the declaration has no value. + public static CssStyleValue? ToStyleValue(this ICssProperty property) + { + var values = property.ToStyleValues(); + return values.Count > 0 ? values[0] : null; + } + + /// + /// Gets the typed value of the given CSSOM value of a property. + /// + /// The value, e.g., the raw value of a declaration. + /// The name of the property the value belongs to. + /// The typed value. + public static CssStyleValue ToStyleValue(this ICssValue value, String property) + { + if (value is null) + throw new ArgumentNullException(nameof(value)); + + return CssStyleValueReifier.Reify(TypedOmProperties.Normalize(property), value); + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssUnitValue.cs b/src/AngleSharp.Css/TypedOm/CssUnitValue.cs new file mode 100644 index 00000000..95414847 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssUnitValue.cs @@ -0,0 +1,85 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents a single numeric value with a unit, e.g., 10px, 50%, or 2 (with + /// the unit "number"). + /// https://www.w3.org/TR/css-typed-om-1/#cssunitvalue + /// + [DomName("CSSUnitValue")] + public sealed class CssUnitValue : CssNumericValue + { + #region Fields + + private readonly String _unit; + + #endregion + + #region ctor + + /// + /// Creates a new unit value. + /// + /// The value, e.g., 10. + /// The unit, e.g., px, percent, or number. + /// The unit is unknown. + [DomConstructor] + public CssUnitValue(Double value, String unit) + : base(CreateType(unit)) + { + Value = value; + _unit = CssUnits.Normalize(unit); + } + + private static CssNumericType CreateType(String unit) + { + var normalized = CssUnits.Normalize(unit); + + if (!CssUnits.IsKnown(normalized)) + { + throw new ArgumentException($"The unit '{unit}' is unknown.", nameof(unit)); + } + + return CssNumericType.ForUnit(normalized); + } + + #endregion + + #region Properties + + /// + /// Gets or sets the numeric value. + /// + [DomName("value")] + public Double Value { get; set; } + + /// + /// Gets the unit, e.g., px, percent, or number. + /// + [DomName("unit")] + public String Unit => _unit; + + #endregion + + #region Internal Methods + + internal override void Serialize(StringBuilder sb, Boolean nested, Boolean parenless) => + sb.Append(CssUnits.Serialize(Value, _unit)); + + internal override Boolean IsEqualTo(CssNumericValue other) => + other is CssUnitValue unit && unit._unit == _unit && unit.Value.Equals(Value); + + internal override List? ToSumValue() + { + var value = Value; + var unit = CssUnits.ToCanonical(_unit, ref value); + return new List { CssSumValueItem.Create(value, unit) }; + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssUnits.cs b/src/AngleSharp.Css/TypedOm/CssUnits.cs new file mode 100644 index 00000000..26ebabe7 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssUnits.cs @@ -0,0 +1,194 @@ +namespace AngleSharp.Css.TypedOm +{ + using System; + using System.Collections.Generic; + + /// + /// The units known to the Typed OM, with their base type and, where the + /// unit is absolute, the factor converting it to the canonical unit. + /// https://www.w3.org/TR/css-typed-om-1/#numeric-typing + /// + static class CssUnits + { + public const String Number = "number"; + public const String Percent = "percent"; + + private static readonly Dictionary Units = new(StringComparer.Ordinal) + { + { Number, new UnitInfo(null, null, 1.0) }, + { Percent, new UnitInfo(CssNumericBaseType.Percent, null, 1.0) }, + + // absolute lengths + { "px", new UnitInfo(CssNumericBaseType.Length, "px", 1.0) }, + { "cm", new UnitInfo(CssNumericBaseType.Length, "px", 96.0 / 2.54) }, + { "mm", new UnitInfo(CssNumericBaseType.Length, "px", 96.0 / 25.4) }, + { "q", new UnitInfo(CssNumericBaseType.Length, "px", 96.0 / 101.6) }, + { "in", new UnitInfo(CssNumericBaseType.Length, "px", 96.0) }, + { "pt", new UnitInfo(CssNumericBaseType.Length, "px", 96.0 / 72.0) }, + { "pc", new UnitInfo(CssNumericBaseType.Length, "px", 16.0) }, + + // relative lengths + { "em", Relative(CssNumericBaseType.Length) }, + { "rem", Relative(CssNumericBaseType.Length) }, + { "ex", Relative(CssNumericBaseType.Length) }, + { "rex", Relative(CssNumericBaseType.Length) }, + { "ch", Relative(CssNumericBaseType.Length) }, + { "rch", Relative(CssNumericBaseType.Length) }, + { "ic", Relative(CssNumericBaseType.Length) }, + { "ric", Relative(CssNumericBaseType.Length) }, + { "cap", Relative(CssNumericBaseType.Length) }, + { "rcap", Relative(CssNumericBaseType.Length) }, + { "lh", Relative(CssNumericBaseType.Length) }, + { "rlh", Relative(CssNumericBaseType.Length) }, + { "vw", Relative(CssNumericBaseType.Length) }, + { "vh", Relative(CssNumericBaseType.Length) }, + { "vi", Relative(CssNumericBaseType.Length) }, + { "vb", Relative(CssNumericBaseType.Length) }, + { "vmin", Relative(CssNumericBaseType.Length) }, + { "vmax", Relative(CssNumericBaseType.Length) }, + { "svw", Relative(CssNumericBaseType.Length) }, + { "svh", Relative(CssNumericBaseType.Length) }, + { "svi", Relative(CssNumericBaseType.Length) }, + { "svb", Relative(CssNumericBaseType.Length) }, + { "svmin", Relative(CssNumericBaseType.Length) }, + { "svmax", Relative(CssNumericBaseType.Length) }, + { "lvw", Relative(CssNumericBaseType.Length) }, + { "lvh", Relative(CssNumericBaseType.Length) }, + { "lvi", Relative(CssNumericBaseType.Length) }, + { "lvb", Relative(CssNumericBaseType.Length) }, + { "lvmin", Relative(CssNumericBaseType.Length) }, + { "lvmax", Relative(CssNumericBaseType.Length) }, + { "dvw", Relative(CssNumericBaseType.Length) }, + { "dvh", Relative(CssNumericBaseType.Length) }, + { "dvi", Relative(CssNumericBaseType.Length) }, + { "dvb", Relative(CssNumericBaseType.Length) }, + { "dvmin", Relative(CssNumericBaseType.Length) }, + { "dvmax", Relative(CssNumericBaseType.Length) }, + { "cqw", Relative(CssNumericBaseType.Length) }, + { "cqh", Relative(CssNumericBaseType.Length) }, + { "cqi", Relative(CssNumericBaseType.Length) }, + { "cqb", Relative(CssNumericBaseType.Length) }, + { "cqmin", Relative(CssNumericBaseType.Length) }, + { "cqmax", Relative(CssNumericBaseType.Length) }, + + // angles + { "deg", new UnitInfo(CssNumericBaseType.Angle, "deg", 1.0) }, + { "rad", new UnitInfo(CssNumericBaseType.Angle, "deg", 180.0 / Math.PI) }, + { "grad", new UnitInfo(CssNumericBaseType.Angle, "deg", 0.9) }, + { "turn", new UnitInfo(CssNumericBaseType.Angle, "deg", 360.0) }, + + // times + { "ms", new UnitInfo(CssNumericBaseType.Time, "ms", 1.0) }, + { "s", new UnitInfo(CssNumericBaseType.Time, "ms", 1000.0) }, + + // frequencies + { "hz", new UnitInfo(CssNumericBaseType.Frequency, "hz", 1.0) }, + { "khz", new UnitInfo(CssNumericBaseType.Frequency, "hz", 1000.0) }, + + // resolutions + { "dppx", new UnitInfo(CssNumericBaseType.Resolution, "dppx", 1.0) }, + { "x", new UnitInfo(CssNumericBaseType.Resolution, "dppx", 1.0) }, + { "dpi", new UnitInfo(CssNumericBaseType.Resolution, "dppx", 1.0 / 96.0) }, + { "dpcm", new UnitInfo(CssNumericBaseType.Resolution, "dppx", 2.54 / 96.0) }, + + // flexible lengths + { "fr", Relative(CssNumericBaseType.Flex) }, + }; + + private static UnitInfo Relative(CssNumericBaseType type) => new(type, null, 1.0); + + /// + /// Normalizes the given unit, i.e., lower cases it and maps "%" to "percent". + /// + public static String Normalize(String unit) + { + if (unit is null) + { + return String.Empty; + } + + var lower = unit.ToLowerInvariant(); + return lower == "%" ? Percent : lower; + } + + /// + /// Checks if the (normalized) unit is known. + /// + public static Boolean IsKnown(String unit) => Units.ContainsKey(unit); + + /// + /// Gets the base type of the (normalized and known) unit, if any. + /// + public static CssNumericBaseType? GetBaseType(String unit) => Units[unit].BaseType; + + /// + /// Gets the canonical unit (and the converted value) for the given unit, which is the + /// unit itself for units that cannot be converted. + /// + public static String ToCanonical(String unit, ref Double value) + { + var info = Units[unit]; + + if (info.Canonical is not null) + { + value *= info.Factor; + return info.Canonical; + } + + return unit; + } + + /// + /// Tries to convert the value from one unit to another one. + /// + public static Boolean TryConvert(Double value, String from, String to, out Double result) + { + result = value; + + if (from == to) + { + return true; + } + + if (Units.TryGetValue(from, out var source) && Units.TryGetValue(to, out var target) && + source.Canonical is not null && source.Canonical == target.Canonical) + { + result = value * source.Factor / target.Factor; + return true; + } + + return false; + } + + /// + /// Gets the serialization of a value in the given unit. + /// + public static String Serialize(Double value, String unit) + { + var text = value.CssStringify(); + + return unit switch + { + Number => text, + Percent => text + "%", + _ => text + unit, + }; + } + + private readonly struct UnitInfo + { + public UnitInfo(CssNumericBaseType? baseType, String? canonical, Double factor) + { + BaseType = baseType; + Canonical = canonical; + Factor = factor; + } + + public CssNumericBaseType? BaseType { get; } + + public String? Canonical { get; } + + public Double Factor { get; } + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssUnparsedValue.cs b/src/AngleSharp.Css/TypedOm/CssUnparsedValue.cs new file mode 100644 index 00000000..a2760870 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssUnparsedValue.cs @@ -0,0 +1,331 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Parser; + using AngleSharp.Text; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + /// + /// Represents a value that is kept as text, e.g., the value of a custom property + /// or a value referencing custom properties. The segments are either strings or + /// references to custom properties, i.e., . + /// https://www.w3.org/TR/css-typed-om-1/#cssunparsedvalue + /// + [DomName("CSSUnparsedValue")] + public sealed class CssUnparsedValue : CssStyleValue, IReadOnlyList + { + #region Fields + + private readonly List _segments; + + #endregion + + #region ctor + + /// + /// Creates a new unparsed value from the given segments. + /// + /// The segments, i.e., strings or variable references. + /// A segment is neither a string nor a variable reference. + [DomConstructor] + public CssUnparsedValue(IEnumerable members) + { + _segments = (members ?? throw new ArgumentNullException(nameof(members))).Select(Validate).ToList(); + } + + private CssUnparsedValue(List segments) + { + _segments = segments; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the segment at the given index. Setting the index right after + /// the last segment appends a segment. + /// + /// A segment is neither a string nor a variable reference. + [DomName("item")] + public Object this[Int32 index] + { + get => _segments[index]; + set + { + if (index == _segments.Count) + { + _segments.Add(Validate(value)); + } + else + { + _segments[index] = Validate(value); + } + } + } + + /// + /// Gets the number of segments. + /// + [DomName("length")] + public Int32 Length => _segments.Count; + + Int32 IReadOnlyCollection.Count => _segments.Count; + + #endregion + + #region Methods + + /// + /// Gets an enumerator over the segments. + /// + public IEnumerator GetEnumerator() => _segments.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + /// Serializes the value, i.e., concatenates the segments. + /// + public override String ToString() + { + var sb = new StringBuilder(); + + foreach (var segment in _segments) + { + sb.Append(segment.ToString()); + } + + return sb.ToString(); + } + + #endregion + + #region Parsing + + /// + /// Splits the given text into strings and references to custom properties. + /// + internal static CssUnparsedValue FromText(String text) => FromText(text, 0); + + // The fallback of a reference is parsed recursively, which stops (keeping the + // fallback as text) at the depth of nested values the parsers allow. + private static CssUnparsedValue FromText(String text, Int32 depth) + { + var segments = new List(); + var start = 0; + var i = 0; + + while (i < text.Length) + { + var c = text[i]; + + if (c is Symbols.DoubleQuote or Symbols.SingleQuote) + { + i = SkipString(text, i); + } + else if (c == Symbols.ReverseSolidus) + { + i = Math.Min(i + 2, text.Length); + } + else if (c == Symbols.Solidus && i + 1 < text.Length && text[i + 1] == Symbols.Asterisk) + { + var end = text.IndexOf("*/", i + 2, StringComparison.Ordinal); + i = end < 0 ? text.Length : end + 2; + } + else if (IsVarFunction(text, i) && TryParseReference(text, i, depth, out var reference, out var next)) + { + if (i > start) + { + segments.Add(text.Substring(start, i - start)); + } + + segments.Add(reference!); + start = i = next; + } + else + { + i++; + } + } + + if (start < text.Length) + { + segments.Add(text.Substring(start)); + } + + return new CssUnparsedValue(segments); + } + + private static Boolean IsVarFunction(String text, Int32 index) + { + if (index + 4 > text.Length || String.Compare(text, index, "var(", 0, 4, StringComparison.OrdinalIgnoreCase) != 0) + { + return false; + } + + // must not be the end of another name, e.g., somevar( + if (index > 0) + { + var previous = text[index - 1]; + + if (previous.IsName() || previous == Symbols.ReverseSolidus) + { + return false; + } + } + + return true; + } + + private static Boolean TryParseReference(String text, Int32 index, Int32 depth, out CssVariableReferenceValue? reference, out Int32 next) + { + var open = index + 4; + var close = FindClosingParenthesis(text, open); + reference = null; + next = close + 1; + + if (close < 0) + { + return false; + } + + var comma = FindTopLevelComma(text, open, close); + var name = text.Substring(open, (comma < 0 ? close : comma) - open).Trim(); + + if (!name.StartsWith("--", StringComparison.Ordinal) || name.Length < 3) + { + return false; + } + + var fallback = default(CssUnparsedValue); + + if (comma >= 0) + { + var fallbackText = text.Substring(comma + 1, close - comma - 1); + fallback = depth + 1 < ValueNesting.Limit ? + FromText(fallbackText, depth + 1) : + new CssUnparsedValue(new List { fallbackText }); + } + + reference = new CssVariableReferenceValue(name, fallback); + return true; + } + + private static Int32 FindClosingParenthesis(String text, Int32 start) + { + var level = 0; + var i = start; + + while (i < text.Length) + { + var c = text[i]; + + if (c is Symbols.DoubleQuote or Symbols.SingleQuote) + { + i = SkipString(text, i); + continue; + } + else if (c == Symbols.ReverseSolidus) + { + i += 2; + continue; + } + else if (c == Symbols.RoundBracketOpen) + { + level++; + } + else if (c == Symbols.RoundBracketClose) + { + if (level == 0) + { + return i; + } + + level--; + } + + i++; + } + + return -1; + } + + private static Int32 FindTopLevelComma(String text, Int32 start, Int32 end) + { + var level = 0; + var i = start; + + while (i < end) + { + var c = text[i]; + + if (c is Symbols.DoubleQuote or Symbols.SingleQuote) + { + i = SkipString(text, i); + continue; + } + else if (c == Symbols.ReverseSolidus) + { + i += 2; + continue; + } + else if (c == Symbols.RoundBracketOpen) + { + level++; + } + else if (c == Symbols.RoundBracketClose) + { + level--; + } + else if (c == Symbols.Comma && level == 0) + { + return i; + } + + i++; + } + + return -1; + } + + private static Int32 SkipString(String text, Int32 index) + { + var quote = text[index]; + var i = index + 1; + + while (i < text.Length) + { + var c = text[i]; + + if (c == Symbols.ReverseSolidus) + { + i += 2; + } + else if (c == quote) + { + return i + 1; + } + else + { + i++; + } + } + + return text.Length; + } + + private static Object Validate(Object segment) => segment switch + { + String text => text, + CssVariableReferenceValue reference => reference, + null => throw new ArgumentNullException(nameof(segment)), + _ => throw new ArgumentException("A segment has to be a string or a variable reference.", nameof(segment)), + }; + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssUnsupportedValue.cs b/src/AngleSharp.Css/TypedOm/CssUnsupportedValue.cs new file mode 100644 index 00000000..ac1dd20d --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssUnsupportedValue.cs @@ -0,0 +1,28 @@ +namespace AngleSharp.Css.TypedOm +{ + using System; + + /// + /// A value without a more specific representation in the Typed OM, which is + /// tied to the property it was obtained for. + /// https://www.w3.org/TR/css-typed-om-1/#reify-as-a-cssstylevalue + /// + sealed class CssUnsupportedValue : CssStyleValue + { + private readonly String _property; + private readonly String _text; + + public CssUnsupportedValue(String property, String text) + { + _property = property; + _text = text; + } + + /// + /// Gets the name of the property the value belongs to. + /// + public String Property => _property; + + public override String ToString() => _text; + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssVariableReferenceValue.cs b/src/AngleSharp.Css/TypedOm/CssVariableReferenceValue.cs new file mode 100644 index 00000000..71b883e6 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/CssVariableReferenceValue.cs @@ -0,0 +1,63 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + + /// + /// Represents a reference to a custom property, i.e., var(--name, fallback), + /// within an unparsed value. + /// https://www.w3.org/TR/css-typed-om-1/#cssvariablereferencevalue + /// + [DomName("CSSVariableReferenceValue")] + public sealed class CssVariableReferenceValue + { + private String _variable; + + /// + /// Creates a new reference to a custom property. + /// + /// The name of the custom property, e.g., --main-color. + /// The optional fallback value. + /// The name is not a custom property name. + [DomConstructor] + public CssVariableReferenceValue(String variable, CssUnparsedValue? fallback = null) + { + _variable = Validate(variable); + Fallback = fallback; + } + + /// + /// Gets or sets the name of the referenced custom property. + /// + /// The name is not a custom property name. + [DomName("variable")] + public String Variable + { + get => _variable; + set => _variable = Validate(value); + } + + /// + /// Gets the fallback value, if any. + /// + [DomName("fallback")] + public CssUnparsedValue? Fallback { get; } + + /// + /// Serializes the reference, i.e., var(--name) or var(--name,fallback). + /// + public override String ToString() => Fallback is null ? + String.Concat("var(", _variable, ")") : + String.Concat("var(", _variable, ",", Fallback.ToString(), ")"); + + private static String Validate(String variable) + { + if (variable is null || !variable.StartsWith("--", StringComparison.Ordinal)) + { + throw new ArgumentException("The name of a custom property has to start with '--'.", nameof(variable)); + } + + return variable; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs b/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs new file mode 100644 index 00000000..327b7132 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs @@ -0,0 +1,28 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + + /// + /// Extends elements with the typed map of their computed style. + /// https://www.w3.org/TR/css-typed-om-1/#computed-stylepropertymapreadonly-objects + /// + [DomExposed("Element")] + public static class ElementComputedStyleMapExtensions + { + /// + /// Gets the typed map of the element's computed style, as script sees it. The map + /// shows the computed style at the time of the call. + /// + /// The element. + /// The map or null if the element is not in a document with a window. + [DomName("computedStyleMap")] + public static IStylePropertyMapReadOnly? ComputedStyleMap(this IElement element) + { + var window = element.Owner?.DefaultView; + var style = window?.GetComputedStyleOfScript(element); + return style is not null ? new StylePropertyMapReadOnly(style, element.Owner?.Context, true) : null; + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs b/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs new file mode 100644 index 00000000..26cfca5c --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs @@ -0,0 +1,25 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + + /// + /// Extends elements with the typed map of their inline style. + /// https://www.w3.org/TR/css-typed-om-1/#declared-stylepropertymap-objects + /// + [DomExposed("HTMLElement")] + [DomExposed("SVGElement")] + public static class ElementStyleMapExtensions + { + /// + /// Gets the typed map of the element's inline style, i.e., of its style attribute. + /// + /// The element. + /// The map or null if the element's context has no CSS support. + [DomName("attributeStyleMap")] + [DomAccessor(Accessors.Getter)] + public static IStylePropertyMap? GetAttributeStyleMap(this IElement element) => + element.GetStyle()?.GetStyleMap(); + } +} diff --git a/src/AngleSharp.Css/TypedOm/IStylePropertyMap.cs b/src/AngleSharp.Css/TypedOm/IStylePropertyMap.cs new file mode 100644 index 00000000..b1ee6b6f --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/IStylePropertyMap.cs @@ -0,0 +1,65 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + + /// + /// A map from properties to their typed values, which writes to the underlying + /// declarations, e.g., the inline style of an element. + /// https://www.w3.org/TR/css-typed-om-1/#stylepropertymap + /// + [DomName("StylePropertyMap")] + public interface IStylePropertyMap : IStylePropertyMapReadOnly + { + /// + /// Sets the value of the given property. Multiple values are only allowed for + /// list-valued properties, e.g., background-image. + /// + /// The name of the property, e.g., width. + /// The values to set. + /// The property is not supported or the values are not valid for it. + [DomName("set")] + void Set(String property, params CssStyleValue[] values); + + /// + /// Sets the value of the given property from its CSS text. + /// + /// The name of the property, e.g., width. + /// The CSS text of the value, e.g., 10px. + /// The property is not supported or the value is not valid for it. + [DomName("set")] + void Set(String property, String value); + + /// + /// Appends the values to the given list-valued property, e.g., background-image. + /// + /// The name of the property, e.g., background-image. + /// The values to append. + /// The property is not list-valued or the values are not valid for it. + [DomName("append")] + void Append(String property, params CssStyleValue[] values); + + /// + /// Appends the value given by its CSS text to the given list-valued property. + /// + /// The name of the property, e.g., background-image. + /// The CSS text of the value(s) to append. + /// The property is not list-valued or the value is not valid for it. + [DomName("append")] + void Append(String property, String value); + + /// + /// Removes the value of the given property. + /// + /// The name of the property, e.g., width. + /// The property is not supported. + [DomName("delete")] + void Delete(String property); + + /// + /// Removes all values. + /// + [DomName("clear")] + void Clear(); + } +} diff --git a/src/AngleSharp.Css/TypedOm/IStylePropertyMapReadOnly.cs b/src/AngleSharp.Css/TypedOm/IStylePropertyMapReadOnly.cs new file mode 100644 index 00000000..443d7aeb --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/IStylePropertyMapReadOnly.cs @@ -0,0 +1,49 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + + /// + /// A read-only map from properties to their typed values, e.g., of the + /// computed style of an element. + /// https://www.w3.org/TR/css-typed-om-1/#stylepropertymapreadonly + /// + [DomName("StylePropertyMapReadOnly")] + public interface IStylePropertyMapReadOnly : IEnumerable>> + { + /// + /// Gets the (first) value of the given property. + /// + /// The name of the property, e.g., width. + /// The value or null if the property has no value. + /// The property is not supported. + [DomName("get")] + CssStyleValue? Get(String property); + + /// + /// Gets all values of the given property, e.g., the single images of a + /// background-image. + /// + /// The name of the property, e.g., background-image. + /// The values, which are empty if the property has no value. + /// The property is not supported. + [DomName("getAll")] + IReadOnlyList GetAll(String property); + + /// + /// Checks if the given property has a value. + /// + /// The name of the property, e.g., width. + /// True if the property has a value, otherwise false. + /// The property is not supported. + [DomName("has")] + Boolean Has(String property); + + /// + /// Gets the number of properties with a value. + /// + [DomName("size")] + Int32 Size { get; } + } +} diff --git a/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs b/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs new file mode 100644 index 00000000..88057748 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs @@ -0,0 +1,121 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Values; + using AngleSharp.Text; + using System; + using System.Linq; + + /// + /// A writable view of style declarations as typed values. The typed values are + /// serialized and validated by the converter of the property, i.e., the same way + /// as values set via the CSSOM. + /// + sealed class StylePropertyMap : StylePropertyMapReadOnly, IStylePropertyMap + { + #region ctor + + public StylePropertyMap(ICssStyleDeclaration declaration, IBrowsingContext? context) + : base(declaration, context, false) + { + } + + #endregion + + #region Methods + + public void Set(String property, params CssStyleValue[] values) + { + var name = Validate(property); + Update(name, GetTexts(name, values), false); + } + + public void Set(String property, String value) + { + var name = Validate(property); + Update(name, new[] { value ?? throw new ArgumentNullException(nameof(value)) }, false); + } + + public void Append(String property, params CssStyleValue[] values) + { + var name = Validate(property); + Update(name, GetTexts(name, values), true); + } + + public void Append(String property, String value) + { + var name = Validate(property); + Update(name, new[] { value ?? throw new ArgumentNullException(nameof(value)) }, true); + } + + public void Delete(String property) + { + var name = Validate(property); + Declaration.RemoveProperty(name); + } + + public void Clear() => Declaration.CssText = String.Empty; + + #endregion + + #region Helpers + + private static String[] GetTexts(String name, CssStyleValue[] values) + { + if (values is null) + throw new ArgumentNullException(nameof(values)); + + return values.Select(value => value switch + { + null => throw new ArgumentNullException(nameof(values)), + CssUnsupportedValue unsupported when unsupported.Property != name => + throw new ArgumentException($"The value was obtained for '{unsupported.Property}' and cannot be used for '{name}'.", nameof(values)), + _ => value.ToString(), + }).ToArray(); + } + + private void Update(String name, String[] texts, Boolean append) + { + var custom = TypedOmProperties.IsCustom(name); + + if (texts.Length == 0) + { + throw new ArgumentException("At least one value is required.", nameof(texts)); + } + + if (custom && (append || texts.Length > 1)) + { + throw new ArgumentException($"The custom property '{name}' is not list-valued.", nameof(name)); + } + + var text = String.Join(", ", texts); + + if (append) + { + var existing = Declaration.GetPropertyValue(name); + text = String.IsNullOrEmpty(existing) ? text : String.Concat(existing, ", ", text); + } + + var property = TypedOmProperties.Parse(Context, name, text); + + if ((append || texts.Length > 1) && property.RawValue is not CssListValue && property.RawValue is not CssReferenceValue) + { + throw new ArgumentException($"The property '{name}' is not list-valued.", nameof(name)); + } + + property.IsImportant = Declaration.GetPropertyPriority(name).Isi(CssKeywords.Important); + + if (Declaration is CssStyleDeclaration declaration) + { + // avoids parsing the text once more + declaration.SetParsedProperty(property); + } + else + { + Declaration.SetProperty(name, text, property.IsImportant ? CssKeywords.Important : null); + } + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs b/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs new file mode 100644 index 00000000..e1774915 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs @@ -0,0 +1,133 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Css.Dom; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + /// + /// A view of style declarations as typed values. Nothing is copied: the values + /// are reified from the declarations whenever they are requested. + /// + class StylePropertyMapReadOnly : IStylePropertyMapReadOnly + { + #region Fields + + private readonly ICssStyleDeclaration _declaration; + private readonly IBrowsingContext? _context; + private readonly Boolean _sorted; + + #endregion + + #region ctor + + public StylePropertyMapReadOnly(ICssStyleDeclaration declaration, IBrowsingContext? context, Boolean sorted) + { + _declaration = declaration; + _context = context ?? (declaration as CssStyleDeclaration)?.Context; + _sorted = sorted; + } + + #endregion + + #region Properties + + protected ICssStyleDeclaration Declaration => _declaration; + + protected IBrowsingContext? Context => _context; + + public Int32 Size => GetNames().Count(name => GetAllCore(name).Count > 0); + + #endregion + + #region Methods + + public CssStyleValue? Get(String property) + { + var values = GetAll(property); + return values.Count > 0 ? values[0] : null; + } + + public IReadOnlyList GetAll(String property) => GetAllCore(Validate(property)); + + public Boolean Has(String property) => !String.IsNullOrEmpty(_declaration.GetPropertyValue(Validate(property))); + + public IEnumerator>> GetEnumerator() + { + foreach (var name in GetNames()) + { + var values = GetAllCore(name); + + if (values.Count > 0) + { + yield return new KeyValuePair>(name, values); + } + } + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + #endregion + + #region Helpers + + protected String Validate(String property) + { + var name = TypedOmProperties.Normalize(property); + TypedOmProperties.GetInfo(_context, name); + return name; + } + + private IReadOnlyList GetAllCore(String name) + { + // the text also covers used values, e.g., of a computed style + var text = _declaration.GetPropertyValue(name); + + if (String.IsNullOrEmpty(text)) + { + return Array.Empty(); + } + + var property = _declaration.GetProperty(name); + var value = property is not null && property.RawValue is not null && property.Value == text ? + property.RawValue : + TryParse(name, text); + + return value is not null ? + CssStyleValueReifier.ReifyAll(name, value) : + new CssStyleValue[] { new CssUnsupportedValue(name, text) }; + } + + private ICssValue? TryParse(String name, String text) + { + try + { + return TypedOmProperties.Parse(_context, name, text).RawValue; + } + catch (ArgumentException) + { + return null; + } + } + + private List GetNames() + { + var names = _declaration.Select(m => m.Name).Distinct(StringComparer.Ordinal).ToList(); + + if (_sorted) + { + // the standard properties come first, followed by the custom properties + names.Sort((a, b) => + { + var custom = TypedOmProperties.IsCustom(a).CompareTo(TypedOmProperties.IsCustom(b)); + return custom != 0 ? custom : String.CompareOrdinal(a, b); + }); + } + + return names; + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/TypedOm/StyleRuleStyleMapExtensions.cs b/src/AngleSharp.Css/TypedOm/StyleRuleStyleMapExtensions.cs new file mode 100644 index 00000000..d62c7807 --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/StyleRuleStyleMapExtensions.cs @@ -0,0 +1,22 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Dom; + + /// + /// Extends style rules with the typed map of their declarations. + /// https://www.w3.org/TR/css-typed-om-1/#declared-stylepropertymap-objects + /// + [DomExposed("CSSStyleRule")] + public static class StyleRuleStyleMapExtensions + { + /// + /// Gets the typed map of the rule's declarations. + /// + /// The style rule. + /// The map of the rule's declarations. + [DomName("styleMap")] + [DomAccessor(Accessors.Getter)] + public static IStylePropertyMap GetStyleMap(this ICssStyleRule rule) => rule.Style.GetStyleMap(); + } +} diff --git a/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs b/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs new file mode 100644 index 00000000..d9d1d94e --- /dev/null +++ b/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs @@ -0,0 +1,61 @@ +namespace AngleSharp.Css.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Text; + using System; + + /// + /// Helpers for resolving and parsing properties for the Typed OM, which use the + /// declarations (and converters) of the browsing context. + /// + static class TypedOmProperties + { + // used without a browsing context, e.g., for CSSStyleValue.parse + private static readonly DefaultDeclarationFactory DefaultFactory = new(); + + public static Boolean IsCustom(String name) => name.StartsWith("--", StringComparison.Ordinal); + + public static String Normalize(String name) + { + if (name is null) + throw new ArgumentNullException(nameof(name)); + + return IsCustom(name) ? name : name.ToLowerFast(); + } + + /// + /// Gets the declaration info of a known property, or throws (TypeError). + /// + public static DeclarationInfo GetInfo(IBrowsingContext? context, String name) + { + var info = context is not null ? context.GetDeclarationInfo(name) : DefaultFactory.Create(name); + + if (info is null || (info.Flags == PropertyFlags.Unknown && !IsCustom(name))) + { + throw new ArgumentException($"The property '{name}' is not supported.", nameof(name)); + } + + return info; + } + + /// + /// Parses the text for the given property, or throws (TypeError) if it is invalid. + /// + public static CssProperty Parse(IBrowsingContext? context, String name, String text) + { + name = Normalize(name); + var info = GetInfo(context, name); + var property = new CssProperty(name, info.Converter, info.Flags) + { + Value = text, + }; + + if (property.RawValue is null) + { + throw new ArgumentException($"The value '{text}' is not valid for the property '{name}'.", nameof(text)); + } + + return property; + } + } +} diff --git a/src/Directory.Build.props b/src/Directory.Build.props index f742b6d0..46acf4d8 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.4.2 + 1.5.0 enable latest true From b74846f4349c847f9322050053a21b57e5f4704a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 11:47:36 +0100 Subject: [PATCH 02/12] Added support for @property #274 --- CHANGELOG.md | 2 + docs/general/07-Supported-At-Rules.md | 2 +- docs/general/09-Typed-OM.md | 2 +- .../Rules/CssPropertyRuleTests.cs | 180 ++++++++++++ .../Styling/RegisterPropertyTests.cs | 195 +++++++++++++ .../Styling/RegisteredCustomPropertyTests.cs | 243 ++++++++++++++++ src/AngleSharp.Css/Constants/CssKeywords.cs | 20 ++ src/AngleSharp.Css/Constants/FunctionNames.cs | 5 + .../Dom/CssHelpers.Properties.cs | 69 +++++ src/AngleSharp.Css/Dom/ICssPropertyRule.cs | 27 ++ .../Dom/Internal/CssProperty.cs | 10 +- .../Dom/Internal/Rules/CssDescriptorRule.cs | 12 + .../Dom/Internal/Rules/CssPropertyRule.cs | 69 +++++ .../Dom/Internal/StyleCollection.cs | 33 ++- src/AngleSharp.Css/Dom/PropertyDefinition.cs | 40 +++ .../Extensions/CssApiExtensions.cs | 2 +- .../Extensions/CssOmExtensions.cs | 29 ++ .../Extensions/StyleCollectionExtensions.cs | 6 +- .../RenderTree/RenderTreeBuilder.cs | 4 +- .../TypedOm/CssStyleValueReifier.cs | 9 +- .../Values/CssComputeContext.cs | 21 +- .../Values/CssCustomPropertyResolver.cs | 212 +++++++++++++- .../Values/CssPropertyRegistration.cs | 176 ++++++++++++ .../Values/CssPropertySyntax.cs | 268 ++++++++++++++++++ 24 files changed, 1619 insertions(+), 17 deletions(-) create mode 100644 src/AngleSharp.Css.Tests/Rules/CssPropertyRuleTests.cs create mode 100644 src/AngleSharp.Css.Tests/Styling/RegisterPropertyTests.cs create mode 100644 src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs create mode 100644 src/AngleSharp.Css/Dom/CssHelpers.Properties.cs create mode 100644 src/AngleSharp.Css/Dom/PropertyDefinition.cs create mode 100644 src/AngleSharp.Css/Values/CssPropertyRegistration.cs create mode 100644 src/AngleSharp.Css/Values/CssPropertySyntax.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index af27d378..c4bfe95f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ Released on tbd. +- Added support for registered custom properties via `@property` (#274): the rule validates its descriptors (`syntax`, `inherits`, `initial-value`) and exposes them on `ICssPropertyRule` (`Syntax`, `Inherits`, `InitialValue`, `IsValid`), and a valid registration makes the custom property match its syntax (otherwise it is invalid at computed-value time), have its initial value, be computed (e.g., `2em` to `32px`), and only be inherited if registered so +- Added `CSS.registerProperty()` (`RegisterProperty` on `CssHelpers` for a window or a document, with a `PropertyDefinition`), which registers a custom property for the document like `@property` does and wins over `@property` rules of the same name; an invalid definition is a `SyntaxError`, registering a name twice an `InvalidModificationError` - Added the CSS Typed OM (#276) in the `AngleSharp.Css.TypedOm` namespace: typed values (`CssUnitValue`, `CssKeywordValue`, `CssUnparsedValue`, the math values such as `CssMathSum`, `CssTransformValue`, `CssPositionValue`, `CssImageValue`) with unit-aware arithmetic and conversions, the `CSS.px()`-style factories on `CssHelpers`, and style property maps over declared (`attributeStyleMap`, `styleMap` of a rule) and computed (`computedStyleMap()`) styles, which read from and write to the existing declarations # 1.4.2 diff --git a/docs/general/07-Supported-At-Rules.md b/docs/general/07-Supported-At-Rules.md index 2157d3a3..b5824136 100644 --- a/docs/general/07-Supported-At-Rules.md +++ b/docs/general/07-Supported-At-Rules.md @@ -27,7 +27,7 @@ This page documents the at-rules recognized by the AngleSharp.Css parser (`CssBu | `@container` | CSS Containment / Container Queries | Parsed into `CssContainerRule` with nested rules. | Condition text parsing is syntax-driven; unsupported condition forms may be rejected. | | `@layer` | CSS Cascade Layers | Parsed into `CssLayerRule` (statement and block forms). | Layer ordering semantics beyond parsed structure are not enforced by a rendering engine here. | | `@scope` | CSS Scoping | Parsed into `CssScopeRule` with nested rules. | Scope prelude is stored as text; advanced selector semantics depend on parser support. | -| `@property` | CSS Properties and Values API | Parsed into `CssPropertyRule` with descriptor storage. | Descriptors are generic properties (`CssDescriptorRule`) without spec-specific descriptor type validation. | +| `@property` | CSS Properties and Values API | Parsed into `CssPropertyRule` (`Syntax`, `Inherits`, `InitialValue`, `IsValid`). Valid rules register the custom property: values are validated against the syntax and computed, the initial value and inheritance apply. | Registration follows the conditions of enclosing `@media` / `@supports` rules like style rules. Script can register custom properties with `CSS.registerProperty()` (`window.RegisterProperty(new PropertyDefinition { ... })`), which wins over `@property` for the same name. | | `@starting-style` | CSS Transitions Level 2 | Parsed into `CssStartingStyleRule` with nested rules. | Behavior-level transition semantics are not evaluated. | | `@view-transition` | View Transitions | Parsed into `CssViewTransitionRule` with descriptor storage. | Descriptors are stored generically, without dedicated descriptor schema validation. | | `@position-try` | CSS Anchor Positioning | Parsed into `CssPositionTryRule` with declaration block. | No layout fallback engine; parsing/serialization only. | diff --git a/docs/general/09-Typed-OM.md b/docs/general/09-Typed-OM.md index bbcc91ee..c0616661 100644 --- a/docs/general/09-Typed-OM.md +++ b/docs/general/09-Typed-OM.md @@ -74,4 +74,4 @@ var t = b.Type(); // length: 1 - The computed style map is a snapshot of the computed style at the time of the call. - Colors and other values beyond the Typed OM Level 1 are given as plain `CssStyleValue`. -- Registered custom properties (`@property`) are still given as `CssUnparsedValue`. +- Custom properties are given as `CssUnparsedValue`, except for the computed values of registered ones (`@property`), which are typed according to their syntax, e.g., a `CssUnitValue` for ``. diff --git a/src/AngleSharp.Css.Tests/Rules/CssPropertyRuleTests.cs b/src/AngleSharp.Css.Tests/Rules/CssPropertyRuleTests.cs new file mode 100644 index 00000000..f58f9bfb --- /dev/null +++ b/src/AngleSharp.Css.Tests/Rules/CssPropertyRuleTests.cs @@ -0,0 +1,180 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Rules +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Values; + using NUnit.Framework; + using System; + using static CssConstructionFunctions; + + [TestFixture] + public class CssPropertyRuleTests + { + private static ICssPropertyRule ParseRule(String source) => + (ICssPropertyRule)ParseStyleSheet(source).Rules[0]; + + [Test] + public void ValidRuleExposesItsDescriptors() + { + var rule = ParseRule("@property --my-color { syntax: \"\"; inherits: false; initial-value: #c0ffee; }"); + + Assert.AreEqual("--my-color", rule.Name); + Assert.AreEqual("", rule.Syntax); + Assert.IsFalse(rule.Inherits); + Assert.AreEqual("#c0ffee", rule.InitialValue); + Assert.IsTrue(rule.IsValid); + } + + [Test] + public void InheritsIsCaseInsensitive() + { + var rule = ParseRule("@property --x { syntax: \"*\"; inherits: TRUE; }"); + Assert.IsTrue(rule.Inherits); + Assert.IsTrue(rule.IsValid); + } + + [Test] + public void UniversalSyntaxNeedsNoInitialValue() + { + var rule = ParseRule("@property --x { syntax: \"*\"; inherits: false; }"); + Assert.IsTrue(rule.IsValid); + Assert.IsNull(rule.InitialValue); + } + + [Test] + public void InvalidSyntaxDescriptorIsIgnored() + { + var rule = ParseRule("@property --x { syntax: \"\"; inherits: false; initial-value: 1px; }"); + Assert.AreEqual(String.Empty, rule.GetPropertyValue("syntax")); + Assert.AreEqual(String.Empty, rule.Syntax); + Assert.IsFalse(rule.IsValid); + } + + [Test] + public void SyntaxMustBeAString() + { + var rule = ParseRule("@property --x { syntax: ; inherits: false; initial-value: 1px; }"); + Assert.AreEqual(String.Empty, rule.GetPropertyValue("syntax")); + Assert.IsFalse(rule.IsValid); + } + + [Test] + public void InvalidInheritsDescriptorIsIgnored() + { + var rule = ParseRule("@property --x { syntax: \"\"; inherits: maybe; initial-value: 1px; }"); + Assert.AreEqual(String.Empty, rule.GetPropertyValue("inherits")); + Assert.IsFalse(rule.IsValid); + } + + [Test] + public void InvalidDescriptorKeepsAnEarlierValidOne() + { + var rule = ParseRule("@property --x { syntax: \"\"; syntax: \"\"; inherits: false; initial-value: 1px; }"); + Assert.AreEqual("", rule.Syntax); + Assert.IsTrue(rule.IsValid); + } + + [Test] + public void UnknownDescriptorsAreIgnoredWithoutInvalidatingTheRule() + { + var rule = ParseRule("@property --x { syntax: \"\"; foo: bar; inherits: false; initial-value: 1px; }"); + Assert.AreEqual(String.Empty, rule.GetPropertyValue("foo")); + Assert.IsTrue(rule.IsValid); + } + + [TestCase("@property --x { inherits: false; initial-value: 1px; }")] + [TestCase("@property --x { syntax: \"\"; initial-value: 1px; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: red; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: 2em; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: calc(1px + 1rem); }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: var(--y); }")] + [TestCase("@property --x { syntax: \"*\"; inherits: false; initial-value: var(--y); }")] + [TestCase("@property x { syntax: \"\"; inherits: false; initial-value: 1px; }")] + public void InvalidRegistrations(String source) + { + Assert.IsFalse(ParseRule(source).IsValid); + } + + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: 1in; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: 10vw; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: 50%; }")] + [TestCase("@property --x { syntax: \" | auto\"; inherits: false; initial-value: auto; }")] + [TestCase("@property --x { syntax: \"#\"; inherits: false; initial-value: red, blue; }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: rotate(45deg) scale(2); }")] + [TestCase("@property --x { syntax: \"\"; inherits: false; initial-value: 'em'; }")] + public void ValidRegistrations(String source) + { + Assert.IsTrue(ParseRule(source).IsValid); + } + + [Test] + public void RuleSerializesAndParsesAgain() + { + var rule = ParseRule("@property --x { syntax: \"\"; inherits: false; initial-value: 0px; }"); + var again = ParseRule(rule.CssText); + + Assert.AreEqual("--x", again.Name); + Assert.AreEqual("", again.Syntax); + Assert.AreEqual("0px", again.InitialValue); + Assert.IsTrue(again.IsValid); + } + + [TestCase("*")] + [TestCase("")] + [TestCase(" ")] + [TestCase("+")] + [TestCase("#")] + [TestCase(" | auto")] + [TestCase("big | bigger | BIGGER")] + [TestCase("")] + [TestCase("+")] + [TestCase("")] + [TestCase("#")] + public void ValidSyntaxStrings(String text) + { + Assert.IsNotNull(CssPropertySyntax.Parse(text)); + } + + [TestCase("")] + [TestCase(" ")] + [TestCase("")] + [TestCase("")] + [TestCase("+")] + [TestCase(" +")] + [TestCase("* | ")] + [TestCase("**")] + [TestCase("inherit")] + [TestCase(" ")] + [TestCase("|")] + [TestCase(" |")] + [TestCase("++")] + public void InvalidSyntaxStrings(String text) + { + Assert.IsNull(CssPropertySyntax.Parse(text)); + } + + [TestCase(" | auto", "10px", true)] + [TestCase(" | auto", "auto", true)] + [TestCase(" | auto", "red", false)] + [TestCase("+", "1px 2em 3vw", true)] + [TestCase("+", "1px, 2px", false)] + [TestCase("#", "red, #00f", true)] + [TestCase("#", "red blue", false)] + [TestCase("big | BIGGER", "BIGGER", true)] + [TestCase("big | BIGGER", "bigger", false)] + [TestCase("", "foo", true)] + [TestCase("", "inherit", false)] + [TestCase("", "3", true)] + [TestCase("", "3.5", false)] + [TestCase("", "45deg", true)] + [TestCase("", "url(a.png)", true)] + [TestCase("", "linear-gradient(red, blue)", true)] + [TestCase("*", "anything goes", true)] + public void Matching(String syntax, String value, Boolean matches) + { + var result = CssPropertySyntax.Parse(syntax).Match(new CssAnyValue(value, isResolved: true)); + Assert.AreEqual(matches, result is not null); + } + } +} diff --git a/src/AngleSharp.Css.Tests/Styling/RegisterPropertyTests.cs b/src/AngleSharp.Css.Tests/Styling/RegisterPropertyTests.cs new file mode 100644 index 00000000..2438a137 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/RegisterPropertyTests.cs @@ -0,0 +1,195 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using static CssConstructionFunctions; + + /// + /// Custom properties registered with CSS.registerProperty() (CSS Properties and Values API 1, 4). + /// + [TestFixture] + public class RegisterPropertyTests + { + private static PropertyDefinition Color(String name = "--c", Boolean inherits = false) => new() + { + Name = name, + Syntax = "", + Inherits = inherits, + InitialValue = "#c0ffee", + }; + + [Test] + public void RegisteredPropertyHasTheInitialValue() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(Color()); + var style = document.GetElementById("target").ComputeCurrentStyle(); + + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("--c")); + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("color")); + } + + [Test] + public void RegisteredPropertyValidatesItsValues() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(Color()); + + Assert.AreEqual("rgba(255, 0, 0, 1)", document.GetElementById("a").ComputeCurrentStyle().GetPropertyValue("--c")); + Assert.AreEqual("rgba(192, 255, 238, 1)", document.GetElementById("b").ComputeCurrentStyle().GetPropertyValue("--c")); + } + + [Test] + public void RegistrationAppliesToStylesComputedAfterwards() + { + var document = ParseDocument("
"); + var target = document.GetElementById("target"); + + Assert.AreEqual("red", target.ComputeCurrentStyle().GetPropertyValue("--c")); + document.DefaultView.RegisterProperty(Color(inherits: false)); + Assert.AreEqual("rgba(192, 255, 238, 1)", target.ComputeCurrentStyle().GetPropertyValue("--c")); + } + + [Test] + public void InheritedRegistration() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(Color(inherits: true)); + Assert.AreEqual("rgba(255, 0, 0, 1)", document.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--c")); + } + + [Test] + public void ScriptRegistrationWinsOverPropertyRule() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(Color()); + Assert.AreEqual("rgba(0, 0, 255, 1)", document.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--c")); + } + + [Test] + public void PropertyRuleDoesNotPreventARegistration() + { + var document = ParseDocument(""); + Assert.DoesNotThrow(() => document.DefaultView.RegisterProperty(Color())); + } + + [Test] + public void RegistrationIsPerDocument() + { + var first = ParseDocument("
"); + var second = ParseDocument("
"); + first.DefaultView.RegisterProperty(Color()); + + Assert.AreEqual("rgba(192, 255, 238, 1)", first.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--c")); + Assert.AreEqual("10px", second.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--c")); + Assert.DoesNotThrow(() => second.DefaultView.RegisterProperty(Color())); + } + + [Test] + public void RegisteringANameTwiceIsAnInvalidModification() + { + var document = ParseDocument(""); + document.DefaultView.RegisterProperty(Color()); + var ex = Assert.Throws(() => document.DefaultView.RegisterProperty(Color())); + Assert.AreEqual((Int32)DomError.InvalidModification, ex.Code); + } + + [Test] + public void DuplicateIsReportedBeforeAnInvalidDefinition() + { + var document = ParseDocument(""); + document.DefaultView.RegisterProperty(Color()); + var ex = Assert.Throws(() => document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--c", Syntax = "" })); + Assert.AreEqual((Int32)DomError.InvalidModification, ex.Code); + } + + [TestCase("c", "", "red")] + [TestCase("--", "", "red")] + [TestCase("--c", "", "red")] + [TestCase("--c", "", "red")] + [TestCase("--c", "", null)] + [TestCase("--c", "", "10px")] + [TestCase("--c", "", "2em")] + [TestCase("--c", "", "var(--x)")] + public void InvalidDefinitionsAreSyntaxErrors(String name, String syntax, String initialValue) + { + var document = ParseDocument(""); + var definition = new PropertyDefinition { Name = name, Syntax = syntax, InitialValue = initialValue }; + var ex = Assert.Throws(() => document.DefaultView.RegisterProperty(definition)); + Assert.AreEqual((Int32)DomError.Syntax, ex.Code); + } + + [Test] + public void FailedRegistrationRegistersNothing() + { + var document = ParseDocument(""); + Assert.Throws(() => document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--c", Syntax = "" })); + Assert.DoesNotThrow(() => document.DefaultView.RegisterProperty(Color())); + } + + [Test] + public void UniversalSyntaxIsTheDefault() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--u" }); + + Assert.AreEqual("foo", document.GetElementById("parent").ComputeCurrentStyle().GetPropertyValue("--u")); + Assert.AreEqual(String.Empty, document.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--u")); + } + + [Test] + public void RegistrationViaTheDocument() + { + var document = ParseDocument("
"); + document.RegisterProperty(new PropertyDefinition { Name = "--len", Syntax = "", InitialValue = "0px" }); + Assert.AreEqual("96px", document.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--len")); + } + + [Test] + public void TypedOmGivesTheTypedValue() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--len", Syntax = "", InitialValue = "0px" }); + var value = (CssUnitValue)document.GetElementById("target").ComputedStyleMap().Get("--len"); + + Assert.AreEqual(30.0, value.Value); + Assert.AreEqual("px", value.Unit); + } + + [Test] + public void RenderTreeUsesTheRegistration() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(Color()); + var tree = document.DefaultView.Render(); + var node = FindNode(tree, document.GetElementById("target")); + + Assert.IsNotNull(node); + Assert.AreEqual("rgba(192, 255, 238, 1)", node.ComputedStyle.GetPropertyValue("color")); + } + + private static AngleSharp.Css.RenderTree.ElementRenderNode FindNode(AngleSharp.Css.RenderTree.IRenderNode node, IElement element) + { + if (node is AngleSharp.Css.RenderTree.ElementRenderNode elementNode && elementNode.Ref == element) + { + return elementNode; + } + + foreach (var child in node.Children) + { + var found = FindNode(child, element); + + if (found is not null) + { + return found; + } + } + + return null; + } + } +} diff --git a/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs b/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs new file mode 100644 index 00000000..f6303922 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs @@ -0,0 +1,243 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using static CssConstructionFunctions; + + /// + /// Custom properties registered with @property (CSS Properties and Values API 1). + /// + [TestFixture] + public class RegisteredCustomPropertyTests + { + private const String Color = "@property --c { syntax: \"\"; inherits: false; initial-value: #c0ffee; }"; + private const String InheritedColor = "@property --c { syntax: \"\"; inherits: true; initial-value: #c0ffee; }"; + private const String Length = "@property --len { syntax: \"\"; inherits: true; initial-value: 0px; }"; + + private static ICssStyleDeclaration Compute(String css, String body, String id = "target") + { + var document = ParseDocument($"{body}"); + return document.GetElementById(id).ComputeCurrentStyle(); + } + + [Test] + public void UndeclaredPropertyHasTheInitialValue() + { + var style = Compute(Color + " #target { color: var(--c) }", "
"); + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("--c")); + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("color")); + } + + [Test] + public void DeclaredValueIsComputed() + { + var style = Compute(Color + " #target { --c: red; color: var(--c) }", "
"); + Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetPropertyValue("--c")); + Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetPropertyValue("color")); + } + + [Test] + public void ValueNotMatchingTheSyntaxIsTheInitialValue() + { + var style = Compute(Color + " #target { --c: 10px; color: var(--c) }", "
"); + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("--c")); + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("color")); + } + + [Test] + public void PropertyThatIsNotInheritedHasTheInitialValueOnChildren() + { + var style = Compute(Color + " #parent { --c: red }", "
"); + Assert.AreEqual("rgba(192, 255, 238, 1)", style.GetPropertyValue("--c")); + } + + [Test] + public void InheritedPropertyHasTheValueOfTheParent() + { + var style = Compute(InheritedColor + " #parent { --c: red }", "
"); + Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetPropertyValue("--c")); + } + + [Test] + public void InvalidValueOfAnInheritedPropertyIsTheValueOfTheParent() + { + var style = Compute(InheritedColor + " #parent { --c: red } #target { --c: 10px }", "
"); + Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetPropertyValue("--c")); + } + + [Test] + public void CssWideKeywords() + { + const String body = "
"; + const String css = Color + " #parent { --c: red } #a { --c: inherit } #b { --c: unset } #c { --c: initial }"; + var document = ParseDocument($"{body}"); + + Assert.AreEqual("rgba(255, 0, 0, 1)", document.GetElementById("a").ComputeCurrentStyle().GetPropertyValue("--c")); + Assert.AreEqual("rgba(192, 255, 238, 1)", document.GetElementById("b").ComputeCurrentStyle().GetPropertyValue("--c")); + Assert.AreEqual("rgba(192, 255, 238, 1)", document.GetElementById("c").ComputeCurrentStyle().GetPropertyValue("--c")); + } + + [Test] + public void LengthIsComputedOnTheElementAndInheritedAsComputed() + { + var css = Length + " #parent { font-size: 10px; --len: 2em } #target { font-size: 20px; width: var(--len) }"; + var style = Compute(css, "
"); + Assert.AreEqual("20px", style.GetPropertyValue("--len")); + Assert.AreEqual("20px", style.GetPropertyValue("width")); + } + + [Test] + public void UnregisteredLengthIsInheritedAsSpecified() + { + var css = "#parent { font-size: 10px; --len: 2em } #target { font-size: 20px; width: var(--len) }"; + var style = Compute(css, "
"); + Assert.AreEqual("2em", style.GetPropertyValue("--len")); + Assert.AreEqual("40px", style.GetPropertyValue("width")); + } + + [Test] + public void AbsoluteUnitsAreConvertedToPixels() + { + var style = Compute(Length + " #target { --len: 1in }", "
"); + Assert.AreEqual("96px", style.GetPropertyValue("--len")); + } + + [Test] + public void InitialValueIsComputed() + { + var style = Compute("@property --len { syntax: \"\"; inherits: false; initial-value: 1in; }", "
"); + Assert.AreEqual("96px", style.GetPropertyValue("--len")); + } + + [Test] + public void PercentagesAreKept() + { + var css = "@property --lp { syntax: \"\"; inherits: false; initial-value: 0px; } #target { --lp: 50% }"; + Assert.AreEqual("50%", Compute(css, "
").GetPropertyValue("--lp")); + } + + [Test] + public void ListsAreComputedPerItem() + { + var css = "@property --l { syntax: \"#\"; inherits: false; initial-value: 0px; } #target { font-size: 10px; --l: 1px, 2em }"; + Assert.AreEqual("1px, 20px", Compute(css, "
").GetPropertyValue("--l")); + } + + [Test] + public void SubstitutedValueIsValidated() + { + var css = Length + " #a { --x: 5px; --len: var(--x) } #b { --len: var(--missing) } #c { --x: red; --len: var(--x) }"; + var document = ParseDocument($"
"); + + Assert.AreEqual("5px", document.GetElementById("a").ComputeCurrentStyle().GetPropertyValue("--len")); + Assert.AreEqual("0px", document.GetElementById("b").ComputeCurrentStyle().GetPropertyValue("--len")); + Assert.AreEqual("0px", document.GetElementById("c").ComputeCurrentStyle().GetPropertyValue("--len")); + } + + [Test] + public void ReferenceToARegisteredPropertySubstitutesItsComputedValue() + { + var css = Length + " #target { font-size: 10px; --len: 3em; --text: var(--len) }"; + Assert.AreEqual("30px", Compute(css, "
").GetPropertyValue("--text")); + } + + [Test] + public void FontRelativePropertyUsedByFontSizeIsACycle() + { + // font-size behaves as unset, i.e., is inherited (CSS Properties and Values API 2.7) + var css = Length + " #parent { font-size: 10px } #target { --len: 2em; font-size: var(--len) }"; + var style = Compute(css, "
"); + Assert.AreEqual("10px", style.GetPropertyValue("font-size")); + Assert.AreEqual("20px", style.GetPropertyValue("--len")); + } + + [Test] + public void AbsolutePropertyUsedByFontSize() + { + var css = Length + " #parent { font-size: 10px } #target { --len: 30px; font-size: var(--len); width: 2em }"; + var style = Compute(css, "
"); + Assert.AreEqual("30px", style.GetPropertyValue("font-size")); + Assert.AreEqual("60px", style.GetPropertyValue("width")); + } + + [Test] + public void InheritedFontRelativePropertyUsedByFontSize() + { + // the inherited value is computed already, i.e., no cycle + var css = Length + " #parent { font-size: 10px; --len: 2em } #target { font-size: var(--len) }"; + var style = Compute(css, "
"); + Assert.AreEqual("20px", style.GetPropertyValue("font-size")); + } + + [Test] + public void LastValidRegistrationWins() + { + var css = "@property --c { syntax: \"\"; inherits: false; initial-value: 1px; } " + + "@property --c { syntax: \"\"; inherits: false; initial-value: red; } " + + "@property --c { syntax: \"\"; inherits: false; initial-value: 2px; } #target { --c: blue }"; + Assert.AreEqual("rgba(0, 0, 255, 1)", Compute(css, "
").GetPropertyValue("--c")); + } + + [Test] + public void InvalidRegistrationLeavesThePropertyUnregistered() + { + var css = "@property --c { syntax: \"\"; inherits: false; } #parent { --c: 10px }"; + var style = Compute(css, "
"); + Assert.AreEqual("10px", style.GetPropertyValue("--c")); + } + + [Test] + public void UniversalSyntaxWithoutInitialValueThatIsNotInherited() + { + var css = "@property --u { syntax: \"*\"; inherits: false; } #parent { --u: foo bar }"; + var document = ParseDocument($"
"); + + Assert.AreEqual("foo bar", document.GetElementById("parent").ComputeCurrentStyle().GetPropertyValue("--u")); + Assert.AreEqual(String.Empty, document.GetElementById("target").ComputeCurrentStyle().GetPropertyValue("--u")); + } + + [Test] + public void IdentifiersAreCaseSensitive() + { + var css = "@property --size { syntax: \"small | BIG\"; inherits: false; initial-value: small; } #a { --size: BIG } #b { --size: big }"; + var document = ParseDocument($"
"); + + Assert.AreEqual("BIG", document.GetElementById("a").ComputeCurrentStyle().GetPropertyValue("--size")); + Assert.AreEqual("small", document.GetElementById("b").ComputeCurrentStyle().GetPropertyValue("--size")); + } + + [Test] + public void UnregisteredPropertiesKeepTheirBehavior() + { + var style = Compute(Color + " #parent { --other: 2em solid } ", "
"); + Assert.AreEqual("2em solid", style.GetPropertyValue("--other")); + } + + [Test] + public void TypedOmGivesTypedValuesOfRegisteredProperties() + { + var css = Length + " #target { font-size: 10px; --len: 2em; --other: 2em }"; + var document = ParseDocument($"
"); + var map = document.GetElementById("target").ComputedStyleMap(); + var value = map.Get("--len") as CssUnitValue; + + Assert.IsNotNull(value); + Assert.AreEqual(20.0, value.Value); + Assert.AreEqual("px", value.Unit); + Assert.IsInstanceOf(map.Get("--other")); + } + + [Test] + public void DeclaredStyleKeepsTheSpecifiedValue() + { + var document = ParseDocument("
"); + var element = document.GetElementById("target"); + + Assert.AreEqual("2em", element.GetStyle().GetPropertyValue("--len")); + } + } +} diff --git a/src/AngleSharp.Css/Constants/CssKeywords.cs b/src/AngleSharp.Css/Constants/CssKeywords.cs index 21270365..a82d1685 100644 --- a/src/AngleSharp.Css/Constants/CssKeywords.cs +++ b/src/AngleSharp.Css/Constants/CssKeywords.cs @@ -2413,5 +2413,25 @@ public static class CssKeywords /// The each-line keyword. /// public static readonly String EachLine = "each-line"; + + /// + /// The true keyword. + /// + public static readonly String True = "true"; + + /// + /// The false keyword. + /// + public static readonly String False = "false"; + + /// + /// The revert keyword. + /// + public static readonly String Revert = "revert"; + + /// + /// The revert-layer keyword. + /// + public static readonly String RevertLayer = "revert-layer"; } } diff --git a/src/AngleSharp.Css/Constants/FunctionNames.cs b/src/AngleSharp.Css/Constants/FunctionNames.cs index 07324702..df42327c 100644 --- a/src/AngleSharp.Css/Constants/FunctionNames.cs +++ b/src/AngleSharp.Css/Constants/FunctionNames.cs @@ -57,6 +57,11 @@ public static class FunctionNames /// public static readonly String Attr = "attr"; + /// + /// The env function. + /// + public static readonly String Env = "env"; + /// /// The symbols function. /// diff --git a/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs b/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs new file mode 100644 index 00000000..bc6242d7 --- /dev/null +++ b/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs @@ -0,0 +1,69 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using System; + + /// + /// The registration of custom properties (CSS Properties and Values API). + /// https://www.w3.org/TR/css-properties-values-api-1/#the-registerproperty-function + /// + public static partial class CssHelpers + { + /// + /// Registers a custom property for the document of the window, which wins over the + /// registrations of @property rules for the same name. Styles computed afterwards + /// validate the values of the property against its syntax, give it the initial value + /// and inherit it only if it is registered as inherited. + /// + /// The hosting window. + /// The definition of the custom property. + /// + /// A SyntaxError if the name, the syntax, or the initial value is not valid, or an + /// InvalidModificationError if the name has been registered already. + /// + [DomName("registerProperty")] + public static void RegisterProperty(this IWindow window, PropertyDefinition definition) + { + if (window is null) + throw new ArgumentNullException(nameof(window)); + + window.Document.RegisterProperty(definition); + } + + /// + /// Registers a custom property for the document, which wins over the registrations + /// of @property rules for the same name. + /// + /// The document to register the property for. + /// The definition of the custom property. + /// + /// A SyntaxError if the name, the syntax, or the initial value is not valid, or an + /// InvalidModificationError if the name has been registered already. + /// + public static void RegisterProperty(this IDocument document, PropertyDefinition definition) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); + + if (definition is null) + throw new ArgumentNullException(nameof(definition)); + + if (!CssPropertyRegistration.IsCustomPropertyName(definition.Name)) + throw new DomException(DomError.Syntax); + + // checked before the definition is validated, as the specification does + if (CssScriptPropertyRegistrations.Get(document)?.Contains(definition.Name) == true) + throw new DomException(DomError.InvalidModification); + + var syntax =CssPropertySyntax.Parse(definition.Syntax ?? String.Empty) ?? throw new DomException(DomError.Syntax); + var registration = CssPropertyRegistration.Create(definition.Name, syntax, definition.Inherits, definition.InitialValue) ?? + throw new DomException(DomError.Syntax); + + if (!CssScriptPropertyRegistrations.TryAdd(document, registration)) + throw new DomException(DomError.InvalidModification); + } + } +} diff --git a/src/AngleSharp.Css/Dom/ICssPropertyRule.cs b/src/AngleSharp.Css/Dom/ICssPropertyRule.cs index 95b5c74f..6f3ef7ca 100644 --- a/src/AngleSharp.Css/Dom/ICssPropertyRule.cs +++ b/src/AngleSharp.Css/Dom/ICssPropertyRule.cs @@ -1,3 +1,4 @@ +#nullable enable namespace AngleSharp.Css.Dom { using AngleSharp.Attributes; @@ -14,5 +15,31 @@ public interface ICssPropertyRule : ICssRule, ICssProperties /// [DomName("name")] String Name { get; } + + /// + /// Gets the syntax of the custom property as specified (without the quotes of + /// the string), e.g., <color>, or an empty string if it has no valid syntax. + /// + [DomName("syntax")] + String Syntax { get; } + + /// + /// Gets if the custom property is inherited. + /// + [DomName("inherits")] + Boolean Inherits { get; } + + /// + /// Gets the initial value of the custom property, if any. + /// + [DomName("initialValue")] + String? InitialValue { get; } + + /// + /// Gets if the rule is valid, i.e., registers the custom property: it needs a valid + /// syntax and inherits descriptor, and an initial value that matches the syntax + /// and is computationally independent, unless the syntax is universal (*). + /// + Boolean IsValid { get; } } } diff --git a/src/AngleSharp.Css/Dom/Internal/CssProperty.cs b/src/AngleSharp.Css/Dom/Internal/CssProperty.cs index 7f26c921..efb247b0 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssProperty.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssProperty.cs @@ -159,6 +159,13 @@ public ICssProperty Compute(ICssComputeContext context) return this; } + /// + /// Computes a value as the value of a property with the given name and converter, + /// e.g., the value of a registered custom property against its syntax. + /// + internal static ICssValue ComputeValue(ICssValue value, IValueConverter converter, String name, ICssComputeContext context) => + value.Compute(new PropertyComputeContext(context, converter, name)); + #endregion #region Keyword State @@ -196,7 +203,8 @@ public PropertyComputeContext(ICssComputeContext parent, IValueConverter convert public IValueConverter Converter => _converter; - public ICssValue Resolve(String name) =>_parent.Resolve(name); + public ICssValue Resolve(String name) => + _parent is CssComputeContext context && _name.Is(PropertyNames.FontSize) ? context.ResolveForFontSize(name) : _parent.Resolve(name); public ICssValue InheritedValue(String name) => (_parent as IInheritingComputeContext)?.InheritedValue(name); diff --git a/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs b/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs index 8927351d..20251859 100644 --- a/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs +++ b/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs @@ -27,6 +27,12 @@ protected CssDescriptorRule(ICssStyleSheet owner, CssRuleType type, String ruleN protected abstract String PreludeText { get; } + /// + /// Checks if the descriptor with the given (non-empty) value is valid for the rule, + /// otherwise it is ignored. By default every descriptor is kept. + /// + protected virtual Boolean IsValidDescriptor(String name, String value) => true; + public ICssProperty GetProperty(String propertyName) { for (var i = 0; i < _descriptors.Count; i++) @@ -73,6 +79,12 @@ public void SetProperty(String propertyName, String propertyValue, String priori return; } + if (!IsValidDescriptor(propertyName, propertyValue)) + { + // an invalid descriptor is ignored, i.e., keeps the current one + return; + } + if (property is null) { property = new DescriptorProperty(propertyName); diff --git a/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs b/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs index 124fbad5..8206a3e4 100644 --- a/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs +++ b/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs @@ -1,15 +1,23 @@ #nullable disable namespace AngleSharp.Css.Dom { + using AngleSharp.Css.Parser; + using AngleSharp.Css.Values; + using AngleSharp.Text; using System; using System.Diagnostics; /// /// Represents a CSS @property rule. + /// https://www.w3.org/TR/css-properties-values-api-1/#at-property-rule /// [DebuggerDisplay(null, Name = "CssPropertyRule ({Name})")] sealed class CssPropertyRule : CssDescriptorRule, ICssPropertyRule { + internal const String SyntaxDescriptor = "syntax"; + internal const String InheritsDescriptor = "inherits"; + internal const String InitialValueDescriptor = "initial-value"; + internal CssPropertyRule(ICssStyleSheet owner) : base(owner, CssRuleType.Property, RuleNames.Property) { @@ -17,13 +25,74 @@ internal CssPropertyRule(ICssStyleSheet owner) public String Name { get; set; } + public String Syntax => ParseSyntaxString(GetPropertyValue(SyntaxDescriptor)) ?? String.Empty; + + public Boolean Inherits => GetPropertyValue(InheritsDescriptor).Isi(CssKeywords.True); + + public String InitialValue => GetProperty(InitialValueDescriptor)?.Value; + + public Boolean IsValid => CreateRegistration() is not null; + protected override String PreludeText => Name; + /// + /// Creates the registration of the rule, if the rule is valid: it needs a valid syntax + /// and inherits, and an initial value that matches the syntax and is computationally + /// independent, unless the syntax is universal. + /// + internal CssPropertyRegistration CreateRegistration() + { + var syntaxText = ParseSyntaxString(GetPropertyValue(SyntaxDescriptor)); + var syntax = syntaxText is not null ? CssPropertySyntax.Parse(syntaxText) : null; + + if (!CssPropertyRegistration.IsCustomPropertyName(Name) || syntax is null || GetProperty(InheritsDescriptor) is null) + { + return null; + } + + return CssPropertyRegistration.Create(Name, syntax, Inherits, GetProperty(InitialValueDescriptor)?.Value); + } + + /// + /// Drops invalid descriptors (CSS Properties and Values API 3): syntax has to be a + /// valid syntax string, inherits either true or false, and unknown descriptors are ignored. + /// + protected override Boolean IsValidDescriptor(String name, String value) + { + if (name.Isi(SyntaxDescriptor)) + { + var text = ParseSyntaxString(value); + return text is not null && CssPropertySyntax.Parse(text) is not null; + } + else if (name.Isi(InheritsDescriptor)) + { + var keyword = value.Trim(); + return keyword.Isi(CssKeywords.True) || keyword.Isi(CssKeywords.False); + } + + return name.Isi(InitialValueDescriptor); + } + protected override void ReplaceWith(ICssRule rule) { var newRule = (ICssPropertyRule)rule; Name = newRule.Name; ReplaceWith((ICssProperties)newRule); } + + // the syntax descriptor is a , e.g., "" + private static String ParseSyntaxString(String value) + { + if (String.IsNullOrEmpty(value)) + { + return null; + } + + var source = new StringSource(value); + source.SkipSpacesAndComments(); + var text = source.ParseString(); + source.SkipSpacesAndComments(); + return source.IsDone ? text : null; + } } } diff --git a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs index d24fc73c..5f951a26 100644 --- a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs +++ b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs @@ -1,5 +1,6 @@ namespace AngleSharp.Css.Dom { + using AngleSharp.Css.Values; using AngleSharp.Dom; using System; using System.Collections; @@ -14,11 +15,13 @@ sealed class StyleCollection : IStyleCollection private readonly IEnumerable _defaultSheets; private readonly IEnumerable _sheets; private readonly IRenderDevice _device; + private readonly IDocument? _document; private List? _rules; private List? _layerRanks; private StyleRuleIndex? _index; private List? _matches; private Int32 _defaultRuleCount; + private CssPropertyRegistry? _registry; #endregion @@ -29,11 +32,12 @@ public StyleCollection(IEnumerable sheets, IRenderDevice device) { } - public StyleCollection(IEnumerable defaultSheets, IEnumerable sheets, IRenderDevice device, IElement? scope = null) + public StyleCollection(IEnumerable defaultSheets, IEnumerable sheets, IRenderDevice device, IElement? scope = null, IDocument? document = null) { _defaultSheets = defaultSheets; _sheets = sheets; _device = device; + _document = document ?? scope?.Owner; Scope = scope; } @@ -111,6 +115,17 @@ internal Int32 GetDefaultRuleCount() return _defaultRuleCount; } + /// + /// Gets the custom properties registered by the valid @property rules of the style + /// sheets, which are collected with the rules: the last registration of a name wins. + /// The registrations of script (CSS.registerProperty) of the document win over them. + /// + internal CssPropertyRegistry GetRegistrations() + { + GetRules(); + return _registry!; + } + #endregion #region Helpers @@ -119,9 +134,16 @@ private List CollectRules() { var rules = new List(); var layers = new List(); + _registry = new CssPropertyRegistry(); AddRules(rules, layers, _defaultSheets); _defaultRuleCount = rules.Count; AddRules(rules, layers, WithoutEarlierDuplicates(_sheets)); + var scripted = _document is not null ? CssScriptPropertyRegistrations.Get(_document) : null; + + if (scripted is not null) + { + _registry.RegisterAll(scripted); + } _layerRanks = layers.ConvertAll(m => m.Rank); return rules; } @@ -207,6 +229,15 @@ private void AddRules(List rules, List layers, ICssRuleLis case ICssStyleRule style: rules.Add(style); layers.Add(layer); + break; + case CssPropertyRule property: + var registration = property.CreateRegistration(); + + if (registration is not null) + { + _registry!.Register(registration); + } + break; case ICssMediaRule media when media.IsValid(_device): AddRules(rules, layers, media.Rules, layer); diff --git a/src/AngleSharp.Css/Dom/PropertyDefinition.cs b/src/AngleSharp.Css/Dom/PropertyDefinition.cs new file mode 100644 index 00000000..59d83d9b --- /dev/null +++ b/src/AngleSharp.Css/Dom/PropertyDefinition.cs @@ -0,0 +1,40 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Attributes; + using System; + + /// + /// The definition of a custom property to register via CSS.registerProperty(). + /// https://www.w3.org/TR/css-properties-values-api-1/#dictdef-propertydefinition + /// + [DomName("PropertyDefinition")] + public class PropertyDefinition + { + /// + /// Gets or sets the name of the custom property, e.g., --my-color. + /// + [DomName("name")] + public String Name { get; set; } = String.Empty; + + /// + /// Gets or sets the syntax values of the property have to match, e.g., <color>. + /// The default is the universal syntax (*), which accepts any value. + /// + [DomName("syntax")] + public String Syntax { get; set; } = "*"; + + /// + /// Gets or sets if the property is inherited. + /// + [DomName("inherits")] + public Boolean Inherits { get; set; } + + /// + /// Gets or sets the initial value, which is required unless the syntax is universal. + /// It has to match the syntax and must not depend on the element, e.g., by em or var(). + /// + [DomName("initialValue")] + public String? InitialValue { get; set; } + } +} diff --git a/src/AngleSharp.Css/Extensions/CssApiExtensions.cs b/src/AngleSharp.Css/Extensions/CssApiExtensions.cs index 2aa17335..b94231a3 100644 --- a/src/AngleSharp.Css/Extensions/CssApiExtensions.cs +++ b/src/AngleSharp.Css/Extensions/CssApiExtensions.cs @@ -33,7 +33,7 @@ public static ICssStyleDeclaration ComputeCurrentStyle(this IElement element) var defaultStyleSheetProvider = ctx?.GetServices() ?? Enumerable.Empty(); var defaultSheets = defaultStyleSheetProvider.Select(m => m.Default).Where(m => m != null); var currentSheets = document?.GetEffectiveStyleSheets() ?? Enumerable.Empty(); - var styleCollection = new StyleCollection(defaultSheets, currentSheets, device!); + var styleCollection = new StyleCollection(defaultSheets, currentSheets, device!, document: document); return styleCollection.ComputeDeclarations(element); } diff --git a/src/AngleSharp.Css/Extensions/CssOmExtensions.cs b/src/AngleSharp.Css/Extensions/CssOmExtensions.cs index b7b6853e..232ae3f2 100644 --- a/src/AngleSharp.Css/Extensions/CssOmExtensions.cs +++ b/src/AngleSharp.Css/Extensions/CssOmExtensions.cs @@ -174,11 +174,40 @@ internal static CssStyleDeclaration PrepareComputedDeclarations(this ICssStyleDe declarations.AddProperty(property.Name.StartsWith("--", StringComparison.Ordinal) ? property.Compute(context) : property); } + AddRegisteredProperties(declarations, style, context); declarations.InheritFrom(parent); LogicalProperties.Apply(declarations, context); return declarations; } + /// + /// Gives every registered custom property (@property) that is not declared its computed + /// value, i.e., the initial value or the value of the parent (CSS Properties and Values + /// API 2.4). Being an own declaration, the value also shadows the one of the parent for + /// a property that is not inherited. + /// + private static void AddRegisteredProperties(CssStyleDeclaration declarations, ICssStyleDeclaration style, ICssComputeContext context) + { + var registry = (context as CssComputeContext)?.Registry; + + if (registry is null || registry.Count == 0) + { + return; + } + + foreach (var registration in registry.Registrations) + { + if (style.GetProperty(registration.Name) is { RawValue: not null }) + { + continue; + } + + var info = context.Context?.GetDeclarationInfo(registration.Name); + var value = context.Resolve(registration.Name) ?? CssInvalidValue.Instance; + declarations.AddProperty(new CssProperty(registration.Name, info?.Converter ?? ValueConverters.Any, info?.Flags ?? PropertyFlags.Inherited, value)); + } + } + /// /// Blockifies the computed display of a floated box, an absolutely positioned box /// and the root element, see CSS Display 3 §2.7 and CSS 2.1 §9.7. diff --git a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs index f89469de..31f3dc41 100644 --- a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs @@ -31,7 +31,7 @@ public static IStyleCollection GetStyleCollection(this IWindow window, IRenderDe var defaultStyleSheetProvider = ctx.GetServices(); var defaultSheets = defaultStyleSheetProvider.Select(m => m.Default).Where(m => m != null); var currentSheets = document.GetEffectiveStyleSheets(); - return new StyleCollection(defaultSheets, currentSheets, renderDevice); + return new StyleCollection(defaultSheets, currentSheets, renderDevice, document: document); } /// @@ -119,7 +119,7 @@ private static ICssStyleDeclaration GetComputedDeclarations(IStyleCollection sty { var node = nodes.Pop(); var explicitStyle = styles.ComputeExplicitStyle(node); - var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parent); + var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parent, (styles as StyleCollection)?.GetRegistrations()); parent = explicitStyle.PrepareComputedDeclarations(parent!, context).Compute(context).Blockify(node); } @@ -196,7 +196,7 @@ public static ICssStyleDeclaration ComputeDeclarationsWithParent(this IStyleColl { var ctx = element.Owner?.Context; var explicitStyle = styles.ComputeExplicitStyle(element); - var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parentComputedStyle); + var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parentComputedStyle, (styles as StyleCollection)?.GetRegistrations()); return explicitStyle.PrepareComputedDeclarations(parentComputedStyle, context).Compute(context).Blockify(element); } diff --git a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs index 6d60b1d3..58adbb9e 100644 --- a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs +++ b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs @@ -223,7 +223,7 @@ private StyleCollection CreateStyleCollection(IRenderDevice device) { var document = _window.Document; var currentSheets = document.GetEffectiveStyleSheets(); - return new StyleCollection(_defaultSheets, currentSheets.ToList(), device); + return new StyleCollection(_defaultSheets, currentSheets.ToList(), device, document: document); } private ElementRenderNode RenderElement( @@ -250,7 +250,7 @@ private ElementRenderNode RenderElement( ? collection.ComputeHostStyle(shadowCollection, element) : collection.ComputeExplicitStyle(element); - var computeContext = new CssComputeContext(collection.Device, _context, explicitStyle, parentComputedStyle); + var computeContext = new CssComputeContext(collection.Device, _context, explicitStyle, parentComputedStyle, collection.GetRegistrations()); var computedStyle = explicitStyle.PrepareComputedDeclarations(parentComputedStyle!, computeContext).Compute(computeContext).Blockify(element); var pending = partial ? new PendingChildren(this, collection, shadowCollection, slottedCollection, getInheritedStyle, childrenBuilt) : null; var children = partial ? null : new List(); diff --git a/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs b/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs index df58f7e9..3dc14199 100644 --- a/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs +++ b/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs @@ -18,7 +18,8 @@ static class CssStyleValueReifier /// /// Reifies the value of the given property, which yields one item per entry - /// of a comma separated list, e.g., of background-image. + /// of a comma separated list, e.g., of background-image (or of a registered + /// custom property with the syntax <length>#). /// public static IReadOnlyList ReifyAll(String property, ICssValue? value) { @@ -27,7 +28,7 @@ public static IReadOnlyList ReifyAll(String property, ICssValue? return Array.Empty(); } - if (!TypedOmProperties.IsCustom(property) && value is CssListValue list) + if (value is CssListValue list) { return list.Items.Select(item => Reify(property, item)).ToArray(); } @@ -40,7 +41,9 @@ public static IReadOnlyList ReifyAll(String property, ICssValue? /// public static CssStyleValue Reify(String property, ICssValue value) { - if (TypedOmProperties.IsCustom(property)) + // the value of a custom property is only typed if it is the computed value of a + // registered (@property) one, e.g., a length + if (TypedOmProperties.IsCustom(property) && value is CssAnyValue or CssReferenceValue or CssInvalidValue) { return CssUnparsedValue.FromText(value.CssText); } diff --git a/src/AngleSharp.Css/Values/CssComputeContext.cs b/src/AngleSharp.Css/Values/CssComputeContext.cs index fc802baf..a62b4975 100644 --- a/src/AngleSharp.Css/Values/CssComputeContext.cs +++ b/src/AngleSharp.Css/Values/CssComputeContext.cs @@ -12,15 +12,23 @@ sealed class CssComputeContext : ICssComputeContext, ILocalComputeContext, IInhe private readonly ICssProperties? _parent; private Double? _fontSize; - public CssComputeContext(IRenderDevice device, IBrowsingContext? context, ICssProperties properties, ICssProperties? parent = null) + public CssComputeContext(IRenderDevice device, IBrowsingContext? context, ICssProperties properties, ICssProperties? parent = null, CssPropertyRegistry? registry = null) { _device = device ?? new DefaultRenderDevice(); _context = context; - _variables = new CssCustomPropertyResolver(properties, parent); _parent = parent; Properties = properties; + Registry = registry; + // the resolver computes registered custom properties against this context, but only + // once it is constructed (resolving them before gives the specified values) + _variables = new CssCustomPropertyResolver(properties, parent, registry, this); } + /// + /// Gets the registered custom properties (@property), if any. + /// + public CssPropertyRegistry? Registry { get; } + public ICssProperties Properties { get; } public IRenderDevice Device => _device; @@ -29,7 +37,14 @@ public CssComputeContext(IRenderDevice device, IBrowsingContext? context, ICssPr public IValueConverter? Converter => null; - public ICssValue? Resolve(String name) => _variables.Resolve(name); + // the resolver is created last, i.e., while it substitutes nothing can be resolved here + public ICssValue? Resolve(String name) => _variables?.Resolve(name); + + /// + /// Resolves a custom property for the font size of the element, see + /// CssCustomPropertyResolver.ResolveForFontSize. + /// + internal ICssValue? ResolveForFontSize(String name) => _variables?.ResolveForFontSize(name); public ICssValue? InheritedValue(String name) => _parent is CssStyleDeclaration parent ? parent.GetDeclaration(name)?.RawValue diff --git a/src/AngleSharp.Css/Values/CssCustomPropertyResolver.cs b/src/AngleSharp.Css/Values/CssCustomPropertyResolver.cs index 21e79350..69f88db6 100644 --- a/src/AngleSharp.Css/Values/CssCustomPropertyResolver.cs +++ b/src/AngleSharp.Css/Values/CssCustomPropertyResolver.cs @@ -4,19 +4,46 @@ namespace AngleSharp.Css.Values using System; using System.Collections.Generic; using System.Linq; + using AngleSharp.Text; sealed class CssCustomPropertyResolver { // created on demand: most elements declare no custom properties (but are computed with a resolver) private Dictionary? _values; + // the custom properties of a parent that is not a CssStyleDeclaration, which are copied + private Dictionary? _parentValues; private readonly CssStyleDeclaration? _parent; private Func? _resolve; + // the registered custom properties (@property) and what is known about them on the element + private readonly CssPropertyRegistry? _registry; + private readonly ICssComputeContext? _context; + private Dictionary? _keywords; + private Dictionary? _computed; + private HashSet? _computing; + private Boolean _initializing; + // the font size of the element refers to custom properties, i.e., cannot be computed + // while they are substituted + private Boolean _fontSizeHasReferences; + public CssCustomPropertyResolver(IEnumerable properties, ICssProperties? parent = null) + : this(properties, parent, null, null) + { + } + + /// + /// Creates the resolver of the custom properties of an element. The values of registered + /// custom properties are validated against their syntax and computed (with the given + /// context) when they are resolved, which must not happen before the context is usable. + /// + public CssCustomPropertyResolver(IEnumerable properties, ICssProperties? parent, CssPropertyRegistry? registry, ICssComputeContext? context) { // the custom properties of the parent are looked up on demand instead of copied, // as there may be thousands of them (e.g., design tokens on :root) _parent = parent as CssStyleDeclaration; + _registry = registry is { Count: > 0 } ? registry : null; + _context = context; + _initializing = true; if (parent is not null && _parent is null) { @@ -24,15 +51,33 @@ public CssCustomPropertyResolver(IEnumerable properties, ICssPrope { if (property.Name.StartsWith("--", StringComparison.Ordinal)) { - SetValue(property.Name, property.RawValue is CssInvalidValue ? null : property.RawValue); + (_parentValues ??= new Dictionary(StringComparer.Ordinal))[property.Name] = property.RawValue is CssInvalidValue ? null : property.RawValue; } } } + try + { + Initialize(properties); + } + finally + { + _initializing = false; + } + } + + private void Initialize(IEnumerable properties) + { + Dictionary? nodes = null; foreach (var property in properties) { + if (property.RawValue is CssReferenceValue && property.Name.Is(PropertyNames.FontSize)) + { + _fontSizeHasReferences = true; + } + if (property.Name.StartsWith("--", StringComparison.Ordinal)) { var value = property.RawValue; @@ -49,6 +94,11 @@ public CssCustomPropertyResolver(IEnumerable properties, ICssPrope new[] { new CssVariableValue(value.CssText) }; var keyword = values.Length == 1 ? values[0].Keyword : null; + if (keyword is not null && _registry?.Get(property.Name) is not null && IsCssWideKeyword(keyword)) + { + (_keywords ??= new Dictionary(StringComparer.Ordinal))[property.Name] = keyword.ToLowerInvariant(); + } + if (String.Equals(keyword, CssKeywords.Inherit, StringComparison.OrdinalIgnoreCase) || String.Equals(keyword, CssKeywords.Unset, StringComparison.OrdinalIgnoreCase)) { @@ -176,11 +226,28 @@ void Enter(Node node) public ICssValue? Resolve(String name) { + var registration = _registry?.Get(name); + + if (registration is not null) + { + return ResolveRegistered(registration); + } + if (_values is not null && _values.TryGetValue(name, out var value)) { return value; } + return ResolveParent(name); + } + + private ICssValue? ResolveParent(String name) + { + if (_parentValues is not null && _parentValues.TryGetValue(name, out var copied)) + { + return copied; + } + if (_parent is not null && name.StartsWith("--", StringComparison.Ordinal)) { var inherited = _parent.GetDeclaration(name)?.RawValue; @@ -190,6 +257,149 @@ void Enter(Node node) return null; } + #region Registered Custom Properties + + /// + /// Resolves the computed value of a registered custom property (CSS Properties and + /// Values API 2.4): a value not matching the syntax is invalid at computed-value time, + /// i.e., behaves as unset, which (as when nothing is declared) is the value of the + /// parent for an inherited property and otherwise the initial value. + /// + private ICssValue? ResolveRegistered(CssPropertyRegistration registration) + { + var name = registration.Name; + + if (_computed is not null && _computed.TryGetValue(name, out var cached)) + { + return cached; + } + + // the value refers to itself while it is computed, e.g., via the font size + if (_computing is not null && _computing.Contains(name)) + { + return null; + } + + // While the custom properties are substituted (in dependency order), a value that + // depends on the font size is computed only if the font size does not depend on the + // custom properties in question, otherwise it is given as specified. + if (_initializing && _fontSizeHasReferences) + { + var specified = Evaluate(registration, false); + + if (specified is not null && !CssPropertySyntax.IsComputationallyIndependent(specified.CssText)) + { + return specified; + } + } + + (_computing ??= new HashSet(StringComparer.Ordinal)).Add(name); + + try + { + var value = Evaluate(registration, true); + (_computed ??= new Dictionary(StringComparer.Ordinal))[name] = value; + return value; + } + finally + { + _computing.Remove(name); + } + } + + /// + /// Resolves the custom property for font-size: a registered property whose value + /// depends on the font size, e.g., 2em, makes a cycle with it (CSS Properties and + /// Values API 2.7), i.e., is the guaranteed-invalid value for font-size. + /// + public ICssValue? ResolveForFontSize(String name) + { + var registration = _registry?.Get(name); + + if (registration is not null) + { + var specified = Evaluate(registration, false); + + if (specified is not null && !CssPropertySyntax.IsComputationallyIndependent(specified.CssText)) + { + return null; + } + } + + return Resolve(name); + } + + private ICssValue? Evaluate(CssPropertyRegistration registration, Boolean compute) + { + var name = registration.Name; + + if (_keywords is not null && _keywords.TryGetValue(name, out var keyword)) + { + return keyword switch + { + "initial" => Initial(registration, compute), + "inherit" => Parent(registration, compute), + _ => Unset(registration, compute), + }; + } + + if (_values is not null && _values.TryGetValue(name, out var declared) && declared is not null) + { + var matched = registration.Syntax.Match(declared); + + if (matched is not null) + { + return compute ? ComputeValue(registration, matched) : matched; + } + } + + // not declared, or invalid at computed-value time + return Unset(registration, compute); + } + + private ICssValue? Unset(CssPropertyRegistration registration, Boolean compute) => + registration.Inherits ? Parent(registration, compute) : Initial(registration, compute); + + // the parent's value is computed already, unless it was computed without the registration + private ICssValue? Parent(CssPropertyRegistration registration, Boolean compute) + { + var inherited = ResolveParent(registration.Name); + + if (inherited is not null) + { + var matched = registration.Syntax.Match(inherited); + + if (matched is not null) + { + // a typed value is the computed value of the parent already + return inherited is not CssAnyValue ? inherited : compute ? ComputeValue(registration, matched) : matched; + } + } + + return Initial(registration, compute); + } + + private ICssValue? Initial(CssPropertyRegistration registration, Boolean compute) + { + var initial = registration.InitialValue; + return initial is not null && compute ? ComputeValue(registration, initial) : initial; + } + + private ICssValue? ComputeValue(CssPropertyRegistration registration, ICssValue value) + { + if (registration.Syntax.IsUniversal || _context is null) + { + return value; + } + + return CssProperty.ComputeValue(value, ValueConverters.Any, registration.Name, _context) ?? value; + } + + private static Boolean IsCssWideKeyword(String keyword) => + keyword.Isi(CssKeywords.Initial) || keyword.Isi(CssKeywords.Inherit) || keyword.Isi(CssKeywords.Unset); + + #endregion + private sealed class Node { public Node(String name, CssVariableValue[] values) diff --git a/src/AngleSharp.Css/Values/CssPropertyRegistration.cs b/src/AngleSharp.Css/Values/CssPropertyRegistration.cs new file mode 100644 index 00000000..10f011f9 --- /dev/null +++ b/src/AngleSharp.Css/Values/CssPropertyRegistration.cs @@ -0,0 +1,176 @@ +namespace AngleSharp.Css.Values +{ + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + using System.Runtime.CompilerServices; + using System.Threading; + + /// + /// The registration of a custom property, e.g., by a valid @property rule. + /// https://www.w3.org/TR/css-properties-values-api-1/#custom-property-registration + /// + sealed class CssPropertyRegistration + { + public CssPropertyRegistration(String name, CssPropertySyntax syntax, Boolean inherits, ICssValue? initialValue) + { + Name = name; + Syntax = syntax; + Inherits = inherits; + InitialValue = initialValue; + } + + /// + /// Creates the registration with the given (non-universal or optional) initial value, + /// which has to match the syntax and be computationally independent. + /// + /// The registration or null if the initial value is not valid. + public static CssPropertyRegistration? Create(String name, CssPropertySyntax syntax, Boolean inherits, String? initialText) + { + var initial = default(ICssValue); + + if (initialText is not null) + { + if (!CssPropertySyntax.IsComputationallyIndependent(initialText)) + { + return null; + } + + initial = syntax.Match(new CssAnyValue(initialText, isResolved: true)); + } + + if (initial is null && !syntax.IsUniversal) + { + return null; + } + + return new CssPropertyRegistration(name, syntax, inherits, initial); + } + + /// + /// Checks if the name is a custom property name, i.e., starts with two dashes. + /// + public static Boolean IsCustomPropertyName(String? name) => + name is not null && name.Length > 2 && name.StartsWith("--", StringComparison.Ordinal); + + /// + /// Gets the name of the custom property, e.g., --my-color. + /// + public String Name { get; } + + /// + /// Gets the syntax values of the property have to match. + /// + public CssPropertySyntax Syntax { get; } + + /// + /// Gets if the property is inherited. + /// + public Boolean Inherits { get; } + + /// + /// Gets the initial value (matched against the syntax), which is null, i.e., the + /// guaranteed-invalid value, for the universal syntax without an initial value. + /// + public ICssValue? InitialValue { get; } + } + + /// + /// The registered custom properties of a document, where the last registration + /// of a name wins. + /// + sealed class CssPropertyRegistry + { + private readonly Dictionary _registrations; + + public CssPropertyRegistry() + { + _registrations = new Dictionary(StringComparer.Ordinal); + } + + private CssPropertyRegistry(CssPropertyRegistry other) + { + _registrations = new Dictionary(other._registrations, StringComparer.Ordinal); + } + + public Boolean Contains(String name) => _registrations.ContainsKey(name); + + /// + /// Creates a copy of the registry with the given registration added. + /// + public CssPropertyRegistry With(CssPropertyRegistration registration) + { + var copy = new CssPropertyRegistry(this); + copy.Register(registration); + return copy; + } + + /// + /// Adds the registrations of the other registry, which replace the own ones. + /// + public void RegisterAll(CssPropertyRegistry other) + { + foreach (var registration in other.Registrations) + { + Register(registration); + } + } + + public Int32 Count => _registrations.Count; + + public IEnumerable Registrations => _registrations.Values; + + public void Register(CssPropertyRegistration registration) => _registrations[registration.Name] = registration; + + public CssPropertyRegistration? Get(String name) => + _registrations.Count > 0 && _registrations.TryGetValue(name, out var registration) ? registration : null; + } + + /// + /// The custom properties registered by script (CSS.registerProperty) per document, which + /// win over the registrations of @property rules (CSS Properties and Values API 2.1). + /// + static class CssScriptPropertyRegistrations + { + private static readonly ConditionalWeakTable Registrations = new(); + + /// + /// Gets the (immutable) registrations of the document, if any. + /// + public static CssPropertyRegistry? Get(IDocument document) => + Registrations.TryGetValue(document, out var holder) ? holder.Registry : null; + + /// + /// Adds the registration to the document. + /// + /// False if the name has been registered by script already. + public static Boolean TryAdd(IDocument document, CssPropertyRegistration registration) + { + var holder = Registrations.GetValue(document, _ => new Holder()); + + lock (holder) + { + if (holder.Registry.Contains(registration.Name)) + { + return false; + } + + // replaced rather than changed, as styles may be computed meanwhile + holder.Registry = holder.Registry.With(registration); + return true; + } + } + + private sealed class Holder + { + private CssPropertyRegistry _registry = new(); + + public CssPropertyRegistry Registry + { + get => Volatile.Read(ref _registry); + set => Volatile.Write(ref _registry, value); + } + } + } +} diff --git a/src/AngleSharp.Css/Values/CssPropertySyntax.cs b/src/AngleSharp.Css/Values/CssPropertySyntax.cs new file mode 100644 index 00000000..67cb5a72 --- /dev/null +++ b/src/AngleSharp.Css/Values/CssPropertySyntax.cs @@ -0,0 +1,268 @@ +namespace AngleSharp.Css.Values +{ + using AngleSharp.Css.Converters; + using AngleSharp.Css.Dom; + using AngleSharp.Css.Parser; + using AngleSharp.Css.Parser.Tokens; + using AngleSharp.Text; + using System; + using System.Collections.Generic; + + /// + /// The syntax definition of a registered custom property, e.g., "<length> | auto" + /// or "<color>#". + /// https://www.w3.org/TR/css-properties-values-api-1/#syntax-strings + /// + sealed class CssPropertySyntax + { + #region Fields + + private static readonly Dictionary DataTypes = new(StringComparer.Ordinal) + { + { "length", ValueConverters.LengthConverter }, + { "number", ValueConverters.NumberConverter }, + { "percentage", ValueConverters.PercentConverter }, + { "length-percentage", ValueConverters.LengthOrPercentConverter }, + { "color", ValueConverters.CurrentColorConverter }, + { "image", ValueConverters.Or(ValueConverters.UrlConverter, ValueConverters.GradientConverter, new ClassValueConverter(CompoundParser.ParseImageSet)) }, + { "url", ValueConverters.UrlConverter }, + { "integer", ValueConverters.IntegerConverter }, + { "angle", new ClassValueConverter(UnitParser.ParseAngleOrCalc) }, + { "time", ValueConverters.TimeConverter }, + { "resolution", ValueConverters.ResolutionConverter }, + { "transform-function", ValueConverters.TransformConverter }, + { "transform-list", ValueConverters.TransformConverter.Many() }, + { "custom-ident", new IdentConverter(null) }, + { "string", ValueConverters.StringConverter }, + }; + + // the units of lengths depending on the font or the root element, see 2.5 + private static readonly HashSet DependentUnits = new(StringComparer.OrdinalIgnoreCase) + { + "em", "ex", "cap", "ch", "ic", "lh", "rem", "rex", "rcap", "rch", "ric", "rlh", + }; + + private readonly String _text; + private readonly Component[] _components; + + #endregion + + #region ctor + + private CssPropertySyntax(String text, Component[] components) + { + _text = text; + _components = components; + } + + #endregion + + #region Properties + + /// + /// Gets the syntax string as specified. + /// + public String Text => _text; + + /// + /// Gets if the syntax is the universal syntax definition, i.e., "*". + /// + public Boolean IsUniversal => _components.Length == 0; + + #endregion + + #region Parsing + + /// + /// Parses the given syntax string. + /// https://www.w3.org/TR/css-properties-values-api-1/#consume-syntax-definition + /// + /// The syntax definition or null if the string is not valid. + public static CssPropertySyntax? Parse(String text) + { + var definition = TrimWhitespace(text); + + if (definition.Length == 0) + { + return null; + } + + if (definition == "*") + { + return new CssPropertySyntax(text, Array.Empty()); + } + + var parts = definition.Split('|'); + var components = new Component[parts.Length]; + + for (var i = 0; i < parts.Length; i++) + { + var component = ParseComponent(TrimWhitespace(parts[i])); + + if (component is null) + { + return null; + } + + components[i] = component; + } + + return new CssPropertySyntax(text, components); + } + + private static Component? ParseComponent(String text) + { + if (text.Length == 0) + { + return null; + } + + // the multiplier has to follow the name immediately, e.g., + + var multiplier = text[text.Length - 1] is Symbols.Plus or Symbols.Num ? text[text.Length - 1] : default(Char?); + var name = multiplier.HasValue ? text.Substring(0, text.Length - 1) : text; + + if (name.Length > 2 && name[0] == Symbols.LessThan && name[name.Length - 1] == Symbols.GreaterThan) + { + var type = name.Substring(1, name.Length - 2); + + // is already a list, i.e., cannot be multiplied + if (!DataTypes.TryGetValue(type, out var converter) || (type == "transform-list" && multiplier.HasValue)) + { + return null; + } + + return new Component(Multiply(converter, multiplier)); + } + + return IsCustomIdent(name) ? new Component(Multiply(new IdentConverter(name), multiplier)) : null; + } + + private static IValueConverter Multiply(IValueConverter converter, Char? multiplier) => multiplier switch + { + Symbols.Plus => converter.Many(), + Symbols.Num => converter.FromList(), + _ => converter, + }; + + private static Boolean IsCustomIdent(String text) + { + var source = new StringSource(text); + var ident = source.ParseCustomIdent(); + return ident is not null && ident.Length == text.Length && source.IsDone && !IsCssWideKeyword(ident); + } + + private static Boolean IsCssWideKeyword(String ident) => + ident.Isi(CssKeywords.Initial) || ident.Isi(CssKeywords.Inherit) || ident.Isi(CssKeywords.Unset) || + ident.Isi(CssKeywords.Revert) || ident.Isi(CssKeywords.RevertLayer) || ident.Isi(CssKeywords.Default); + + private static String TrimWhitespace(String text) => text.Trim(' ', '\t', '\n', '\r', '\f'); + + #endregion + + #region Matching + + /// + /// Matches the value against the syntax, trying the components in their order. + /// + /// The value, e.g., the substituted value of a declaration. + /// The value according to the first matching component, or null if none matches. + public ICssValue? Match(ICssValue value) + { + if (IsUniversal) + { + return value; + } + + var text = value.CssText; + + foreach (var component in _components) + { + var source = new StringSource(text); + source.SkipSpacesAndComments(); + var result = component.Converter.Convert(source); + source.SkipSpacesAndComments(); + + if (result is not null && source.IsDone) + { + return result; + } + } + + return null; + } + + /// + /// Checks if the value can be computed without the element, i.e., if it does not + /// refer to custom properties or to the font of the element or the root. + /// https://www.w3.org/TR/css-properties-values-api-1/#computationally-independent + /// + public static Boolean IsComputationallyIndependent(String text) + { + var tokenizer = new CssTokenizer(new TextSource(text)); + + while (true) + { + var token = tokenizer.Get(); + + switch (token.Type) + { + case CssTokenType.EndOfFile: + return true; + case CssTokenType.Function when IsReference(token.Data): + return false; + case CssTokenType.Dimension when DependentUnits.Contains(token.Data.CssUnit(out _)): + return false; + } + } + } + + private static Boolean IsReference(String name) + { + var function = name.TrimEnd(Symbols.RoundBracketOpen); + return function.Isi(FunctionNames.Var) || function.Isi(FunctionNames.Env) || function.Isi(FunctionNames.Attr); + } + + #endregion + + #region Components + + private sealed class Component + { + public Component(IValueConverter converter) + { + Converter = converter; + } + + public IValueConverter Converter { get; } + } + + /// + /// Converts a <custom-ident>, or exactly the given identifier (case-sensitive). + /// + private sealed class IdentConverter : IValueConverter + { + private readonly String? _ident; + + public IdentConverter(String? ident) + { + _ident = ident; + } + + public ICssValue? Convert(StringSource source) + { + var start = source.Index; + var ident = source.ParseCustomIdent(); + + if (ident is not null && !IsCssWideKeyword(ident) && (_ident is null || String.Equals(ident, _ident, StringComparison.Ordinal))) + { + return new CssIdentifierValue(ident); + } + + source.BackTo(start); + return null; + } + } + + #endregion + } +} From 698b68c6deda81b48c6ac90a69b34e006dc7e4f6 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 13:01:38 +0100 Subject: [PATCH 03/12] Improved CSSOM #275 --- CHANGELOG.md | 2 + docs/general/07-Supported-At-Rules.md | 2 +- docs/general/09-Typed-OM.md | 67 +++- .../Styling/PropertyRegistrationCacheTests.cs | 201 ++++++++++++ .../Styling/PropertyRegistrationTests.cs | 155 ++++++++++ .../TypedOm/RegisteredPropertyTypedOmTests.cs | 205 +++++++++++++ .../Dom/CssHelpers.Properties.cs | 4 +- .../Dom/CssPropertyRegistrationOrigin.cs | 17 ++ .../Dom/ICssPropertyRegistration.cs | 69 +++++ .../Dom/Internal/CssRuleList.cs | 19 ++ .../Dom/Internal/Rules/CssDescriptorRule.cs | 30 +- .../Dom/Internal/Rules/CssPropertyRule.cs | 17 +- .../CssPropertyRegistrationExtensions.cs | 62 ++++ src/AngleSharp.Css/TypedOm/CssStyleValue.cs | 11 +- .../TypedOm/CssStyleValueReifier.cs | 24 ++ .../TypedOm/CssTypedOmExtensions.cs | 17 ++ .../ElementComputedStyleMapExtensions.cs | 2 +- .../TypedOm/ElementStyleMapExtensions.cs | 2 +- .../TypedOm/StylePropertyMap.cs | 23 +- .../TypedOm/StylePropertyMapReadOnly.cs | 48 ++- .../TypedOm/TypedOmProperties.cs | 26 +- .../Values/CssPropertyRegistration.cs | 59 +++- .../Values/CssPropertyRegistryCache.cs | 285 ++++++++++++++++++ .../Values/CssPropertySyntax.cs | 64 +++- 24 files changed, 1365 insertions(+), 46 deletions(-) create mode 100644 src/AngleSharp.Css.Tests/Styling/PropertyRegistrationCacheTests.cs create mode 100644 src/AngleSharp.Css.Tests/Styling/PropertyRegistrationTests.cs create mode 100644 src/AngleSharp.Css.Tests/TypedOm/RegisteredPropertyTypedOmTests.cs create mode 100644 src/AngleSharp.Css/Dom/CssPropertyRegistrationOrigin.cs create mode 100644 src/AngleSharp.Css/Dom/ICssPropertyRegistration.cs create mode 100644 src/AngleSharp.Css/Extensions/CssPropertyRegistrationExtensions.cs create mode 100644 src/AngleSharp.Css/Values/CssPropertyRegistryCache.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c4bfe95f..89da6c8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Released on tbd. - Added support for registered custom properties via `@property` (#274): the rule validates its descriptors (`syntax`, `inherits`, `initial-value`) and exposes them on `ICssPropertyRule` (`Syntax`, `Inherits`, `InitialValue`, `IsValid`), and a valid registration makes the custom property match its syntax (otherwise it is invalid at computed-value time), have its initial value, be computed (e.g., `2em` to `32px`), and only be inherited if registered so - Added `CSS.registerProperty()` (`RegisterProperty` on `CssHelpers` for a window or a document, with a `PropertyDefinition`), which registers a custom property for the document like `@property` does and wins over `@property` rules of the same name; an invalid definition is a `SyntaxError`, registering a name twice an `InvalidModificationError` +- Added a common representation of registered custom properties (#275), `ICssPropertyRegistration` (`Name`, `Syntax`, `Inherits`, `InitialValue`, `RawInitialValue`, `IsList`, `Origin`, `Match`), shared by `@property` rules and `CSS.registerProperty()`: `GetRegisteredProperties()` and `GetRegisteredProperty(name)` give the registrations in effect for a document, `GetRegistration()` the one of a `@property` rule; the registrations of a document are kept until the DOM, the rules, the style sheets, or the conditions around `@property` rules change +- Added typing registered custom properties in the Typed OM according to their syntax (#275): declared values in `attributeStyleMap` and `styleMap` (e.g., a `CssUnitValue` of `2em` for ``), one value per item for a list syntax (`#`, `+`), and `CssStyleValue.Parse`; `Set` and `Append` reject values not matching the syntax and are only list-valued for a list syntax - Added the CSS Typed OM (#276) in the `AngleSharp.Css.TypedOm` namespace: typed values (`CssUnitValue`, `CssKeywordValue`, `CssUnparsedValue`, the math values such as `CssMathSum`, `CssTransformValue`, `CssPositionValue`, `CssImageValue`) with unit-aware arithmetic and conversions, the `CSS.px()`-style factories on `CssHelpers`, and style property maps over declared (`attributeStyleMap`, `styleMap` of a rule) and computed (`computedStyleMap()`) styles, which read from and write to the existing declarations # 1.4.2 diff --git a/docs/general/07-Supported-At-Rules.md b/docs/general/07-Supported-At-Rules.md index b5824136..ef72b77e 100644 --- a/docs/general/07-Supported-At-Rules.md +++ b/docs/general/07-Supported-At-Rules.md @@ -27,7 +27,7 @@ This page documents the at-rules recognized by the AngleSharp.Css parser (`CssBu | `@container` | CSS Containment / Container Queries | Parsed into `CssContainerRule` with nested rules. | Condition text parsing is syntax-driven; unsupported condition forms may be rejected. | | `@layer` | CSS Cascade Layers | Parsed into `CssLayerRule` (statement and block forms). | Layer ordering semantics beyond parsed structure are not enforced by a rendering engine here. | | `@scope` | CSS Scoping | Parsed into `CssScopeRule` with nested rules. | Scope prelude is stored as text; advanced selector semantics depend on parser support. | -| `@property` | CSS Properties and Values API | Parsed into `CssPropertyRule` (`Syntax`, `Inherits`, `InitialValue`, `IsValid`). Valid rules register the custom property: values are validated against the syntax and computed, the initial value and inheritance apply. | Registration follows the conditions of enclosing `@media` / `@supports` rules like style rules. Script can register custom properties with `CSS.registerProperty()` (`window.RegisterProperty(new PropertyDefinition { ... })`), which wins over `@property` for the same name. | +| `@property` | CSS Properties and Values API | Parsed into `CssPropertyRule` (`Syntax`, `Inherits`, `InitialValue`, `IsValid`). Valid rules register the custom property: values are validated against the syntax and computed, the initial value and inheritance apply. | Registration follows the conditions of enclosing `@media` / `@supports` rules like style rules. Script can register custom properties with `CSS.registerProperty()` (`window.RegisterProperty(new PropertyDefinition { ... })`), which wins over `@property` for the same name. The registrations in effect are available as `ICssPropertyRegistration` via `document.GetRegisteredProperties()`, see [Typed OM](09-Typed-OM.md#registered-custom-properties). | | `@starting-style` | CSS Transitions Level 2 | Parsed into `CssStartingStyleRule` with nested rules. | Behavior-level transition semantics are not evaluated. | | `@view-transition` | View Transitions | Parsed into `CssViewTransitionRule` with descriptor storage. | Descriptors are stored generically, without dedicated descriptor schema validation. | | `@position-try` | CSS Anchor Positioning | Parsed into `CssPositionTryRule` with declaration block. | No layout fallback engine; parsing/serialization only. | diff --git a/docs/general/09-Typed-OM.md b/docs/general/09-Typed-OM.md index c0616661..62b63ae0 100644 --- a/docs/general/09-Typed-OM.md +++ b/docs/general/09-Typed-OM.md @@ -70,8 +70,73 @@ var t = b.Type(); // length: 1 - `Equals` compares values structurally. - `CssTransformValue.ToMatrix()` gives the `TransformMatrix` of a transform with absolute units. +## Registered Custom Properties + +A custom property can be registered with a valid `@property` rule or with `CSS.registerProperty()` (`window.RegisterProperty(new PropertyDefinition { ... })`), see the [CSS Properties and Values API Level 1](https://www.w3.org/TR/css-properties-values-api-1/). Both kinds of registration share one representation, `ICssPropertyRegistration`, which the cascade, the computed style, and the Typed OM use alike. + +```cs +using AngleSharp.Css.Dom; +using AngleSharp.Css.TypedOm; + +// the registrations in effect for the document (script wins over @property for a name) +var registration = document.GetRegisteredProperty("--gap"); +var all = document.GetRegisteredProperties(); + +registration.Syntax; // "" +registration.Inherits; // false +registration.Origin; // Rule (@property) or Script (CSS.registerProperty) +registration.IsList; // true for e.g. "#" or "+" +registration.InitialValue; // "0px" +registration.RawInitialValue; // the CSSOM value, e.g., a CssLengthValue +registration.RawInitialValue.ToStyleValue(registration.Name); // CssUnitValue 0px +registration.Match("10px"); // the CSSOM value matching the syntax, or null + +// the registration a single @property rule makes, whether it is in effect or not +var own = propertyRule.GetRegistration(); // null if the rule is not valid +``` + +The registrations always reflect the current style sheets, but they are only collected again after something they depend on changed: the DOM (e.g., an added or removed `
"); + + private static ICssStyleSheet Sheet(IDocument document) => (ICssStyleSheet)document.StyleSheets[0]; + + private static ICssPropertyRule PropertyRule(IDocument document) => Sheet(document).Rules.OfType().Single(); + + [Test] + public void SameRegistryWithoutChanges() + { + var document = Document(Length); + var first = document.GetRegisteredProperty("--len"); + + Assert.AreSame(first, document.GetRegisteredProperty("--len")); + } + + [Test] + public void UnrelatedDomChangeKeepsTheRegistrations() + { + var document = Document(Length); + document.GetRegisteredProperty("--len"); + document.Body.AppendChild(document.CreateElement("p")); + + Assert.AreEqual("", document.GetRegisteredProperty("--len").Syntax); + } + + [Test] + public void InsertedAndRemovedRules() + { + var document = Document(""); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + Sheet(document).Insert(Length, 0); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + + Sheet(document).RemoveAt(0); + Assert.IsNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void RuleInsertedIntoAMediaRule() + { + var document = Document("@media all { }"); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + ((ICssMediaRule)Sheet(document).Rules[0]).Insert(Length, 0); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void ChangedDescriptors() + { + var document = Document(Length); + Assert.AreEqual("", document.GetRegisteredProperty("--len").Syntax); + + PropertyRule(document).SetProperty("syntax", "\"\""); + PropertyRule(document).SetProperty("initial-value", "red"); + Assert.AreEqual("", document.GetRegisteredProperty("--len").Syntax); + + PropertyRule(document).RemoveProperty("inherits"); + Assert.IsNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void DescriptorChangedViaItsProperty() + { + var document = Document(Length); + Assert.AreNotEqual("5px", document.GetRegisteredProperty("--len").InitialValue); + + PropertyRule(document).GetProperty("initial-value").Value = "5px"; + Assert.AreEqual("5px", document.GetRegisteredProperty("--len").InitialValue); + } + + [Test] + public void RemovedAndAddedStyleElements() + { + var document = Document(Length); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + + var style = document.QuerySelector("style"); + style.Remove(); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + document.Head.AppendChild(style); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void ChangedStyleText() + { + var document = Document(Length); + Assert.AreEqual("", document.GetRegisteredProperty("--len").Syntax); + + document.QuerySelector("style").TextContent = Length.Replace("", ""); + Assert.AreEqual("", document.GetRegisteredProperty("--len").Syntax); + } + + [Test] + public void ChangedMediaAttribute() + { + var document = Document(Length); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + + document.QuerySelector("style").SetAttribute("media", "print"); + Assert.IsNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void DisabledStyleSheet() + { + var document = Document(Length); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + + // a disabled sheet is not in the list of the document anymore + var sheet = Sheet(document); + sheet.IsDisabled = true; + Assert.IsNull(document.GetRegisteredProperty("--len")); + + sheet.IsDisabled = false; + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void AdoptedStyleSheets() + { + var document = Document(""); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + var sheet = new CssStyleSheet(document.DefaultView); + sheet.ReplaceSync(Length); + document.GetAdoptedStyleSheets().Add(sheet); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + + sheet.ReplaceSync(""); + Assert.IsNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void ChangedMediaRuleCondition() + { + var document = Document("@media print { " + Length + " }"); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + ((ICssMediaRule)Sheet(document).Rules[0]).Media.MediaText = "all"; + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void ChangedDevice() + { + var device = new DefaultRenderDevice { DeviceWidth = 1280, DeviceHeight = 800, ViewPortWidth = 1280, ViewPortHeight = 800 }; + var context = BrowsingContext.New(Configuration.Default.WithCss().WithRenderDevice(device)); + var document = context.GetService().ParseDocument(""); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + device.ViewPortWidth = 500; + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void ScriptRegistration() + { + var document = Document(Length); + Assert.AreEqual(CssPropertyRegistrationOrigin.Rule, document.GetRegisteredProperty("--len").Origin); + + document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--len", Syntax = "*" }); + Assert.AreEqual(CssPropertyRegistrationOrigin.Script, document.GetRegisteredProperty("--len").Origin); + } + + [Test] + public void StyleMapSeesChanges() + { + var document = ParseDocument("
"); + var map = document.GetElementById("target").GetAttributeStyleMap(); + Assert.IsInstanceOf(map.Get("--len")); + + Sheet(document).Insert(Length, 0); + Assert.IsInstanceOf(map.Get("--len")); + } + } +} diff --git a/src/AngleSharp.Css.Tests/Styling/PropertyRegistrationTests.cs b/src/AngleSharp.Css.Tests/Styling/PropertyRegistrationTests.cs new file mode 100644 index 00000000..495a1a5b --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/PropertyRegistrationTests.cs @@ -0,0 +1,155 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.TypedOm; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Linq; + using static CssConstructionFunctions; + + /// + /// The representation of registrations (CSS Properties and Values API 1, 2.1), which + /// @property rules and CSS.registerProperty() share. + /// + [TestFixture] + public class PropertyRegistrationTests + { + private const String LengthRule = "@property --len { syntax: \"\"; inherits: true; initial-value: 1in; }"; + + private static IDocument Document(String css, String body = "") => + ParseDocument($"{body}"); + + [Test] + public void PropertyRuleRegistrationIsExposed() + { + var registration = Document(LengthRule).GetRegisteredProperty("--len"); + + Assert.IsNotNull(registration); + Assert.AreEqual("--len", registration.Name); + Assert.AreEqual("", registration.Syntax); + Assert.IsFalse(registration.IsUniversal); + Assert.IsFalse(registration.IsList); + Assert.IsTrue(registration.Inherits); + Assert.AreEqual(CssPropertyRegistrationOrigin.Rule, registration.Origin); + } + + [Test] + public void InitialValueHasAllRepresentations() + { + var registration = Document(LengthRule).GetRegisteredProperty("--len"); + + Assert.AreEqual("1in", registration.InitialValue); + Assert.IsInstanceOf(registration.RawInitialValue); + var typed = (CssUnitValue)registration.RawInitialValue.ToStyleValue(registration.Name); + Assert.AreEqual(1.0, typed.Value); + Assert.AreEqual("in", typed.Unit); + } + + [Test] + public void UniversalSyntaxWithoutInitialValue() + { + var registration = Document("@property --any { syntax: \"*\"; inherits: false; }").GetRegisteredProperty("--any"); + + Assert.IsTrue(registration.IsUniversal); + Assert.IsNull(registration.InitialValue); + Assert.IsNull(registration.RawInitialValue); + } + + [Test] + public void ScriptRegistrationIsExposedAndWins() + { + var document = Document(LengthRule); + document.DefaultView.RegisterProperty(new PropertyDefinition + { + Name = "--len", + Syntax = "", + InitialValue = "red", + }); + var registration = document.GetRegisteredProperty("--len"); + + Assert.AreEqual(CssPropertyRegistrationOrigin.Script, registration.Origin); + Assert.AreEqual("", registration.Syntax); + Assert.IsFalse(registration.Inherits); + Assert.AreEqual(1, document.GetRegisteredProperties().Count()); + } + + [Test] + public void InvalidAndUnregisteredPropertiesHaveNoRegistration() + { + var document = Document("@property --bad { syntax: \"\"; inherits: false; initial-value: 1em; }"); + + Assert.IsNull(document.GetRegisteredProperty("--bad")); + Assert.IsNull(document.GetRegisteredProperty("--unknown")); + Assert.IsNull(document.GetRegisteredProperty("color")); + Assert.AreEqual(0, document.GetRegisteredProperties().Count()); + } + + [Test] + public void LastValidRuleWins() + { + var css = LengthRule + " @property --len { syntax: \"\"; inherits: false; initial-value: blue; }"; + var registration = Document(css).GetRegisteredProperty("--len"); + + Assert.AreEqual("", registration.Syntax); + } + + [Test] + public void RegistrationFollowsConditionalRules() + { + var document = Document("@media print { " + LengthRule + " }"); + Assert.IsNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void RegistrationReflectsChangedStyleSheets() + { + var document = Document(""); + Assert.IsNull(document.GetRegisteredProperty("--len")); + + var sheet = (ICssStyleSheet)document.StyleSheets[0]; + sheet.Insert(LengthRule, 0); + Assert.IsNotNull(document.GetRegisteredProperty("--len")); + } + + [Test] + public void RuleGivesItsRegistration() + { + var sheet = ParseStyleSheet(LengthRule + " @property --bad { syntax: \"\"; }"); + var rules = sheet.Rules.OfType().ToArray(); + + var registration = rules[0].GetRegistration(); + Assert.AreEqual("--len", registration.Name); + Assert.AreEqual(rules[0].Syntax, registration.Syntax); + Assert.AreEqual(rules[0].Inherits, registration.Inherits); + Assert.AreEqual(rules[0].InitialValue, registration.InitialValue); + Assert.IsNull(rules[1].GetRegistration()); + } + + [Test] + public void MatchUsesTheSyntax() + { + var registration = Document("@property --v { syntax: \" | auto\"; inherits: false; initial-value: auto; }").GetRegisteredProperty("--v"); + + Assert.IsInstanceOf(registration.Match("10px")); + Assert.AreEqual("auto", registration.Match(" auto ").CssText); + Assert.IsNull(registration.Match("red")); + Assert.IsNull(registration.Match("var(--x)")); + } + + [Test] + public void ListSyntaxes() + { + var css = "@property --a { syntax: \"#\"; inherits: false; initial-value: 0px; } " + + "@property --b { syntax: \"+\"; inherits: false; initial-value: 0px; } " + + "@property --c { syntax: \"# | \"; inherits: false; initial-value: 0px; }"; + var document = Document(css); + + Assert.IsTrue(document.GetRegisteredProperty("--a").IsList); + Assert.IsTrue(document.GetRegisteredProperty("--b").IsList); + Assert.IsFalse(document.GetRegisteredProperty("--c").IsList); + } + } +} diff --git a/src/AngleSharp.Css.Tests/TypedOm/RegisteredPropertyTypedOmTests.cs b/src/AngleSharp.Css.Tests/TypedOm/RegisteredPropertyTypedOmTests.cs new file mode 100644 index 00000000..c1bc5058 --- /dev/null +++ b/src/AngleSharp.Css.Tests/TypedOm/RegisteredPropertyTypedOmTests.cs @@ -0,0 +1,205 @@ +#nullable disable +namespace AngleSharp.Css.Tests.TypedOm +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Linq; + using System.Threading.Tasks; + using static CssConstructionFunctions; + + /// + /// The typed values of registered custom properties (CSS Typed OM 1, 5 and CSS + /// Properties and Values API 1, 6) and their relation to the CSSOM. + /// + [TestFixture] + public class RegisteredPropertyTypedOmTests + { + private const String Rules = + "@property --len { syntax: \"\"; inherits: false; initial-value: 0px; } " + + "@property --list { syntax: \"#\"; inherits: false; initial-value: 0px; } " + + "@property --spaced { syntax: \"+\"; inherits: false; initial-value: 0px; } " + + "@property --any { syntax: \"*\"; inherits: false; }"; + + private static IElement CreateElement(String style) + { + var document = ParseDocument($"
"); + return document.GetElementById("target"); + } + + [Test] + public void DeclaredValueIsTypedBySyntax() + { + var map = CreateElement("--len: 2em; --other: 2em").GetAttributeStyleMap(); + var value = map.Get("--len") as CssUnitValue; + + Assert.IsNotNull(value); + Assert.AreEqual(2.0, value.Value); + Assert.AreEqual("em", value.Unit); + Assert.IsInstanceOf(map.Get("--other")); + } + + [Test] + public void DeclaredValueWithReferenceIsUnparsed() + { + var map = CreateElement("--len: var(--x)").GetAttributeStyleMap(); + Assert.IsInstanceOf(map.Get("--len")); + } + + [Test] + public void DeclaredValueNotMatchingTheSyntaxIsUnparsed() + { + // invalid at computed-value time, but still declared + var map = CreateElement("--len: red").GetAttributeStyleMap(); + Assert.IsInstanceOf(map.Get("--len")); + } + + [Test] + public void UniversalSyntaxIsUnparsed() + { + var map = CreateElement("--any: 10px").GetAttributeStyleMap(); + Assert.IsInstanceOf(map.Get("--any")); + } + + [Test] + public void ListSyntaxesGiveOneValuePerItem() + { + var map = CreateElement("--list: 1px, 2px; --spaced: 3px 4px 5px").GetAttributeStyleMap(); + + Assert.AreEqual(new[] { "1px", "2px" }, map.GetAll("--list").Select(m => m.ToString()).ToArray()); + Assert.AreEqual(new[] { "3px", "4px", "5px" }, map.GetAll("--spaced").Select(m => m.ToString()).ToArray()); + Assert.IsTrue(map.GetAll("--spaced").All(m => m is CssUnitValue)); + } + + [Test] + public void SetValidatesTheSyntax() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + + map.Set("--len", CssHelpers.Px(10)); + Assert.AreEqual("10px", element.GetStyle().GetPropertyValue("--len")); + Assert.Throws(() => map.Set("--len", "red")); + Assert.Throws(() => map.Set("--len", CssHelpers.Number(3))); + Assert.AreEqual("10px", element.GetStyle().GetPropertyValue("--len")); + } + + [Test] + public void SetAcceptsReferencesAndKeywords() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + + map.Set("--len", "var(--x)"); + Assert.AreEqual("var(--x)", element.GetStyle().GetPropertyValue("--len")); + map.Set("--len", "initial"); + Assert.AreEqual("initial", element.GetStyle().GetPropertyValue("--len")); + } + + [Test] + public void SetOfUnregisteredOrUniversalPropertyAcceptsAnything() + { + var map = CreateElement("").GetAttributeStyleMap(); + + Assert.DoesNotThrow(() => map.Set("--other", "red")); + Assert.DoesNotThrow(() => map.Set("--any", "red")); + } + + [Test] + public void ListSyntaxIsListValued() + { + var element = CreateElement(""); + var map = element.GetAttributeStyleMap(); + + map.Set("--list", CssHelpers.Px(1), CssHelpers.Px(2)); + map.Append("--list", CssHelpers.Px(3)); + map.Set("--spaced", CssHelpers.Px(4), CssHelpers.Px(5)); + + Assert.AreEqual("1px, 2px, 3px", element.GetStyle().GetPropertyValue("--list")); + Assert.AreEqual("4px 5px", element.GetStyle().GetPropertyValue("--spaced")); + Assert.AreEqual(3, map.GetAll("--list").Count); + Assert.Throws(() => map.Append("--list", "red")); + } + + [Test] + public void NonListSyntaxIsNotListValued() + { + var map = CreateElement("").GetAttributeStyleMap(); + + Assert.Throws(() => map.Set("--len", CssHelpers.Px(1), CssHelpers.Px(2))); + Assert.Throws(() => map.Append("--len", CssHelpers.Px(1))); + Assert.Throws(() => map.Append("--any", "a")); + } + + [Test] + public void ScriptRegistrationApplies() + { + var element = CreateElement("--c: red"); + element.Owner.DefaultView.RegisterProperty(new PropertyDefinition + { + Name = "--c", + Syntax = "", + InitialValue = "0", + }); + var map = element.GetAttributeStyleMap(); + + Assert.IsInstanceOf(map.Get("--c")); + map.Set("--c", CssHelpers.Number(5)); + Assert.IsInstanceOf(map.Get("--c")); + Assert.Throws(() => map.Set("--c", "red")); + } + + [Test] + public void StyleRuleMapUsesTheRegistrationsOfTheDocument() + { + var document = ParseDocument($""); + var sheet = (ICssStyleSheet)document.StyleSheets[0]; + var rule = sheet.Rules.OfType().Single(); + var map = rule.GetStyleMap(); + + Assert.IsInstanceOf(map.Get("--len")); + Assert.Throws(() => map.Set("--len", "red")); + } + + [Test] + public void TypedAndCssomViewsStayInSync() + { + var element = CreateElement("--len: 1px"); + var style = element.GetStyle(); + var map = element.GetAttributeStyleMap(); + + style.SetProperty("--len", "4em"); + Assert.AreEqual("4em", map.Get("--len").ToString()); + map.Set("--len", CssHelpers.Px(7)); + Assert.AreEqual("7px", style.GetPropertyValue("--len")); + // the CSSOM keeps the declared value of a custom property, i.e., any value + style.SetProperty("--len", "red"); + Assert.AreEqual("red", style.GetPropertyValue("--len")); + Assert.IsInstanceOf(map.Get("--len")); + } + + [Test] + public void ComputedMapTypesRegisteredValues() + { + var element = CreateElement("font-size: 10px; --len: 2em; --list: 1px, 1em"); + var map = element.ComputedStyleMap(); + + Assert.AreEqual("20px", map.Get("--len").ToString()); + Assert.AreEqual(new[] { "1px", "10px" }, map.GetAll("--list").Select(m => m.ToString()).ToArray()); + } + + [Test] + public async Task ParseUsesTheRegistrationOfTheActiveDocument() + { + var context = BrowsingContext.New(Configuration.Default.WithCss()); + await context.OpenAsync(res => res.Content($"")); + + Assert.IsInstanceOf(CssStyleValue.Parse("--len", "1px", context)); + Assert.Throws(() => CssStyleValue.Parse("--len", "red", context)); + Assert.AreEqual(2, CssStyleValue.ParseAll("--list", "1px, 2px", context).Count); + Assert.IsInstanceOf(CssStyleValue.Parse("--len", "1px")); + } + } +} diff --git a/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs b/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs index bc6242d7..81d51ecb 100644 --- a/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs +++ b/src/AngleSharp.Css/Dom/CssHelpers.Properties.cs @@ -58,8 +58,8 @@ public static void RegisterProperty(this IDocument document, PropertyDefinition if (CssScriptPropertyRegistrations.Get(document)?.Contains(definition.Name) == true) throw new DomException(DomError.InvalidModification); - var syntax =CssPropertySyntax.Parse(definition.Syntax ?? String.Empty) ?? throw new DomException(DomError.Syntax); - var registration = CssPropertyRegistration.Create(definition.Name, syntax, definition.Inherits, definition.InitialValue) ?? + var syntax = CssPropertySyntax.Parse(definition.Syntax ?? String.Empty) ?? throw new DomException(DomError.Syntax); + var registration = CssPropertyRegistration.Create(definition.Name, syntax, definition.Inherits, definition.InitialValue, CssPropertyRegistrationOrigin.Script) ?? throw new DomException(DomError.Syntax); if (!CssScriptPropertyRegistrations.TryAdd(document, registration)) diff --git a/src/AngleSharp.Css/Dom/CssPropertyRegistrationOrigin.cs b/src/AngleSharp.Css/Dom/CssPropertyRegistrationOrigin.cs new file mode 100644 index 00000000..bfaf06ec --- /dev/null +++ b/src/AngleSharp.Css/Dom/CssPropertyRegistrationOrigin.cs @@ -0,0 +1,17 @@ +namespace AngleSharp.Css.Dom +{ + /// + /// What registered a custom property. + /// + public enum CssPropertyRegistrationOrigin : byte + { + /// + /// A valid @property rule of a style sheet. + /// + Rule, + /// + /// Script, i.e., CSS.registerProperty(), which wins over the @property rules. + /// + Script, + } +} diff --git a/src/AngleSharp.Css/Dom/ICssPropertyRegistration.cs b/src/AngleSharp.Css/Dom/ICssPropertyRegistration.cs new file mode 100644 index 00000000..f5a10506 --- /dev/null +++ b/src/AngleSharp.Css/Dom/ICssPropertyRegistration.cs @@ -0,0 +1,69 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using System; + + /// + /// The registration of a custom property, made by a valid @property rule or by + /// CSS.registerProperty(). Both share this representation, which is what the + /// cascade, the computed style, and the Typed OM use. + /// https://www.w3.org/TR/css-properties-values-api-1/#custom-property-registration + /// + public interface ICssPropertyRegistration + { + /// + /// Gets the name of the custom property, e.g., --my-color. + /// + String Name { get; } + + /// + /// Gets the syntax values of the property have to match as specified, e.g., + /// <length> | auto, or * for the universal syntax. + /// + String Syntax { get; } + + /// + /// Gets if the syntax is the universal syntax (*), which accepts any value. + /// + Boolean IsUniversal { get; } + + /// + /// Gets if the syntax is list-valued, i.e., all of its components are multiplied + /// by # (a comma separated list) or all by + (a space separated list), e.g., + /// <length>#. + /// + Boolean IsList { get; } + + /// + /// Gets if the property is inherited. + /// + Boolean Inherits { get; } + + /// + /// Gets the serialization of the initial value, or null if there is none, i.e., + /// the initial value is the guaranteed-invalid value (only for the universal syntax). + /// + String? InitialValue { get; } + + /// + /// Gets the initial value as a value of the CSSOM, i.e., as matched against the + /// syntax (e.g., a length for <length>), or null if there is none. Use + /// ToStyleValue(Name) to get its typed (Typed OM) representation. + /// + ICssValue? RawInitialValue { get; } + + /// + /// Gets what made the registration. + /// + CssPropertyRegistrationOrigin Origin { get; } + + /// + /// Matches the given text against the syntax, using the same converters as the + /// cascade does. References (e.g., var()) are not substituted, i.e., they only + /// match the universal syntax. + /// + /// The text to match, e.g., 10px. + /// The value according to the first matching component, or null if none matches. + ICssValue? Match(String cssText); + } +} diff --git a/src/AngleSharp.Css/Dom/Internal/CssRuleList.cs b/src/AngleSharp.Css/Dom/Internal/CssRuleList.cs index b2175856..41f4a986 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssRuleList.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssRuleList.cs @@ -1,5 +1,6 @@ namespace AngleSharp.Css.Dom { + using AngleSharp.Css.Values; using AngleSharp.Dom; using System; using System.Collections; @@ -74,6 +75,7 @@ public Int32 Length public void Clear() { _rules.Clear(); + CssPropertyRegistryCache.Invalidate(); } public void RemoveAt(Int32 index) @@ -98,6 +100,7 @@ public void Remove(ICssRule rule) if (index >= 0) { _rules.RemoveAt(index); + Invalidate(rule); } } } @@ -126,6 +129,8 @@ public void Insert(Int32 index, ICssRule rule) { _rules.Insert(actualIndex, rule); } + + Invalidate(rule); } public void Add(ICssRule rule) @@ -133,6 +138,7 @@ public void Add(ICssRule rule) if (rule != null) { _rules.Add(rule); + Invalidate(rule); } } @@ -145,6 +151,19 @@ public void AddRange(IEnumerable rules) var oldLength = _rules.Count; _rules.AddRange(rules); + CssPropertyRegistryCache.Invalidate(); + } + + /// + /// Marks the registered custom properties as outdated, unless the rule cannot hold + /// a @property rule, i.e., is a style rule (whose nested rules are not registered). + /// + private static void Invalidate(ICssRule rule) + { + if (rule is not ICssStyleRule) + { + CssPropertyRegistryCache.Invalidate(); + } } internal IEnumerable GetFormattables() => _rules; diff --git a/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs b/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs index 20251859..87406655 100644 --- a/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs +++ b/src/AngleSharp.Css/Dom/Internal/Rules/CssDescriptorRule.cs @@ -33,6 +33,13 @@ protected CssDescriptorRule(ICssStyleSheet owner, CssRuleType type, String ruleN ///
protected virtual Boolean IsValidDescriptor(String name, String value) => true; + /// + /// Called after a descriptor has been added, changed, or removed. + /// + protected virtual void OnDescriptorsChanged() + { + } + public ICssProperty GetProperty(String propertyName) { for (var i = 0; i < _descriptors.Count; i++) @@ -74,6 +81,7 @@ public void SetProperty(String propertyName, String propertyValue, String priori if (property is not null) { _descriptors.Remove(property); + OnDescriptorsChanged(); } return; @@ -87,12 +95,13 @@ public void SetProperty(String propertyName, String propertyValue, String priori if (property is null) { - property = new DescriptorProperty(propertyName); + property = new DescriptorProperty(this, propertyName); _descriptors.Add(property); } - property.Value = propertyValue; property.IsImportant = priority.Is(CssKeywords.Important); + // notifies about the change + property.Value = propertyValue; } public String RemoveProperty(String propertyName) @@ -104,6 +113,7 @@ public String RemoveProperty(String propertyName) if (descriptor.Name.Is(propertyName)) { _descriptors.RemoveAt(i); + OnDescriptorsChanged(); return descriptor.Value; } } @@ -130,6 +140,7 @@ public override void ToCss(TextWriter writer, IStyleFormatter formatter) protected void ReplaceWith(ICssProperties properties) { _descriptors.Clear(); + OnDescriptorsChanged(); foreach (var property in properties) { @@ -139,10 +150,13 @@ protected void ReplaceWith(ICssProperties properties) private sealed class DescriptorProperty : ICssProperty { + private readonly CssDescriptorRule _owner; private readonly String _name; + private String _value = String.Empty; - public DescriptorProperty(String name) + public DescriptorProperty(CssDescriptorRule owner, String name) { + _owner = owner; _name = name; } @@ -150,7 +164,15 @@ public DescriptorProperty(String name) public ICssValue RawValue => null; - public String Value { get; set; } = String.Empty; + public String Value + { + get => _value; + set + { + _value = value; + _owner.OnDescriptorsChanged(); + } + } public Boolean IsImportant { get; set; } diff --git a/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs b/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs index 8206a3e4..433a6523 100644 --- a/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs +++ b/src/AngleSharp.Css/Dom/Internal/Rules/CssPropertyRule.cs @@ -23,7 +23,17 @@ internal CssPropertyRule(ICssStyleSheet owner) { } - public String Name { get; set; } + private String _name; + + public String Name + { + get => _name; + set + { + _name = value; + CssPropertyRegistryCache.Invalidate(); + } + } public String Syntax => ParseSyntaxString(GetPropertyValue(SyntaxDescriptor)) ?? String.Empty; @@ -50,7 +60,7 @@ internal CssPropertyRegistration CreateRegistration() return null; } - return CssPropertyRegistration.Create(Name, syntax, Inherits, GetProperty(InitialValueDescriptor)?.Value); + return CssPropertyRegistration.Create(Name, syntax, Inherits, GetProperty(InitialValueDescriptor)?.Value, CssPropertyRegistrationOrigin.Rule); } /// @@ -73,6 +83,9 @@ protected override Boolean IsValidDescriptor(String name, String value) return name.Isi(InitialValueDescriptor); } + // the registrations of documents may change + protected override void OnDescriptorsChanged() => CssPropertyRegistryCache.Invalidate(); + protected override void ReplaceWith(ICssRule rule) { var newRule = (ICssPropertyRule)rule; diff --git a/src/AngleSharp.Css/Extensions/CssPropertyRegistrationExtensions.cs b/src/AngleSharp.Css/Extensions/CssPropertyRegistrationExtensions.cs new file mode 100644 index 00000000..12256324 --- /dev/null +++ b/src/AngleSharp.Css/Extensions/CssPropertyRegistrationExtensions.cs @@ -0,0 +1,62 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Extensions to get the registered custom properties (CSS Properties and Values API). + /// + public static class CssPropertyRegistrationExtensions + { + /// + /// Gets the custom properties registered for the document, i.e., by the valid + /// @property rules of its style sheets (which follow the conditions of enclosing + /// rules, e.g., of @media) and by CSS.registerProperty(), which wins for the same + /// name. The registrations reflect the style sheets at the time of the call. + /// + /// The document. + /// The registrations in effect, one per name. + public static IEnumerable GetRegisteredProperties(this IDocument document) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); + + return CssPropertyRegistry.ForDocument(document).Registrations.ToArray(); + } + + /// + /// Gets the registration in effect for the given custom property of the document. + /// + /// The document. + /// The name of the custom property, e.g., --my-color. + /// The registration or null if the property is not registered. + public static ICssPropertyRegistration? GetRegisteredProperty(this IDocument document, String name) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); + + if (name is null) + throw new ArgumentNullException(nameof(name)); + + return CssPropertyRegistration.IsCustomPropertyName(name) ? CssPropertyRegistry.ForDocument(document).Get(name) : null; + } + + /// + /// Gets the registration the @property rule makes, regardless of whether it is in + /// effect for a document, e.g., if a later rule or script registers the same name. + /// + /// The @property rule. + /// The registration or null if the rule is not valid. + public static ICssPropertyRegistration? GetRegistration(this ICssPropertyRule rule) + { + if (rule is null) + throw new ArgumentNullException(nameof(rule)); + + return (rule as CssPropertyRule)?.CreateRegistration(); + } + } +} diff --git a/src/AngleSharp.Css/TypedOm/CssStyleValue.cs b/src/AngleSharp.Css/TypedOm/CssStyleValue.cs index 211546f7..a71900a1 100644 --- a/src/AngleSharp.Css/TypedOm/CssStyleValue.cs +++ b/src/AngleSharp.Css/TypedOm/CssStyleValue.cs @@ -40,7 +40,8 @@ internal CssStyleValue() /// /// The name of the property, e.g., width. /// The text to parse, e.g., 10px. - /// The browsing context determining the known properties, if any. + /// The browsing context determining the known properties, if any. A custom + /// property registered for its active document is parsed and typed according to its syntax. /// The typed value. /// The property is unknown or the text is not valid for it. public static CssStyleValue Parse(String property, String cssText, IBrowsingContext? context) => @@ -63,7 +64,8 @@ public static CssStyleValue Parse(String property, String cssText, IBrowsingCont /// /// The name of the property, e.g., background-image. /// The text to parse, e.g., url(a.png), url(b.png). - /// The browsing context determining the known properties, if any. + /// The browsing context determining the known properties, if any. A custom + /// property registered for its active document is parsed and typed according to its syntax. /// The typed values. /// The property is unknown or the text is not valid for it. public static IReadOnlyList ParseAll(String property, String cssText, IBrowsingContext? context) @@ -74,8 +76,9 @@ public static IReadOnlyList ParseAll(String property, String cssT if (cssText is null) throw new ArgumentNullException(nameof(cssText)); - var declaration = TypedOmProperties.Parse(context, property, cssText); - return CssStyleValueReifier.ReifyAll(declaration.Name, declaration.RawValue); + var registration = TypedOmProperties.GetRegistration(context, TypedOmProperties.Normalize(property)); + var declaration = TypedOmProperties.Parse(context, property, cssText, registration); + return CssStyleValueReifier.ReifyAll(declaration.Name, declaration.RawValue, registration); } /// diff --git a/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs b/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs index 3dc14199..f02d5d7f 100644 --- a/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs +++ b/src/AngleSharp.Css/TypedOm/CssStyleValueReifier.cs @@ -36,6 +36,30 @@ public static IReadOnlyList ReifyAll(String property, ICssValue? return new[] { Reify(property, value) }; } + /// + /// Reifies the value of a property, which is typed according to the syntax of the + /// given registration if it is a registered custom property: a declared value that + /// matches the syntax and has no references (e.g., 10px for <length>) is typed + /// like the computed value is, and a list syntax (e.g., <length>+) yields one + /// item per entry. Otherwise, e.g., with var(), it is a CssUnparsedValue. + /// + public static IReadOnlyList ReifyAll(String property, ICssValue? value, CssPropertyRegistration? registration) + { + if (registration is null || value is null) + { + return ReifyAll(property, value); + } + + value = registration.MatchDeclared(value) ?? value; + + if (value is CssTupleValue tuple && registration.Syntax.ListSeparator == " ") + { + return tuple.Items.Select(item => Reify(property, item)).ToArray(); + } + + return ReifyAll(property, value); + } + /// /// Reifies a single value of the given property. /// diff --git a/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs b/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs index 89dfd249..2b491195 100644 --- a/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs +++ b/src/AngleSharp.Css/TypedOm/CssTypedOmExtensions.cs @@ -1,6 +1,7 @@ namespace AngleSharp.Css.TypedOm { using AngleSharp.Css.Dom; + using AngleSharp.Dom; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -26,6 +27,22 @@ public static IStylePropertyMap GetStyleMap(this ICssStyleDeclaration declaratio return Maps.GetValue(declaration, m => new StylePropertyMap(m, null)); } + /// + /// Gets the (always same) typed view of the declarations, whose registered custom + /// properties are the ones of the given document. + /// + internal static IStylePropertyMap GetStyleMap(this ICssStyleDeclaration declaration, IDocument? document) + { + var map = declaration.GetStyleMap(); + + if (map is StylePropertyMapReadOnly typed && typed.Document is null) + { + typed.Document = document; + } + + return map; + } + /// /// Gets a read-only typed view of the given declarations, e.g., of a computed style. /// The entries are sorted by name, with the custom properties last. diff --git a/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs b/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs index 327b7132..34a2ca40 100644 --- a/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs +++ b/src/AngleSharp.Css/TypedOm/ElementComputedStyleMapExtensions.cs @@ -22,7 +22,7 @@ public static class ElementComputedStyleMapExtensions { var window = element.Owner?.DefaultView; var style = window?.GetComputedStyleOfScript(element); - return style is not null ? new StylePropertyMapReadOnly(style, element.Owner?.Context, true) : null; + return style is not null ? new StylePropertyMapReadOnly(style, element.Owner?.Context, true, element.Owner) : null; } } } diff --git a/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs b/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs index 26cfca5c..56207362 100644 --- a/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs +++ b/src/AngleSharp.Css/TypedOm/ElementStyleMapExtensions.cs @@ -20,6 +20,6 @@ public static class ElementStyleMapExtensions [DomName("attributeStyleMap")] [DomAccessor(Accessors.Getter)] public static IStylePropertyMap? GetAttributeStyleMap(this IElement element) => - element.GetStyle()?.GetStyleMap(); + element.GetStyle()?.GetStyleMap(element.Owner); } } diff --git a/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs b/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs index 88057748..3e8e1a03 100644 --- a/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs +++ b/src/AngleSharp.Css/TypedOm/StylePropertyMap.cs @@ -2,6 +2,7 @@ namespace AngleSharp.Css.TypedOm { using AngleSharp.Css.Dom; using AngleSharp.Css.Values; + using AngleSharp.Dom; using AngleSharp.Text; using System; using System.Linq; @@ -9,14 +10,15 @@ namespace AngleSharp.Css.TypedOm /// /// A writable view of style declarations as typed values. The typed values are /// serialized and validated by the converter of the property, i.e., the same way - /// as values set via the CSSOM. + /// as values set via the CSSOM. The values of a registered custom property also + /// have to match its syntax, which is list-valued for a syntax such as <length>#. /// sealed class StylePropertyMap : StylePropertyMapReadOnly, IStylePropertyMap { #region ctor - public StylePropertyMap(ICssStyleDeclaration declaration, IBrowsingContext? context) - : base(declaration, context, false) + public StylePropertyMap(ICssStyleDeclaration declaration, IBrowsingContext? context, IDocument? document = null) + : base(declaration, context, false, document) { } @@ -83,22 +85,27 @@ private void Update(String name, String[] texts, Boolean append) throw new ArgumentException("At least one value is required.", nameof(texts)); } - if (custom && (append || texts.Length > 1)) + // only a registered custom property with a list syntax (e.g., #) is list-valued + var registration = custom ? GetRegistration(name) : null; + var separator = custom ? registration?.Syntax.ListSeparator : ", "; + + if (separator is null && (append || texts.Length > 1)) { throw new ArgumentException($"The custom property '{name}' is not list-valued.", nameof(name)); } - var text = String.Join(", ", texts); + var text = String.Join(separator ?? String.Empty, texts); if (append) { var existing = Declaration.GetPropertyValue(name); - text = String.IsNullOrEmpty(existing) ? text : String.Concat(existing, ", ", text); + text = String.IsNullOrEmpty(existing) ? text : String.Concat(existing, separator, text); } - var property = TypedOmProperties.Parse(Context, name, text); + var property = TypedOmProperties.Parse(Context, name, text, registration); - if ((append || texts.Length > 1) && property.RawValue is not CssListValue && property.RawValue is not CssReferenceValue) + // the values of a registered list were matched against its syntax already + if (!custom && (append || texts.Length > 1) && property.RawValue is not CssListValue && property.RawValue is not CssReferenceValue) { throw new ArgumentException($"The property '{name}' is not list-valued.", nameof(name)); } diff --git a/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs b/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs index e1774915..0a9f31ec 100644 --- a/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs +++ b/src/AngleSharp.Css/TypedOm/StylePropertyMapReadOnly.cs @@ -1,6 +1,8 @@ namespace AngleSharp.Css.TypedOm { using AngleSharp.Css.Dom; + using AngleSharp.Css.Values; + using AngleSharp.Dom; using System; using System.Collections; using System.Collections.Generic; @@ -8,7 +10,9 @@ namespace AngleSharp.Css.TypedOm /// /// A view of style declarations as typed values. Nothing is copied: the values - /// are reified from the declarations whenever they are requested. + /// are reified from the declarations whenever they are requested. The values of + /// custom properties are typed according to their registration in the document, + /// which is looked up when they are requested, too. /// class StylePropertyMapReadOnly : IStylePropertyMapReadOnly { @@ -22,11 +26,12 @@ class StylePropertyMapReadOnly : IStylePropertyMapReadOnly #region ctor - public StylePropertyMapReadOnly(ICssStyleDeclaration declaration, IBrowsingContext? context, Boolean sorted) + public StylePropertyMapReadOnly(ICssStyleDeclaration declaration, IBrowsingContext? context, Boolean sorted, IDocument? document = null) { _declaration = declaration; _context = context ?? (declaration as CssStyleDeclaration)?.Context; _sorted = sorted; + Document = document; } #endregion @@ -37,7 +42,21 @@ public StylePropertyMapReadOnly(ICssStyleDeclaration declaration, IBrowsingConte protected IBrowsingContext? Context => _context; - public Int32 Size => GetNames().Count(name => GetAllCore(name).Count > 0); + /// + /// Gets or sets the document whose registered custom properties apply, which is + /// otherwise the one of the style sheet of the declarations' rule, or the active + /// document of the context. + /// + internal IDocument? Document { get; set; } + + public Int32 Size + { + get + { + var registry = new Lazy(GetRegistry); + return GetNames().Count(name => GetAllCore(name, registry).Count > 0); + } + } #endregion @@ -49,15 +68,18 @@ public StylePropertyMapReadOnly(ICssStyleDeclaration declaration, IBrowsingConte return values.Count > 0 ? values[0] : null; } - public IReadOnlyList GetAll(String property) => GetAllCore(Validate(property)); + public IReadOnlyList GetAll(String property) => + GetAllCore(Validate(property), new Lazy(GetRegistry)); public Boolean Has(String property) => !String.IsNullOrEmpty(_declaration.GetPropertyValue(Validate(property))); public IEnumerator>> GetEnumerator() { + var registry = new Lazy(GetRegistry); + foreach (var name in GetNames()) { - var values = GetAllCore(name); + var values = GetAllCore(name, registry); if (values.Count > 0) { @@ -79,7 +101,16 @@ protected String Validate(String property) return name; } - private IReadOnlyList GetAllCore(String name) + /// + /// Gets the registration of the custom property in effect for the declarations. + /// + protected CssPropertyRegistration? GetRegistration(String name) => + TypedOmProperties.IsCustom(name) ? GetRegistry()?.Get(name) : null; + + private CssPropertyRegistry? GetRegistry() => + TypedOmProperties.GetRegistry(Document ?? _declaration.Parent?.Owner?.OwnerNode?.Owner ?? _context?.Active); + + private IReadOnlyList GetAllCore(String name, Lazy registry) { // the text also covers used values, e.g., of a computed style var text = _declaration.GetPropertyValue(name); @@ -94,8 +125,11 @@ private IReadOnlyList GetAllCore(String name) property.RawValue : TryParse(name, text); + // the registry is only needed (and collected) for custom properties + var registration = TypedOmProperties.IsCustom(name) ? registry.Value?.Get(name) : null; + return value is not null ? - CssStyleValueReifier.ReifyAll(name, value) : + CssStyleValueReifier.ReifyAll(name, value, registration) : new CssStyleValue[] { new CssUnsupportedValue(name, text) }; } diff --git a/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs b/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs index d9d1d94e..50e740da 100644 --- a/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs +++ b/src/AngleSharp.Css/TypedOm/TypedOmProperties.cs @@ -1,6 +1,8 @@ namespace AngleSharp.Css.TypedOm { using AngleSharp.Css.Dom; + using AngleSharp.Css.Values; + using AngleSharp.Dom; using AngleSharp.Text; using System; @@ -38,10 +40,25 @@ public static DeclarationInfo GetInfo(IBrowsingContext? context, String name) return info; } + /// + /// Gets the registrations in effect for the document, if any. + /// + public static CssPropertyRegistry? GetRegistry(IDocument? document) => + document is not null ? CssPropertyRegistry.ForDocument(document) : null; + + /// + /// Gets the registration of the custom property in the document of the context. + /// + public static CssPropertyRegistration? GetRegistration(IBrowsingContext? context, String name) => + IsCustom(name) ? GetRegistry(context?.Active)?.Get(name) : null; + /// /// Parses the text for the given property, or throws (TypeError) if it is invalid. + /// The value of a registered custom property has to match its syntax, unless it is + /// a CSS-wide keyword or has references (e.g., var()), which are only resolved at + /// computed-value time. /// - public static CssProperty Parse(IBrowsingContext? context, String name, String text) + public static CssProperty Parse(IBrowsingContext? context, String name, String text, CssPropertyRegistration? registration = null) { name = Normalize(name); var info = GetInfo(context, name); @@ -50,12 +67,17 @@ public static CssProperty Parse(IBrowsingContext? context, String name, String t Value = text, }; - if (property.RawValue is null) + if (property.RawValue is null || !MatchesRegistration(registration, property.RawValue)) { throw new ArgumentException($"The value '{text}' is not valid for the property '{name}'.", nameof(text)); } return property; } + + private static Boolean MatchesRegistration(CssPropertyRegistration? registration, ICssValue value) => + registration is null || registration.IsUniversal || value is ICssSpecialValue || + CssPropertySyntax.IsCssWideKeyword(value.CssText.Trim()) || + CssPropertySyntax.HasReferences(value.CssText) || registration.Syntax.Match(value) is not null; } } diff --git a/src/AngleSharp.Css/Values/CssPropertyRegistration.cs b/src/AngleSharp.Css/Values/CssPropertyRegistration.cs index 10f011f9..d7fc5390 100644 --- a/src/AngleSharp.Css/Values/CssPropertyRegistration.cs +++ b/src/AngleSharp.Css/Values/CssPropertyRegistration.cs @@ -4,6 +4,7 @@ namespace AngleSharp.Css.Values using AngleSharp.Dom; using System; using System.Collections.Generic; + using System.Linq; using System.Runtime.CompilerServices; using System.Threading; @@ -11,14 +12,15 @@ namespace AngleSharp.Css.Values /// The registration of a custom property, e.g., by a valid @property rule. /// https://www.w3.org/TR/css-properties-values-api-1/#custom-property-registration /// - sealed class CssPropertyRegistration + sealed class CssPropertyRegistration : ICssPropertyRegistration { - public CssPropertyRegistration(String name, CssPropertySyntax syntax, Boolean inherits, ICssValue? initialValue) + public CssPropertyRegistration(String name, CssPropertySyntax syntax, Boolean inherits, ICssValue? initialValue, CssPropertyRegistrationOrigin origin = CssPropertyRegistrationOrigin.Rule) { Name = name; Syntax = syntax; Inherits = inherits; InitialValue = initialValue; + Origin = origin; } /// @@ -26,7 +28,7 @@ public CssPropertyRegistration(String name, CssPropertySyntax syntax, Boolean in /// which has to match the syntax and be computationally independent. /// /// The registration or null if the initial value is not valid. - public static CssPropertyRegistration? Create(String name, CssPropertySyntax syntax, Boolean inherits, String? initialText) + public static CssPropertyRegistration? Create(String name, CssPropertySyntax syntax, Boolean inherits, String? initialText, CssPropertyRegistrationOrigin origin = CssPropertyRegistrationOrigin.Rule) { var initial = default(ICssValue); @@ -45,7 +47,7 @@ public CssPropertyRegistration(String name, CssPropertySyntax syntax, Boolean in return null; } - return new CssPropertyRegistration(name, syntax, inherits, initial); + return new CssPropertyRegistration(name, syntax, inherits, initial, origin); } /// @@ -74,6 +76,46 @@ public static Boolean IsCustomPropertyName(String? name) => /// guaranteed-invalid value, for the universal syntax without an initial value. /// public ICssValue? InitialValue { get; } + + public CssPropertyRegistrationOrigin Origin { get; } + + public Boolean IsUniversal => Syntax.IsUniversal; + + public Boolean IsList => Syntax.ListSeparator is not null; + + String ICssPropertyRegistration.Syntax => Syntax.Text; + + String? ICssPropertyRegistration.InitialValue => InitialValue?.CssText; + + ICssValue? ICssPropertyRegistration.RawInitialValue => InitialValue; + + public ICssValue? Match(String cssText) + { + if (cssText is null) + throw new ArgumentNullException(nameof(cssText)); + + if (!IsUniversal && CssPropertySyntax.HasReferences(cssText)) + { + return null; + } + + return Syntax.Match(new CssAnyValue(cssText, isResolved: true)); + } + + /// + /// Matches a declared (not yet substituted) value against the syntax, which is only + /// possible without references, i.e., for a value that is no CssReferenceValue. + /// + /// The matched value, or null if it does not match or has references. + internal ICssValue? MatchDeclared(ICssValue value) + { + if (IsUniversal || value is not CssAnyValue || CssPropertySyntax.HasReferences(value.CssText)) + { + return null; + } + + return Syntax.Match(value); + } } /// @@ -82,6 +124,15 @@ public static Boolean IsCustomPropertyName(String? name) => /// sealed class CssPropertyRegistry { + /// + /// Gets the registrations in effect for the document: the ones of the valid @property + /// rules of its (effective) style sheets, which apply under the same conditions as the + /// style rules (e.g., of an enclosing @media rule), and the ones of script, which win. + /// The registrations reflect the current style sheets: they are kept until something + /// they depend on changes, i.e., the result must not be modified. + /// + public static CssPropertyRegistry ForDocument(IDocument document) => CssPropertyRegistryCache.Get(document); + private readonly Dictionary _registrations; public CssPropertyRegistry() diff --git a/src/AngleSharp.Css/Values/CssPropertyRegistryCache.cs b/src/AngleSharp.Css/Values/CssPropertyRegistryCache.cs new file mode 100644 index 00000000..9b5e1c14 --- /dev/null +++ b/src/AngleSharp.Css/Values/CssPropertyRegistryCache.cs @@ -0,0 +1,285 @@ +namespace AngleSharp.Css.Values +{ + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Threading; + + /// + /// Keeps the registrations in effect for a document (see CssPropertyRegistry.ForDocument) + /// until something they were collected from changes. Checking that costs a few reads, not + /// a walk over the DOM or the rules: + /// - the DOM (inserted or removed style elements, edited style text, changed attributes + /// such as media or disabled) by the mutation version of the document, + /// - the CSSOM (inserted or removed rules, changed @property descriptors) by a version + /// that these changes advance (see Invalidate), + /// - the style sheets of the style elements (e.g., a link that loaded), whether they are + /// disabled, the adopted and the default style sheets, and the registrations of script + /// by their references, + /// - the conditions (@media, @supports, and the media of a sheet) around @property rules, + /// which depend on the device, by evaluating them again. + /// + static class CssPropertyRegistryCache + { + #region Fields + + private static readonly ConditionalWeakTable Entries = new(); + private static Int64 _version; + + #endregion + + #region Methods + + /// + /// Marks the registrations of all documents as outdated, e.g., as a rule that may hold + /// a @property rule (but not a style rule) was inserted. + /// + public static void Invalidate() => Interlocked.Increment(ref _version); + + /// + /// Gets the registrations in effect for the document, which are only collected again + /// if something they depend on changed. The registry must not be modified. + /// + public static CssPropertyRegistry Get(IDocument document) + { + var context = document.Context; + var device = context?.GetService() ?? DefaultDevice; + var defaults = GetDefaultSheets(context); + var scripted = CssScriptPropertyRegistrations.Get(document); + + // the cache needs the mutation version, which only AngleSharp's own document has + if (document is not Document dom) + { + return Collect(document, device, defaults); + } + + var holder = Entries.GetValue(document, _ => new Holder()); + var entry = holder.Entry; + + if (entry is not null && entry.IsCurrent(dom, device, defaults, scripted)) + { + return entry.Registry; + } + + // read before collecting: a change made meanwhile makes the entry outdated + var version = Interlocked.Read(ref _version); + var mutationVersion = dom.MutationVersion; + var owners = document.GetDescendants().OfType().ToArray(); + var ownerSheets = Array.ConvertAll(owners, m => m.Sheet); + var adopted = document.GetAdoptedStyleSheets().ToArray(); + var registry = Collect(document, device, defaults); + var sheets = defaults.Concat(ownerSheets.OfType()).Concat(adopted); + holder.Entry = new Entry(version, mutationVersion, device, defaults, scripted, owners, ownerSheets, adopted, GetGates(sheets), registry); + return registry; + } + + #endregion + + #region Helpers + + private static readonly IRenderDevice DefaultDevice = new DefaultRenderDevice(); + + private static ICssStyleSheet[] GetDefaultSheets(IBrowsingContext? context) + { + var providers = context?.GetServices() ?? Enumerable.Empty(); + return providers.Select(m => m.Default).Where(m => m is not null).ToArray(); + } + + private static CssPropertyRegistry Collect(IDocument document, IRenderDevice device, ICssStyleSheet[] defaults) + { + var collection = new StyleCollection(defaults, document.GetEffectiveStyleSheets(), device, document: document); + return collection.GetRegistrations(); + } + + /// + /// Gets the conditions the @property rules of the sheets are under, exactly the ones + /// the style collection follows: the media of a sheet, @media, and @supports. + /// + private static Gate[] GetGates(IEnumerable sheets) + { + var gates = new List(); + + foreach (var sheet in sheets) + { + if (CollectGates(sheet.Rules, gates) && sheet.Media.Length > 0) + { + var media = sheet.Media; + gates.Add(new Gate(device => media.Validate(device))); + } + } + + return gates.ToArray(); + } + + /// True if the rules hold a @property rule, also within nested rules. + private static Boolean CollectGates(ICssRuleList rules, List gates) + { + var found = false; + + foreach (var rule in rules) + { + switch (rule) + { + case ICssPropertyRule: + found = true; + break; + case ICssMediaRule media when CollectGates(media.Rules, gates): + gates.Add(new Gate(device => media.IsValid(device))); + found = true; + break; + case ICssSupportsRule supports when CollectGates(supports.Rules, gates): + gates.Add(new Gate(device => supports.IsValid(device))); + found = true; + break; + case ICssLayerRule layer when !layer.IsStatement && CollectGates(layer.Rules, gates): + found = true; + break; + } + } + + return found; + } + + #endregion + + #region Entry + + private sealed class Holder + { + private Entry? _entry; + + public Entry? Entry + { + get => Volatile.Read(ref _entry); + set => Volatile.Write(ref _entry, value); + } + } + + private readonly struct Gate + { + private readonly Func _evaluate; + + public Gate(Func evaluate) + { + _evaluate = evaluate; + Result = null; + } + + private Gate(Func evaluate, Boolean result) + { + _evaluate = evaluate; + Result = result; + } + + public Boolean? Result { get; } + + public Gate Evaluate(IRenderDevice device) => new(_evaluate, _evaluate(device)); + + public Boolean IsUnchanged(IRenderDevice device) => _evaluate(device) == Result; + } + + private sealed class Entry + { + private readonly Int64 _version; + private readonly Int64 _mutationVersion; + private readonly IRenderDevice _device; + private readonly ICssStyleSheet[] _defaults; + private readonly CssPropertyRegistry? _scripted; + private readonly ILinkStyle[] _owners; + private readonly IStyleSheet?[] _ownerSheets; + private readonly Boolean[] _ownerDisabled; + private readonly ICssStyleSheet[] _adopted; + private readonly Boolean[] _adoptedDisabled; + private readonly Gate[] _gates; + + public Entry(Int64 version, Int64 mutationVersion, IRenderDevice device, ICssStyleSheet[] defaults, CssPropertyRegistry? scripted, + ILinkStyle[] owners, IStyleSheet?[] ownerSheets, ICssStyleSheet[] adopted, Gate[] gates, CssPropertyRegistry registry) + { + _version = version; + _mutationVersion = mutationVersion; + _device = device; + _defaults = defaults; + _scripted = scripted; + _owners = owners; + _ownerSheets = ownerSheets; + _ownerDisabled = Array.ConvertAll(ownerSheets, m => m?.IsDisabled ?? false); + _adopted = adopted; + _adoptedDisabled = Array.ConvertAll(adopted, m => m.IsDisabled); + _gates = Array.ConvertAll(gates, m => m.Evaluate(device)); + Registry = registry; + } + + public CssPropertyRegistry Registry { get; } + + public Boolean IsCurrent(Document document, IRenderDevice device, ICssStyleSheet[] defaults, CssPropertyRegistry? scripted) + { + if (_version != Interlocked.Read(ref CssPropertyRegistryCache._version) || + _mutationVersion != document.MutationVersion || + !ReferenceEquals(_device, device) || + !ReferenceEquals(_scripted, scripted) || + !SameSheets(_defaults, defaults)) + { + return false; + } + + for (var i = 0; i < _owners.Length; i++) + { + var sheet = _owners[i].Sheet; + + if (!ReferenceEquals(sheet, _ownerSheets[i]) || (sheet?.IsDisabled ?? false) != _ownerDisabled[i]) + { + return false; + } + } + + var adopted = document.GetAdoptedStyleSheets(); + + if (adopted.Count != _adopted.Length) + { + return false; + } + + for (var i = 0; i < _adopted.Length; i++) + { + if (!ReferenceEquals(adopted[i], _adopted[i]) || _adopted[i].IsDisabled != _adoptedDisabled[i]) + { + return false; + } + } + + foreach (var gate in _gates) + { + if (!gate.IsUnchanged(device)) + { + return false; + } + } + + return true; + } + + private static Boolean SameSheets(ICssStyleSheet[] a, ICssStyleSheet[] b) + { + if (a.Length != b.Length) + { + return false; + } + + for (var i = 0; i < a.Length; i++) + { + if (!ReferenceEquals(a[i], b[i])) + { + return false; + } + } + + return true; + } + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/Values/CssPropertySyntax.cs b/src/AngleSharp.Css/Values/CssPropertySyntax.cs index 67cb5a72..585c1dbc 100644 --- a/src/AngleSharp.Css/Values/CssPropertySyntax.cs +++ b/src/AngleSharp.Css/Values/CssPropertySyntax.cs @@ -69,6 +69,38 @@ private CssPropertySyntax(String text, Component[] components) /// public Boolean IsUniversal => _components.Length == 0; + /// + /// Gets the separator of the items if the syntax is list-valued, i.e., ", " if all + /// components are multiplied by # and " " if all are multiplied by +, otherwise null. + /// + public String? ListSeparator + { + get + { + if (_components.Length == 0) + { + return null; + } + + var multiplier = _components[0].Multiplier; + + for (var i = 1; i < _components.Length; i++) + { + if (_components[i].Multiplier != multiplier) + { + return null; + } + } + + return multiplier switch + { + Symbols.Num => ", ", + Symbols.Plus => " ", + _ => null, + }; + } + } + #endregion #region Parsing @@ -131,10 +163,10 @@ private CssPropertySyntax(String text, Component[] components) return null; } - return new Component(Multiply(converter, multiplier)); + return new Component(Multiply(converter, multiplier), multiplier); } - return IsCustomIdent(name) ? new Component(Multiply(new IdentConverter(name), multiplier)) : null; + return IsCustomIdent(name) ? new Component(Multiply(new IdentConverter(name), multiplier), multiplier) : null; } private static IValueConverter Multiply(IValueConverter converter, Char? multiplier) => multiplier switch @@ -151,7 +183,10 @@ private static Boolean IsCustomIdent(String text) return ident is not null && ident.Length == text.Length && source.IsDone && !IsCssWideKeyword(ident); } - private static Boolean IsCssWideKeyword(String ident) => + /// + /// Checks if the identifier is a CSS-wide keyword, e.g., initial. + /// + public static Boolean IsCssWideKeyword(String ident) => ident.Isi(CssKeywords.Initial) || ident.Isi(CssKeywords.Inherit) || ident.Isi(CssKeywords.Unset) || ident.Isi(CssKeywords.Revert) || ident.Isi(CssKeywords.RevertLayer) || ident.Isi(CssKeywords.Default); @@ -196,7 +231,15 @@ private static Boolean IsCssWideKeyword(String ident) => /// refer to custom properties or to the font of the element or the root. /// https://www.w3.org/TR/css-properties-values-api-1/#computationally-independent /// - public static Boolean IsComputationallyIndependent(String text) + public static Boolean IsComputationallyIndependent(String text) => !Contains(text, true); + + /// + /// Checks if the value refers to other values, i.e., contains var(), env(), or attr(), + /// which are only substituted at computed-value time. + /// + public static Boolean HasReferences(String text) => Contains(text, false); + + private static Boolean Contains(String text, Boolean dependentUnits) { var tokenizer = new CssTokenizer(new TextSource(text)); @@ -207,11 +250,11 @@ public static Boolean IsComputationallyIndependent(String text) switch (token.Type) { case CssTokenType.EndOfFile: - return true; - case CssTokenType.Function when IsReference(token.Data): - return false; - case CssTokenType.Dimension when DependentUnits.Contains(token.Data.CssUnit(out _)): return false; + case CssTokenType.Function when IsReference(token.Data): + return true; + case CssTokenType.Dimension when dependentUnits && DependentUnits.Contains(token.Data.CssUnit(out _)): + return true; } } } @@ -228,12 +271,15 @@ private static Boolean IsReference(String name) private sealed class Component { - public Component(IValueConverter converter) + public Component(IValueConverter converter, Char? multiplier) { Converter = converter; + Multiplier = multiplier; } public IValueConverter Converter { get; } + + public Char? Multiplier { get; } } /// From 926f5b98c12ee7e4783af8b00bcd6670dc275edf Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 16:12:13 +0100 Subject: [PATCH 04/12] Added CSS paint API --- AGENTS.md | 4 + CHANGELOG.md | 15 +- docs/README.md | 3 +- docs/general/06-Provided-Services.md | 7 + docs/general/10-Painting-API.md | 193 +++++ .../Painting/PaintFunctionTests.cs | 146 ++++ .../Painting/PaintImageTests.cs | 316 ++++++++ .../Painting/PaintWorkletTests.cs | 165 ++++ .../Painting/RecordingContextTests.cs | 394 ++++++++++ src/AngleSharp.Css/Constants/FunctionNames.cs | 5 + src/AngleSharp.Css/Dom/CssHelpers.Paint.cs | 45 ++ src/AngleSharp.Css/Painting/CanvasColor.cs | 50 ++ src/AngleSharp.Css/Painting/CanvasEnums.cs | 91 +++ src/AngleSharp.Css/Painting/CanvasGradient.cs | 97 +++ .../Painting/CanvasPathBuilder.cs | 155 ++++ src/AngleSharp.Css/Painting/CanvasPattern.cs | 30 + src/AngleSharp.Css/Painting/ICanvasPath.cs | 81 ++ .../Painting/IPaintDefinition.cs | 47 ++ .../Painting/IPaintRenderingContext2D.cs | 345 +++++++++ .../Painting/IPaintRenderingContextFactory.cs | 25 + .../Painting/IPaintWorkletModuleLoader.cs | 29 + src/AngleSharp.Css/Painting/PaintCommand.cs | 50 ++ .../Painting/PaintDefinition.cs | 46 ++ src/AngleSharp.Css/Painting/PaintImage.cs | 47 ++ .../Painting/PaintImageExtensions.cs | 227 ++++++ .../Painting/PaintInputPropertyMap.cs | 55 ++ src/AngleSharp.Css/Painting/PaintMatrix.cs | 84 +++ .../PaintRenderingContext2DSettings.cs | 20 + src/AngleSharp.Css/Painting/PaintSize.cs | 44 ++ src/AngleSharp.Css/Painting/PaintWorklet.cs | 262 +++++++ .../Painting/PaintWorkletGlobalScope.cs | 53 ++ src/AngleSharp.Css/Painting/Path2D.cs | 119 +++ src/AngleSharp.Css/Painting/PathGeometry.cs | 394 ++++++++++ .../RecordingPaintRenderingContext2D.cs | 708 ++++++++++++++++++ .../Parser/Micro/CompoundParser.cs | 125 +++- src/AngleSharp.Css/ValueConverters.cs | 1 + .../Values/CssPropertySyntax.cs | 2 +- .../Values/Functions/CssPaintValue.cs | 103 +++ 38 files changed, 4572 insertions(+), 11 deletions(-) create mode 100644 docs/general/10-Painting-API.md create mode 100644 src/AngleSharp.Css.Tests/Painting/PaintFunctionTests.cs create mode 100644 src/AngleSharp.Css.Tests/Painting/PaintImageTests.cs create mode 100644 src/AngleSharp.Css.Tests/Painting/PaintWorkletTests.cs create mode 100644 src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs create mode 100644 src/AngleSharp.Css/Dom/CssHelpers.Paint.cs create mode 100644 src/AngleSharp.Css/Painting/CanvasColor.cs create mode 100644 src/AngleSharp.Css/Painting/CanvasEnums.cs create mode 100644 src/AngleSharp.Css/Painting/CanvasGradient.cs create mode 100644 src/AngleSharp.Css/Painting/CanvasPathBuilder.cs create mode 100644 src/AngleSharp.Css/Painting/CanvasPattern.cs create mode 100644 src/AngleSharp.Css/Painting/ICanvasPath.cs create mode 100644 src/AngleSharp.Css/Painting/IPaintDefinition.cs create mode 100644 src/AngleSharp.Css/Painting/IPaintRenderingContext2D.cs create mode 100644 src/AngleSharp.Css/Painting/IPaintRenderingContextFactory.cs create mode 100644 src/AngleSharp.Css/Painting/IPaintWorkletModuleLoader.cs create mode 100644 src/AngleSharp.Css/Painting/PaintCommand.cs create mode 100644 src/AngleSharp.Css/Painting/PaintDefinition.cs create mode 100644 src/AngleSharp.Css/Painting/PaintImage.cs create mode 100644 src/AngleSharp.Css/Painting/PaintImageExtensions.cs create mode 100644 src/AngleSharp.Css/Painting/PaintInputPropertyMap.cs create mode 100644 src/AngleSharp.Css/Painting/PaintMatrix.cs create mode 100644 src/AngleSharp.Css/Painting/PaintRenderingContext2DSettings.cs create mode 100644 src/AngleSharp.Css/Painting/PaintSize.cs create mode 100644 src/AngleSharp.Css/Painting/PaintWorklet.cs create mode 100644 src/AngleSharp.Css/Painting/PaintWorkletGlobalScope.cs create mode 100644 src/AngleSharp.Css/Painting/Path2D.cs create mode 100644 src/AngleSharp.Css/Painting/PathGeometry.cs create mode 100644 src/AngleSharp.Css/Painting/RecordingPaintRenderingContext2D.cs create mode 100644 src/AngleSharp.Css/Values/Functions/CssPaintValue.cs diff --git a/AGENTS.md b/AGENTS.md index 2f06d9ee..29170523 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,6 +80,10 @@ Notes: - `src/AngleSharp.Css/RenderTree` - Render tree construction and render node/value computation. +- `src/AngleSharp.Css/Painting` + - CSS Painting API: the paint worklet registry, paint definitions, the canvas-like rendering context abstractions, and the default recording context. + - Scripting engines and renderers plug in through `IPaintWorkletModuleLoader` and `IPaintRenderingContextFactory`; nothing here may depend on a script engine. + - `src/AngleSharp.Css/FeatureValidators` - Validators used for media feature / supports-style checks. diff --git a/CHANGELOG.md b/CHANGELOG.md index 89da6c8d..13adba26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,13 @@ # 1.5.0 -Released on tbd. - -- Added support for registered custom properties via `@property` (#274): the rule validates its descriptors (`syntax`, `inherits`, `initial-value`) and exposes them on `ICssPropertyRule` (`Syntax`, `Inherits`, `InitialValue`, `IsValid`), and a valid registration makes the custom property match its syntax (otherwise it is invalid at computed-value time), have its initial value, be computed (e.g., `2em` to `32px`), and only be inherited if registered so -- Added `CSS.registerProperty()` (`RegisterProperty` on `CssHelpers` for a window or a document, with a `PropertyDefinition`), which registers a custom property for the document like `@property` does and wins over `@property` rules of the same name; an invalid definition is a `SyntaxError`, registering a name twice an `InvalidModificationError` -- Added a common representation of registered custom properties (#275), `ICssPropertyRegistration` (`Name`, `Syntax`, `Inherits`, `InitialValue`, `RawInitialValue`, `IsList`, `Origin`, `Match`), shared by `@property` rules and `CSS.registerProperty()`: `GetRegisteredProperties()` and `GetRegisteredProperty(name)` give the registrations in effect for a document, `GetRegistration()` the one of a `@property` rule; the registrations of a document are kept until the DOM, the rules, the style sheets, or the conditions around `@property` rules change -- Added typing registered custom properties in the Typed OM according to their syntax (#275): declared values in `attributeStyleMap` and `styleMap` (e.g., a `CssUnitValue` of `2em` for ``), one value per item for a list syntax (`#`, `+`), and `CssStyleValue.Parse`; `Set` and `Append` reject values not matching the syntax and are only list-valued for a list syntax -- Added the CSS Typed OM (#276) in the `AngleSharp.Css.TypedOm` namespace: typed values (`CssUnitValue`, `CssKeywordValue`, `CssUnparsedValue`, the math values such as `CssMathSum`, `CssTransformValue`, `CssPositionValue`, `CssImageValue`) with unit-aware arithmetic and conversions, the `CSS.px()`-style factories on `CssHelpers`, and style property maps over declared (`attributeStyleMap`, `styleMap` of a rule) and computed (`computedStyleMap()`) styles, which read from and write to the existing declarations +Released on Wednesday, November 18. + +- Added the CSS Painting API with the `paint()` image function (#277) +- Added support for registered custom properties via `@property` (#274) +- Added `CSS.registerProperty()` +- Added a common representation of registered custom properties (#275) +- Added typing registered custom properties in the Typed OM according to their syntax (#275) +- Added the CSS Typed OM in the `AngleSharp.Css.TypedOm` namespace (#276) # 1.4.2 diff --git a/docs/README.md b/docs/README.md index bc95429d..7a9feb48 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ We have more detailed information regarding the following subjects: - [Supported At-Rules](general/07-Supported-At-Rules.md) - [Supported Declarations](general/08-Supported-Declarations.md) - [Typed OM](general/09-Typed-OM.md) +- [Painting API](general/10-Painting-API.md) ## Tutorials @@ -31,7 +32,7 @@ If you are new to AngleSharp.Css, this order gives a practical ramp-up: 4. [CSSOM](general/03-CSSOM.md) and [Core Interfaces](general/04-Core-Interfaces.md) once you need a deeper model understanding. 5. [Supported At-Rules](general/07-Supported-At-Rules.md) and [Supported Declarations](general/08-Supported-Declarations.md) when checking implementation coverage and constraints. 6. [Value Model](general/02-Values.md) and [Render Tree Examples](tutorials/03-Render-Tree.md) for style computation workflows. -7. [Extensibility](general/05-Extensibility.md) and [Provided Services](general/06-Provided-Services.md) for custom integrations. +7. [Extensibility](general/05-Extensibility.md) and [Provided Services](general/06-Provided-Services.md) for custom integrations, and the [Painting API](general/10-Painting-API.md) for drawing `paint()` images with your own painters or scripting engine. 8. [FAQ](tutorials/04-Questions.md) for common pitfalls and output customization. ## What You Can Do With AngleSharp.Css diff --git a/docs/general/06-Provided-Services.md b/docs/general/06-Provided-Services.md index d1ba3e60..f62a2d1d 100644 --- a/docs/general/06-Provided-Services.md +++ b/docs/general/06-Provided-Services.md @@ -52,6 +52,13 @@ This is the bridge that enables stylesheet loading from DOM resources. - render-tree generation (`window.Render(...)`), - media query feature validation. +## Optional Painting Services + +`WithCss()` registers nothing for the [Painting API](10-Painting-API.md); the following services can be added to the configuration with `With(...)`: + +- `IPaintWorkletModuleLoader` runs the modules given to `CSS.paintWorklet.addModule()`, e.g., with a scripting engine. Without it, `AddModule` fails with a `NotSupportedError`. +- `IPaintRenderingContextFactory` creates the rendering contexts paint definitions draw with, e.g., into a bitmap. Without it, the operations are recorded by a `RecordingPaintRenderingContext2D`. + ## Practical Checks ```cs diff --git a/docs/general/10-Painting-API.md b/docs/general/10-Painting-API.md new file mode 100644 index 00000000..cbf2fac8 --- /dev/null +++ b/docs/general/10-Painting-API.md @@ -0,0 +1,193 @@ +--- +title: "Painting API" +section: "AngleSharp.Css" +--- +# Painting API + +AngleSharp.Css implements the [CSS Painting API Level 1](https://www.w3.org/TR/css-paint-api-1/) in the `AngleSharp.Css.Painting` namespace. A *paint definition*, registered under a name, draws the images of the `paint()` functions that use this name, e.g., a background: + +```css +.element { + --stripe-color: tomato; + background-image: paint(stripes, 8px); +} +``` + +The API is split into three parts, none of which needs a scripting engine: + +1. **CSS** - `paint()` is parsed, kept in the value model, computed, and serialized, whether a paint definition exists or not. +2. **Registry and drawing** - the paint worklet of a document holds the paint definitions and draws the images for elements. +3. **Extension points** - interfaces that a scripting engine (e.g., AngleSharp.Js) or an application implements to run paint worklet modules or to draw into a real bitmap. + +## The `paint()` Function + +`paint( , ? )` is an ``, so it is accepted wherever images are: `background-image`, `background`, `border-image-source`, `border-image`, `mask-image`, `list-style-image`, `image-set()`, and custom properties registered with the syntax ``. + +```cs +var property = style.GetProperty("background-image"); +var paint = property.RawValue.GetPaintValues().Single(); // CssPaintValue + +paint.PainterName; // "stripes" +paint.Arguments; // [8px], each one as written (split at the top-level commas) +paint.CssText; // "paint(stripes, 8px)" +``` + +- The arguments are kept as written, since only the paint definition knows their syntax (its `InputArguments`). `var()` in the arguments is substituted like anywhere else. +- The computed value is as specified. +- In the Typed OM, `paint()` is a `CssImageValue`. +- `GetPaintValues()` finds the `paint()` functions in any value, e.g., in the layers of a `background-image` or the options of an `image-set()`. + +Parsing never depends on a paint definition: a `paint()` with an unknown name is a valid value, it is just drawn as an invalid image (i.e., transparent). + +## Registering Paint Definitions + +The paint worklet of a document (`CSS.paintWorklet`) is `window.GetPaintWorklet()` or `document.GetPaintWorklet()`. A paint definition implements `IPaintDefinition`, or uses `PaintDefinition` with a callback: + +```cs +using AngleSharp.Css.Dom; +using AngleSharp.Css.Painting; +using AngleSharp.Css.TypedOm; + +var worklet = document.DefaultView.GetPaintWorklet(); + +worklet.RegisterPaint("stripes", new PaintDefinition((ctx, size, properties, arguments) => +{ + var width = ((CssUnitValue)arguments[0]).Value; + ctx.FillStyle = properties.Get("--stripe-color")?.ToString() ?? "black"; + + for (var x = 0.0; x < size.Width; x += 2 * width) + { + ctx.FillRect(x, 0, width, size.Height); + } +}) +{ + InputProperties = new[] { "--stripe-color" }, + InputArguments = new[] { "" }, + ContextOptions = new PaintRenderingContext2DSettings { Alpha = true }, +}); +``` + +| Member | Meaning | +|--------|---------| +| `InputProperties` | The properties of the element given to `Paint` (standard or custom). Unknown properties are ignored. Read once at registration. | +| `InputArguments` | The syntax of each argument (as for `@property`, e.g., ``, `+`, `*`). Without any, the arguments are given as `CssUnparsedValue`. Read once at registration. | +| `ContextOptions` | `Alpha = false` asks for an opaque image. | +| `Paint(ctx, size, properties, arguments)` | Draws the image. `properties` is a `IStylePropertyMapReadOnly` of the computed values of the input properties (typed according to their registration, e.g., a `--radius` registered as `` is a `CssUnitValue` in pixels); `arguments` are typed by `InputArguments`. | + +`RegisterPaint` follows the specification: an empty name or an invalid syntax of an input argument is a `TypeError` (`ArgumentException`), registering a name twice is an `InvalidModificationError` (`DomException`). The same method is on `worklet.GlobalScope`, which is what a module sees as `registerPaint()`. `worklet.Get(name)`, `Contains(name)`, `Names`, and `GetInputProperties(name)` tell what has been registered. + +Each document has its own paint worklet, which only lives as long as the document. + +## Drawing Paint Images + +AngleSharp.Css does no layout, so whoever draws the image (e.g., a renderer that knows the box of the element) gives its size in CSS pixels: + +```cs +var element = document.QuerySelector(".element"); + +// all paint() functions in the computed value of the property +IReadOnlyList images = element.DrawPaintImages("background-image", new PaintSize(200, 100)); + +// a single paint() function, optionally with a known computed style +PaintImage? image = element.DrawPaintImage(paint, new PaintSize(200, 100)); + +// or for a node of the render tree, using its computed style +var images2 = renderNode.DrawPaintImages("background-image", new PaintSize(200, 100)); +``` + +A `PaintImage` gives the `Source` (`CssPaintValue`), `Name`, `Size`, `DevicePixelRatio`, and the `Context` that was drawn with, which holds the output. + +The image is invalid, i.e., `null`, if: + +- no paint definition has been registered under its name (a definition registered later is used by later drawing), +- the arguments do not match `InputArguments` (a different count or a value not matching its syntax), +- `Paint` throws. + +An invalid image is meant to be drawn as transparent black. None of these cases affects parsing or computing styles. + +## Rendering Contexts + +`Paint` draws with an `IPaintRenderingContext2D`, the subset of the canvas 2D context the specification allows: state (`Save`, `Restore`, `Reset`), transforms, compositing, image smoothing, fill and stroke styles (colors, `CanvasGradient`, `CanvasPattern`), shadows, rectangles, paths (`ICanvasPath`, `Path2D`), clipping, hit testing (`IsPointInPath`, `IsPointInStroke`), `DrawImage` (of `CssImageValue`s), and line styles. There is no text and no access to pixels. + +### The Default: Recording + +Without further configuration, the context is a `RecordingPaintRenderingContext2D`, which draws nothing but records the operations as `PaintCommand`s, a display list any renderer can replay: + +```cs +var recording = (RecordingPaintRenderingContext2D)image.Context; + +foreach (var command in recording.Commands) +{ + // e.g., fillStyle("#ff6347"), fillRect(0, 0, 8, 100), ... + Console.WriteLine(command); + // command.Name: "fillRect", command.Arguments: [0.0, 0.0, 8.0, 100.0] +} +``` + +- Commands are named like the canvas operations (a setter is recorded under the name of its property, e.g., `fillStyle`), with validated and normalized arguments: colors are serialized (`#rrggbb` or `rgba(r, g, b, a)`), and calls the canvas API ignores (e.g., non-finite coordinates, a negative `lineWidth`, an unknown composite operation) are not recorded. +- The drawing state works as in a canvas, so reading `FillStyle` gives what has been set, `Save` / `Restore` apply, and `Reset` clears the recording. +- Paths drawn with `Fill(path)`, `Stroke(path)`, or `Clip(path)` are recorded as snapshots, and gradients are recorded by reference. +- Hit testing works on the flattened geometry of the path (curves and arcs are approximated). `IsPointInStroke` considers the line width but not joins, caps, or dashes. The SVG path data of `new Path2D("M 0 0 ...")` is kept as a command named `d` and not used for hit testing. +- Coordinates are CSS pixels, i.e., the `DevicePixelRatio` is left to the renderer replaying the commands. + +### Custom Rendering Contexts + +To draw into a real bitmap (e.g., with SkiaSharp or System.Drawing), register an `IPaintRenderingContextFactory`: + +```cs +public sealed class SkiaPaintContextFactory : IPaintRenderingContextFactory +{ + public IPaintRenderingContext2D Create(PaintSize size, Double devicePixelRatio, PaintRenderingContext2DSettings settings) => + new SkiaPaintRenderingContext(size, devicePixelRatio, settings.Alpha); +} + +var config = Configuration.Default + .WithCss() + .With(new SkiaPaintContextFactory()); +``` + +A new context is created for each image, and `PaintImage.Context` is that context, so the bitmap is obtained by casting it back. The device pixel ratio is the `Resolution` of the `IRenderDevice` divided by 96 (or 1 without a render device), as is `devicePixelRatio` of the global scope. + +## Integrating a Scripting Engine + +In a browser, paint definitions are classes of a script module loaded with `CSS.paintWorklet.addModule(url)`. AngleSharp.Css does not depend on any scripting engine; instead, `AddModule` hands the module to the `IPaintWorkletModuleLoader` of the configuration: + +```cs +public interface IPaintWorkletModuleLoader +{ + Task LoadAsync(PaintWorkletGlobalScope scope, Url moduleUrl, CancellationToken cancellationToken); +} +``` + +Without a loader, `AddModule` fails with a `NotSupportedError` (`DomException`), while paint definitions can still be registered directly. A loader, e.g., one provided by AngleSharp.Js, would: + +1. Fetch the module (`moduleUrl` is already resolved against the base URL of the document; `scope.Document.Context` gives the browsing context to load it with). +2. Run it in a new script global that exposes `registerPaint(name, class)` and `devicePixelRatio` of the `PaintWorkletGlobalScope` (both carry `[DomName]` attributes for that purpose). +3. For each `registerPaint(name, class)` call, read the static `inputProperties`, `inputArguments`, and `contextOptions` of the class, and register an `IPaintDefinition` adapter with `scope.RegisterPaint(name, adapter)`. Its `Paint` constructs (or reuses) an instance of the class and calls its `paint(ctx, size, properties, args)` method, passing the .NET objects, which are annotated with `[DomName]` (`PaintRenderingContext2D`, `PaintSize`, `StylePropertyMapReadOnly`, `CSSStyleValue`, `Path2D`, `CanvasGradient`, ...). +4. Complete the task once the module has run, or fail it, e.g., for a syntax error of the module. + +```cs +var config = Configuration.Default + .WithCss() + .With(new MyScriptPaintWorkletLoader()); + +await document.DefaultView.GetPaintWorklet().AddModule("painters/stripes.js"); +``` + +Exceptions thrown by a paint definition while drawing make the image invalid, which is how errors of script painters are expected to surface, too. + +## Mapping to the Specification + +| Specification | AngleSharp.Css | +|---------------|----------------| +| `paint()` | `CssPaintValue` (`PainterName`, `Arguments`) | +| `CSS.paintWorklet` | `window.GetPaintWorklet()` / `document.GetPaintWorklet()` (`PaintWorklet`) | +| `paintWorklet.addModule(url)` | `PaintWorklet.AddModule(url)`, run by `IPaintWorkletModuleLoader` | +| `PaintWorkletGlobalScope` | `PaintWorkletGlobalScope` (`RegisterPaint`, `DevicePixelRatio`) | +| paint definition (class) | `IPaintDefinition` / `PaintDefinition` | +| `PaintSize` | `PaintSize` | +| `PaintRenderingContext2D` | `IPaintRenderingContext2D`, by default `RecordingPaintRenderingContext2D` | +| `PaintRenderingContext2DSettings` | `PaintRenderingContext2DSettings` | +| draw a paint image | `DrawPaintImage` / `DrawPaintImages` (`PaintImage`, `null` for an invalid image) | + +Not supported: invalidating and repainting (the caller draws when it needs an image), several global scopes per worklet, and `getTransform()` / `DOMMatrix` arguments of the canvas API. diff --git a/src/AngleSharp.Css.Tests/Painting/PaintFunctionTests.cs b/src/AngleSharp.Css.Tests/Painting/PaintFunctionTests.cs new file mode 100644 index 00000000..46b0aa4f --- /dev/null +++ b/src/AngleSharp.Css.Tests/Painting/PaintFunctionTests.cs @@ -0,0 +1,146 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Painting +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Painting; + using AngleSharp.Css.TypedOm; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Linq; + using static CssConstructionFunctions; + + /// + /// Parsing and serializing the paint() function (CSS Painting API 1, 2), which works + /// without any paint definition or scripting engine. + /// + [TestFixture] + public class PaintFunctionTests + { + [TestCase("background-image: paint(checkerboard)", "paint(checkerboard)")] + [TestCase("background-image: PAINT( checkerboard )", "paint(checkerboard)")] + [TestCase("background-image: paint(checkerboard, 10px)", "paint(checkerboard, 10px)")] + [TestCase("background-image: paint(checkerboard,10px,red)", "paint(checkerboard, 10px, red)")] + [TestCase("background-image: paint(x, 1px solid red, \"a, b\")", "paint(x, 1px solid red, \"a, b\")")] + [TestCase("background-image: paint(x, calc(1px + 2px), rgb(0, 0, 0))", "paint(x, calc(1px + 2px), rgb(0, 0, 0))")] + [TestCase("background-image: paint(x, [a, b], f(c, d))", "paint(x, [a, b], f(c, d))")] + [TestCase("background-image: paint(x, a /* , b */)", "paint(x, a /* , b */)")] + [TestCase("background-image: paint(a), url(b.png), paint(c, 1)", "paint(a), url(\"b.png\"), paint(c, 1)")] + [TestCase("background-image: image-set(paint(a) 1x, \"b.png\" 2x)", "image-set(paint(a) 1x, \"b.png\" 2x)")] + [TestCase("border-image-source: paint(border)", "paint(border)")] + [TestCase("mask-image: paint(mask, 2)", "paint(mask, 2)")] + [TestCase("list-style-image: paint(bullet)", "paint(bullet)")] + public void PaintFunctionIsParsedAndSerialized(String declaration, String expected) + { + var property = ParseDeclaration(declaration); + Assert.IsTrue(property.HasValue, declaration); + Assert.AreEqual(expected, property.Value); + } + + [TestCase("background-image: paint()")] + [TestCase("background-image: paint(10px)")] + [TestCase("background-image: paint(\"name\")")] + [TestCase("background-image: paint(x,)")] + [TestCase("background-image: paint(x, )")] + [TestCase("background-image: paint(x, a,, b)")] + [TestCase("background-image: paint(x, a, )")] + [TestCase("background-image: paint(x y)")] + [TestCase("background-image: paint(x, a])")] + [TestCase("background-image: paint(x, (a)")] + [TestCase("background-image: paint(x")] + [TestCase("background-image: paint(x) red")] + public void InvalidPaintFunctionIsDropped(String declaration) + { + var property = ParseDeclaration(declaration); + Assert.IsFalse(property.HasValue, declaration); + } + + [Test] + public void PaintFunctionKeepsTheNameAndTheArguments() + { + var property = ParseDeclaration("background-image: paint(ring, 2px, \"a, b\", f(1, 2))"); + var paint = property.RawValue.GetPaintValues().Single(); + + Assert.AreEqual("paint", paint.Name); + Assert.AreEqual("ring", paint.PainterName); + CollectionAssert.AreEqual(new[] { "2px", "\"a, b\"", "f(1, 2)" }, paint.Arguments.Select(m => m.CssText).ToArray()); + } + + [Test] + public void PaintFunctionsAreEqualIfTheyAreWrittenAlike() + { + var a = new CssPaintValue("x", new ICssValue[] { new CssAnyValue("1px") }); + var b = ParseDeclaration("background-image: paint(x, 1px)").RawValue.GetPaintValues().Single(); + var c = new CssPaintValue("x", new ICssValue[] { new CssAnyValue("2px") }); + + Assert.IsTrue(a.Equals(b)); + Assert.IsFalse(a.Equals(c)); + } + + [Test] + public void BackgroundShorthandWithPaintFunction() + { + var style = ParseDeclarations("background: paint(stripes, 4px) no-repeat center / cover, red"); + + Assert.AreEqual("paint(stripes, 4px), none", style.GetPropertyValue("background-image")); + Assert.AreEqual("paint(stripes, 4px) center / cover no-repeat, rgba(255, 0, 0, 1)", style.GetPropertyValue("background")); + } + + [Test] + public void BorderImageShorthandWithPaintFunction() + { + var style = ParseDeclarations("border-image: paint(frame) 30 round"); + Assert.AreEqual("paint(frame)", style.GetPropertyValue("border-image-source")); + } + + [Test] + public void PaintFunctionWithVariableInArguments() + { + var document = ParseDocument("
"); + var style = document.GetElementById("target").ComputeCurrentStyle(); + + Assert.AreEqual("paint(dots, 8px)", style.GetPropertyValue("background-image")); + } + + [Test] + public void PaintFunctionIsComputedAsSpecified() + { + var document = ParseDocument("
"); + var style = document.GetElementById("target").ComputeCurrentStyle(); + + Assert.AreEqual("paint(dots, 2em)", style.GetPropertyValue("background-image")); + } + + [Test] + public void PaintFunctionMatchesImageSyntaxOfRegisteredProperty() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--img", Syntax = "", Inherits = false, InitialValue = "url(a.png)" }); + var style = document.GetElementById("target").ComputeCurrentStyle(); + + Assert.AreEqual("paint(x, 1)", style.GetPropertyValue("--img")); + } + + [Test] + public void PaintFunctionIsReifiedAsImageValue() + { + var document = ParseDocument("
"); + var map = document.GetElementById("target").GetAttributeStyleMap(); + var value = map.Get("background-image"); + + Assert.IsInstanceOf(value); + Assert.AreEqual("paint(x, 1px)", value.ToString()); + } + + [Test] + public void ElementWithUnregisteredPainterIsStillStyled() + { + var document = ParseDocument("
"); + var style = document.GetElementById("target").ComputeCurrentStyle(); + + Assert.AreEqual("paint(missing)", style.GetPropertyValue("background-image")); + Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetPropertyValue("color")); + } + } +} diff --git a/src/AngleSharp.Css.Tests/Painting/PaintImageTests.cs b/src/AngleSharp.Css.Tests/Painting/PaintImageTests.cs new file mode 100644 index 00000000..64b13aa2 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Painting/PaintImageTests.cs @@ -0,0 +1,316 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Painting +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Painting; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Collections.Generic; + using System.Linq; + using static CssConstructionFunctions; + + /// + /// Drawing the images of paint() functions with registered paint definitions + /// (CSS Painting API 6). + /// + [TestFixture] + public class PaintImageTests + { + private static readonly PaintSize Size = new(100, 50); + + private static RecordingPaintRenderingContext2D Draw(PaintImage image) => + (RecordingPaintRenderingContext2D)image.Context; + + [Test] + public void RegisteredPainterDrawsTheImage() + { + var document = ParseDocument("
"); + document.GetPaintWorklet().RegisterPaint("box", new PaintDefinition((ctx, size, props, args) => + { + ctx.FillStyle = "red"; + ctx.FillRect(0, 0, size.Width, size.Height); + })); + + var image = document.GetElementById("target").DrawPaintImages("background-image", Size).Single(); + + Assert.IsNotNull(image); + Assert.AreEqual("box", image.Name); + Assert.AreSame(Size, image.Size); + Assert.AreEqual(1.0, image.DevicePixelRatio); + CollectionAssert.AreEqual(new[] { "fillStyle(\"#ff0000\")", "fillRect(0, 0, 100, 50)" }, Draw(image).Commands.Select(m => m.ToString())); + } + + [Test] + public void MissingPainterGivesAnInvalidImage() + { + var document = ParseDocument("
"); + document.GetPaintWorklet().RegisterPaint("box", new PaintDefinition((ctx, size, props, args) => { })); + + var images = document.GetElementById("target").DrawPaintImages("background-image", Size); + + Assert.AreEqual(2, images.Count); + Assert.IsNull(images[0]); + Assert.IsNotNull(images[1]); + } + + [Test] + public void NoPaintWorkletGivesAnInvalidImage() + { + var document = ParseDocument("
"); + var images = document.GetElementById("target").DrawPaintImages("background-image", Size); + + Assert.AreEqual(1, images.Count); + Assert.IsNull(images[0]); + } + + [Test] + public void PropertyWithoutPaintFunctionGivesNoImages() + { + var document = ParseDocument("
"); + document.GetPaintWorklet().RegisterPaint("box", new PaintDefinition((ctx, size, props, args) => { })); + + CollectionAssert.IsEmpty(document.GetElementById("target").DrawPaintImages("background-image", Size)); + CollectionAssert.IsEmpty(document.GetElementById("target").DrawPaintImages("border-image-source", Size)); + } + + [Test] + public void PainterRegisteredLaterIsUsedForLaterDrawing() + { + var document = ParseDocument("
"); + var element = document.GetElementById("target"); + + Assert.IsNull(element.DrawPaintImages("background-image", Size)[0]); + document.GetPaintWorklet().RegisterPaint("late", new PaintDefinition((ctx, size, props, args) => { })); + Assert.IsNotNull(element.DrawPaintImages("background-image", Size)[0]); + } + + [Test] + public void ThrowingPainterGivesAnInvalidImage() + { + var document = ParseDocument("
"); + document.GetPaintWorklet().RegisterPaint("broken", new PaintDefinition((ctx, size, props, args) => ctx.Arc(0, 0, -1, 0, 1))); + + Assert.IsNull(document.GetElementById("target").DrawPaintImages("background-image", Size)[0]); + } + + [Test] + public void PainterReadsItsInputProperties() + { + var document = ParseDocument("
"); + var seen = new Dictionary(); + var size = 0; + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => + { + size = props.Size; + seen["color"] = props.Get("color")?.ToString(); + seen["--gap"] = props.Get("--gap")?.ToString(); + seen["border-top-width"] = props.Get("border-top-width")?.ToString(); + seen["opacity"] = props.Get("opacity")?.ToString(); + seen["has-opacity"] = props.Has("opacity").ToString(); + }) + { + InputProperties = new[] { "color", "--gap", "border-top-width" }, + }); + + Assert.IsNotNull(document.GetElementById("target").DrawPaintImages("background-image", Size)[0]); + Assert.AreEqual("rgba(0, 0, 255, 1)", seen["color"]); + Assert.AreEqual("4px", seen["--gap"]); + Assert.AreEqual("3px", seen["border-top-width"]); + Assert.IsNull(seen["opacity"]); + Assert.AreEqual("False", seen["has-opacity"]); + Assert.AreEqual(3, size); + } + + [Test] + public void InputPropertiesHaveTheirInitialOrInheritedValues() + { + var document = ParseDocument("
"); + var seen = new Dictionary(); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => + { + seen["color"] = props.Get("color")?.ToString(); + seen["opacity"] = props.Get("opacity")?.ToString(); + }) + { + InputProperties = new[] { "color", "opacity" }, + }); + + document.GetElementById("target").DrawPaintImages("background-image", Size); + + Assert.AreEqual("rgba(0, 128, 0, 1)", seen["color"]); + Assert.AreEqual("1", seen["opacity"]); + } + + [Test] + public void RegisteredCustomInputPropertyIsTyped() + { + var document = ParseDocument("
"); + document.DefaultView.RegisterProperty(new PropertyDefinition { Name = "--radius", Syntax = "", Inherits = false, InitialValue = "0px" }); + var radius = default(CssStyleValue); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => radius = props.Get("--radius")) + { + InputProperties = new[] { "--radius" }, + }); + + document.GetElementById("target").DrawPaintImages("background-image", Size); + + Assert.IsInstanceOf(radius); + Assert.AreEqual(20.0, ((CssUnitValue)radius).Value); + Assert.AreEqual("px", ((CssUnitValue)radius).Unit); + } + + [Test] + public void ArgumentsAreTypedByTheirSyntax() + { + var document = ParseDocument("
"); + var arguments = default(IReadOnlyList); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => arguments = args) + { + InputArguments = new[] { "", "", "*" }, + }); + + Assert.IsNotNull(document.GetElementById("target").DrawPaintImages("background-image", Size)[0]); + Assert.AreEqual(3, arguments.Count); + Assert.IsInstanceOf(arguments[0]); + Assert.AreEqual("10px", arguments[0].ToString()); + Assert.AreEqual("rgba(255, 0, 0, 1)", arguments[1].ToString()); + Assert.IsInstanceOf(arguments[2]); + Assert.AreEqual("a b c", arguments[2].ToString()); + } + + [TestCase("paint(x, red)")] + [TestCase("paint(x, 10px, 20px)")] + [TestCase("paint(x)")] + public void ArgumentsNotMatchingTheirSyntaxGiveAnInvalidImage(String value) + { + var document = ParseDocument($"
"); + var called = false; + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => called = true) + { + InputArguments = new[] { "" }, + }); + + Assert.IsNull(document.GetElementById("target").DrawPaintImages("background-image", Size)[0]); + Assert.IsFalse(called); + } + + [Test] + public void ArgumentsWithoutInputArgumentsAreUnparsed() + { + var document = ParseDocument("
"); + var arguments = default(IReadOnlyList); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => arguments = args)); + + document.GetElementById("target").DrawPaintImages("background-image", Size); + + Assert.AreEqual(2, arguments.Count); + Assert.IsTrue(arguments.All(m => m is CssUnparsedValue)); + Assert.AreEqual("10px", arguments[0].ToString()); + Assert.AreEqual("foo(1, 2)", arguments[1].ToString()); + } + + [Test] + public void ArgumentsWithVariablesAreSubstituted() + { + var document = ParseDocument("
"); + var arguments = default(IReadOnlyList); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => arguments = args) + { + InputArguments = new[] { "" }, + }); + + document.GetElementById("target").DrawPaintImages("background-image", Size); + + Assert.AreEqual("6px", arguments[0].ToString()); + } + + [Test] + public void ContextOptionsArePassedToTheContext() + { + var document = ParseDocument("
"); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => { }) + { + ContextOptions = new PaintRenderingContext2DSettings { Alpha = false }, + }); + + var image = document.GetElementById("target").DrawPaintImages("background-image", Size)[0]; + + Assert.IsFalse(Draw(image).Settings.Alpha); + } + + [Test] + public void CustomContextFactoryIsUsed() + { + var factory = new FakeContextFactory(); + var config = Configuration.Default.WithCss().With(factory).WithRenderDevice(new DefaultRenderDevice { Resolution = 288 }); + var document = BrowsingContext.New(config).OpenAsync(m => m.Content("
")).Result; + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => ctx.FillRect(1, 2, 3, 4))); + + var image = document.GetElementById("target").DrawPaintImages("background-image", Size)[0]; + + Assert.AreSame(factory.Created, image.Context); + Assert.AreEqual(3.0, image.DevicePixelRatio); + Assert.AreEqual(3.0, factory.Created.DevicePixelRatio); + Assert.AreEqual("fillRect(1, 2, 3, 4)", factory.Created.Commands.Single().ToString()); + } + + [Test] + public void PaintImageOfRenderTreeNode() + { + var document = ParseDocument("

Hello

"); + var color = default(String); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => color = props.Get("color").ToString()) + { + InputProperties = new[] { "color" }, + }); + var tree = document.DefaultView.Render(); + var node = Find(tree, "p"); + + var image = node.DrawPaintImages("background-image", Size).Single(); + + Assert.IsNotNull(image); + Assert.AreEqual("rgba(255, 0, 0, 1)", color); + } + + [Test] + public void DrawingAPaintValueDirectly() + { + var document = ParseDocument("
"); + document.GetPaintWorklet().RegisterPaint("x", new PaintDefinition((ctx, s, props, args) => ctx.StrokeRect(0, 0, s.Width, s.Height))); + var paint = ParseDeclaration("border-image-source: paint(x)").RawValue.GetPaintValues().Single(); + + var image = document.GetElementById("target").DrawPaintImage(paint, new PaintSize(8, 8)); + + Assert.AreSame(paint, image.Source); + Assert.AreEqual("strokeRect(0, 0, 8, 8)", Draw(image).Commands.Single().ToString()); + } + + [Test] + public void PaintSizeMustBeNonNegativeAndFinite() + { + Assert.Throws(() => new PaintSize(-1, 1)); + Assert.Throws(() => new PaintSize(1, Double.NaN)); + Assert.Throws(() => new PaintSize(Double.PositiveInfinity, 1)); + } + + private static RenderTree.ElementRenderNode Find(RenderTree.IRenderNode node, String tag) + { + if (node is RenderTree.ElementRenderNode element && element.Ref.LocalName == tag) + { + return element; + } + + return node.Children.Select(child => Find(child, tag)).FirstOrDefault(m => m is not null); + } + + private sealed class FakeContextFactory : IPaintRenderingContextFactory + { + public RecordingPaintRenderingContext2D Created { get; private set; } + + public IPaintRenderingContext2D Create(PaintSize size, Double devicePixelRatio, PaintRenderingContext2DSettings settings) => + Created = new RecordingPaintRenderingContext2D(size, devicePixelRatio, settings); + } + } +} diff --git a/src/AngleSharp.Css.Tests/Painting/PaintWorkletTests.cs b/src/AngleSharp.Css.Tests/Painting/PaintWorkletTests.cs new file mode 100644 index 00000000..30e9037e --- /dev/null +++ b/src/AngleSharp.Css.Tests/Painting/PaintWorkletTests.cs @@ -0,0 +1,165 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Painting +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Painting; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using static CssConstructionFunctions; + + /// + /// The registry of paint definitions (CSS Painting API 3 and 4) and the extension + /// point for scripting engines (addModule). + /// + [TestFixture] + public class PaintWorkletTests + { + private static PaintDefinition Noop() => new((ctx, size, props, args) => { }); + + [Test] + public void WindowAndDocumentShareThePaintWorklet() + { + var document = ParseDocument("
"); + var worklet = document.DefaultView.GetPaintWorklet(); + + Assert.AreSame(worklet, document.GetPaintWorklet()); + Assert.AreSame(document, worklet.Document); + Assert.AreSame(worklet, worklet.GlobalScope.Worklet); + } + + [Test] + public void DocumentsHaveTheirOwnPaintWorklets() + { + var a = ParseDocument("
"); + var b = ParseDocument("
"); + a.GetPaintWorklet().RegisterPaint("x", Noop()); + + Assert.IsTrue(a.GetPaintWorklet().Contains("x")); + Assert.IsFalse(b.GetPaintWorklet().Contains("x")); + } + + [Test] + public void RegisteredDefinitionCanBeLookedUp() + { + var worklet = ParseDocument("").GetPaintWorklet(); + var definition = Noop(); + worklet.GlobalScope.RegisterPaint("checkerboard", definition); + + Assert.AreSame(definition, worklet.Get("checkerboard")); + Assert.IsNull(worklet.Get("Checkerboard")); + Assert.IsNull(worklet.Get("missing")); + CollectionAssert.AreEqual(new[] { "checkerboard" }, worklet.Names); + } + + [Test] + public void RegisteringTheSameNameTwiceIsAnInvalidModificationError() + { + var worklet = ParseDocument("").GetPaintWorklet(); + worklet.RegisterPaint("x", Noop()); + + var ex = Assert.Throws(() => worklet.RegisterPaint("x", Noop())); + Assert.AreEqual((Int32)DomError.InvalidModification, ex.Code); + } + + [Test] + public void EmptyNameIsATypeError() + { + var worklet = ParseDocument("").GetPaintWorklet(); + Assert.Throws(() => worklet.RegisterPaint("", Noop())); + } + + [Test] + public void InvalidSyntaxOfInputArgumentIsATypeError() + { + var worklet = ParseDocument("").GetPaintWorklet(); + var definition = new PaintDefinition((ctx, size, props, args) => { }) { InputArguments = new[] { "", "" } }; + + Assert.Throws(() => worklet.RegisterPaint("x", definition)); + Assert.IsFalse(worklet.Contains("x")); + } + + [Test] + public void UnknownInputPropertiesAreIgnored() + { + var worklet = ParseDocument("").GetPaintWorklet(); + var definition = new PaintDefinition((ctx, size, props, args) => { }) + { + InputProperties = new[] { "Color", "--My-Prop", "not-a-property", "color", "border-top-width" }, + }; + worklet.RegisterPaint("x", definition); + + CollectionAssert.AreEqual(new[] { "color", "--My-Prop", "border-top-width" }, worklet.GetInputProperties("x")); + } + + [Test] + public void DevicePixelRatioFollowsTheRenderDevice() + { + var config = Configuration.Default.WithCss().WithRenderDevice(new DefaultRenderDevice { Resolution = 192 }); + var document = BrowsingContext.New(config).OpenNewAsync().Result; + + Assert.AreEqual(2.0, document.GetPaintWorklet().GlobalScope.DevicePixelRatio); + Assert.AreEqual(1.0, ParseDocument("").GetPaintWorklet().DevicePixelRatio); + } + + [Test] + public void AddModuleWithoutLoaderIsNotSupported() + { + var worklet = ParseDocument("").GetPaintWorklet(); + var task = worklet.AddModule("painter.js"); + + Assert.IsTrue(task.IsFaulted); + var ex = task.Exception.InnerException as DomException; + Assert.IsNotNull(ex); + Assert.AreEqual((Int32)DomError.NotSupported, ex.Code); + } + + [Test] + public async Task AddModuleRunsTheModuleWithTheLoader() + { + var loader = new FakeModuleLoader(); + var config = Configuration.Default.WithCss().With(loader); + var document = await BrowsingContext.New(config).OpenAsync(m => m.Content("
").Address("https://example.com/app/index.html")); + var worklet = document.DefaultView.GetPaintWorklet(); + + await worklet.AddModule("painters/rings.js"); + + Assert.AreEqual("https://example.com/app/painters/rings.js", loader.Loaded[0].Href); + Assert.IsTrue(worklet.Contains("rings")); + } + + [Test] + public void AddModuleFailsWhenTheLoaderFails() + { + var loader = new FakeModuleLoader { Fail = true }; + var config = Configuration.Default.WithCss().With(loader); + var document = BrowsingContext.New(config).OpenNewAsync().Result; + var task = document.GetPaintWorklet().AddModule("https://example.com/broken.js"); + + Assert.ThrowsAsync(() => task); + } + + private sealed class FakeModuleLoader : IPaintWorkletModuleLoader + { + public List Loaded { get; } = new(); + + public Boolean Fail { get; set; } + + public Task LoadAsync(PaintWorkletGlobalScope scope, Url moduleUrl, CancellationToken cancellationToken) + { + if (Fail) + { + return Task.FromException(new InvalidOperationException("The module failed.")); + } + + Loaded.Add(moduleUrl); + // what a script engine does when the module calls registerPaint('rings', class { ... }) + scope.RegisterPaint("rings", new PaintDefinition((ctx, size, props, args) => ctx.FillRect(0, 0, size.Width, size.Height))); + return Task.CompletedTask; + } + } + } +} diff --git a/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs b/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs new file mode 100644 index 00000000..d8f35df7 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs @@ -0,0 +1,394 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Painting +{ + using AngleSharp.Css.Painting; + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Linq; + + /// + /// The default rendering context of paint definitions, which records the operations + /// and keeps the drawing state as the canvas API does. + /// + [TestFixture] + public class RecordingContextTests + { + private static RecordingPaintRenderingContext2D Create() => new(new PaintSize(100, 100)); + + private static String[] Commands(RecordingPaintRenderingContext2D ctx) => ctx.Commands.Select(m => m.ToString()).ToArray(); + + [Test] + public void DefaultState() + { + var ctx = Create(); + + Assert.AreEqual("#000000", ctx.FillStyle); + Assert.AreEqual("#000000", ctx.StrokeStyle); + Assert.AreEqual(1.0, ctx.GlobalAlpha); + Assert.AreEqual("source-over", ctx.GlobalCompositeOperation); + Assert.AreEqual(1.0, ctx.LineWidth); + Assert.AreEqual(CanvasLineCap.Butt, ctx.LineCap); + Assert.AreEqual(CanvasLineJoin.Miter, ctx.LineJoin); + Assert.AreEqual(10.0, ctx.MiterLimit); + Assert.AreEqual("rgba(0, 0, 0, 0)", ctx.ShadowColor); + Assert.IsTrue(ctx.ImageSmoothingEnabled); + Assert.AreEqual(ImageSmoothingQuality.Low, ctx.ImageSmoothingQuality); + CollectionAssert.IsEmpty(ctx.GetLineDash()); + CollectionAssert.IsEmpty(ctx.Commands); + Assert.IsTrue(ctx.Settings.Alpha); + } + + [TestCase("red", "#ff0000")] + [TestCase("#ABC", "#aabbcc")] + [TestCase("rgb(1 2 3 / 50%)", "rgba(1, 2, 3, 0.5)")] + [TestCase("transparent", "rgba(0, 0, 0, 0)")] + [TestCase("hsl(120, 100%, 25%)", "#008000")] + public void ColorsAreSerialized(String color, String expected) + { + var ctx = Create(); + ctx.FillStyle = color; + ctx.StrokeStyle = color; + ctx.ShadowColor = color; + + Assert.AreEqual(expected, ctx.FillStyle); + Assert.AreEqual(expected, ctx.StrokeStyle); + Assert.AreEqual(expected, ctx.ShadowColor); + } + + [Test] + public void InvalidValuesAreIgnored() + { + var ctx = Create(); + ctx.FillStyle = "not a color"; + ctx.FillStyle = 42; + ctx.GlobalAlpha = 2; + ctx.GlobalAlpha = Double.NaN; + ctx.GlobalCompositeOperation = "unknown"; + ctx.LineWidth = 0; + ctx.LineWidth = -1; + ctx.MiterLimit = Double.PositiveInfinity; + ctx.ShadowBlur = -1; + ctx.ShadowOffsetX = Double.NaN; + ctx.SetLineDash(new[] { 1.0, -1.0 }); + ctx.FillRect(Double.NaN, 0, 1, 1); + ctx.MoveTo(0, Double.PositiveInfinity); + + Assert.AreEqual("#000000", ctx.FillStyle); + Assert.AreEqual(1.0, ctx.GlobalAlpha); + Assert.AreEqual("source-over", ctx.GlobalCompositeOperation); + Assert.AreEqual(1.0, ctx.LineWidth); + Assert.AreEqual(10.0, ctx.MiterLimit); + Assert.AreEqual(0.0, ctx.ShadowBlur); + Assert.AreEqual(0.0, ctx.ShadowOffsetX); + CollectionAssert.IsEmpty(ctx.GetLineDash()); + CollectionAssert.IsEmpty(ctx.Commands); + } + + [Test] + public void OperationsAreRecordedInOrder() + { + var ctx = Create(); + ctx.Save(); + ctx.Translate(10, 20); + ctx.GlobalCompositeOperation = "multiply"; + ctx.LineCap = CanvasLineCap.Round; + ctx.BeginPath(); + ctx.MoveTo(0, 0); + ctx.LineTo(5, 5); + ctx.Arc(5, 5, 2, 0, Math.PI, true); + ctx.ClosePath(); + ctx.Fill(CanvasFillRule.EvenOdd); + ctx.Stroke(); + ctx.Restore(); + + CollectionAssert.AreEqual(new[] + { + "save()", + "translate(10, 20)", + "globalCompositeOperation(\"multiply\")", + "lineCap(\"round\")", + "beginPath()", + "moveTo(0, 0)", + "lineTo(5, 5)", + "arc(5, 5, 2, 0, 3.141592653589793, true)", + "closePath()", + "fill(\"evenodd\")", + "stroke()", + "restore()", + }, Commands(ctx)); + } + + [Test] + public void SaveAndRestoreTheDrawingState() + { + var ctx = Create(); + ctx.FillStyle = "red"; + ctx.LineWidth = 4; + ctx.Save(); + ctx.FillStyle = "blue"; + ctx.LineWidth = 8; + ctx.Translate(50, 50); + ctx.Restore(); + + Assert.AreEqual("#ff0000", ctx.FillStyle); + Assert.AreEqual(4.0, ctx.LineWidth); + + // the transform has been restored, too + ctx.Rect(0, 0, 10, 10); + Assert.IsTrue(ctx.IsPointInPath(5, 5)); + } + + [Test] + public void RestoreWithoutSaveDoesNothing() + { + var ctx = Create(); + ctx.Restore(); + CollectionAssert.IsEmpty(ctx.Commands); + } + + [Test] + public void ResetClearsEverything() + { + var ctx = Create(); + ctx.FillStyle = "red"; + ctx.Save(); + ctx.Rect(0, 0, 10, 10); + ctx.FillRect(0, 0, 10, 10); + ctx.Reset(); + + Assert.AreEqual("#000000", ctx.FillStyle); + Assert.IsFalse(ctx.IsPointInPath(5, 5)); + CollectionAssert.IsEmpty(ctx.Commands); + } + + [Test] + public void LineDashWithOddCountIsRepeated() + { + var ctx = Create(); + ctx.SetLineDash(new[] { 1.0, 2.0, 3.0 }); + + CollectionAssert.AreEqual(new[] { 1.0, 2.0, 3.0, 1.0, 2.0, 3.0 }, ctx.GetLineDash()); + Assert.AreEqual("setLineDash([1, 2, 3, 1, 2, 3])", Commands(ctx).Single()); + } + + [Test] + public void PointInRectangle() + { + var ctx = Create(); + ctx.Rect(10, 10, 20, 20); + + Assert.IsTrue(ctx.IsPointInPath(15, 15)); + Assert.IsTrue(ctx.IsPointInPath(10, 10)); + Assert.IsFalse(ctx.IsPointInPath(5, 15)); + Assert.IsFalse(ctx.IsPointInPath(35, 35)); + } + + [Test] + public void PointInCircle() + { + var ctx = Create(); + ctx.Arc(50, 50, 10, 0, 2 * Math.PI); + + Assert.IsTrue(ctx.IsPointInPath(50, 50)); + Assert.IsTrue(ctx.IsPointInPath(57, 57)); + Assert.IsFalse(ctx.IsPointInPath(58, 58)); + } + + [Test] + public void PointInPathWithFillRule() + { + var ctx = Create(); + ctx.Rect(0, 0, 30, 30); + ctx.Rect(10, 10, 10, 10); + + Assert.IsTrue(ctx.IsPointInPath(15, 15, CanvasFillRule.NonZero)); + Assert.IsFalse(ctx.IsPointInPath(15, 15, CanvasFillRule.EvenOdd)); + Assert.IsTrue(ctx.IsPointInPath(5, 5, CanvasFillRule.EvenOdd)); + } + + [Test] + public void PointInPathUsesTheTransformAtTheTimeOfBuilding() + { + var ctx = Create(); + ctx.Translate(50, 0); + ctx.Scale(2, 2); + ctx.Rect(0, 0, 10, 10); + ctx.ResetTransform(); + + Assert.IsTrue(ctx.IsPointInPath(65, 15)); + Assert.IsFalse(ctx.IsPointInPath(5, 5)); + } + + [Test] + public void PointInPath2DUsesTheCurrentTransform() + { + var ctx = Create(); + var path = new Path2D(); + path.Rect(0, 0, 10, 10); + ctx.Translate(50, 50); + + Assert.IsTrue(ctx.IsPointInPath(path, 55, 55)); + Assert.IsFalse(ctx.IsPointInPath(path, 5, 5)); + } + + [Test] + public void PointInRoundedRectangle() + { + var ctx = Create(); + ctx.RoundRect(0, 0, 40, 40, 10); + + Assert.IsTrue(ctx.IsPointInPath(20, 20)); + Assert.IsTrue(ctx.IsPointInPath(10, 1)); + Assert.IsFalse(ctx.IsPointInPath(1, 1)); + Assert.IsFalse(ctx.IsPointInPath(39, 39)); + } + + [Test] + public void PointInRoundedCornerOfArcTo() + { + var ctx = Create(); + ctx.MoveTo(0, 0); + ctx.ArcTo(40, 0, 40, 40, 20); + ctx.LineTo(40, 40); + ctx.LineTo(0, 40); + + Assert.IsTrue(ctx.IsPointInPath(20, 20)); + Assert.IsTrue(ctx.IsPointInPath(30, 5)); + Assert.IsFalse(ctx.IsPointInPath(39, 1)); + } + + [Test] + public void PointInStroke() + { + var ctx = Create(); + ctx.MoveTo(0, 50); + ctx.LineTo(100, 50); + ctx.LineWidth = 10; + + Assert.IsTrue(ctx.IsPointInStroke(50, 54)); + Assert.IsFalse(ctx.IsPointInStroke(50, 56)); + Assert.IsFalse(ctx.IsPointInPath(50, 60)); + } + + [Test] + public void PointInStrokeOfCurve() + { + var ctx = Create(); + ctx.MoveTo(0, 0); + ctx.QuadraticCurveTo(50, 100, 100, 0); + ctx.BezierCurveTo(100, 50, 50, 50, 0, 0); + + Assert.IsTrue(ctx.IsPointInStroke(50, 50)); + Assert.IsFalse(ctx.IsPointInStroke(50, 80)); + } + + [Test] + public void NegativeRadiusIsAnIndexSizeError() + { + var ctx = Create(); + + Assert.AreEqual((Int32)DomError.IndexSizeError, Assert.Throws(() => ctx.Arc(0, 0, -1, 0, 1)).Code); + Assert.AreEqual((Int32)DomError.IndexSizeError, Assert.Throws(() => ctx.ArcTo(0, 0, 1, 1, -1)).Code); + Assert.AreEqual((Int32)DomError.IndexSizeError, Assert.Throws(() => ctx.Ellipse(0, 0, 1, -1, 0, 0, 1)).Code); + Assert.AreEqual((Int32)DomError.IndexSizeError, Assert.Throws(() => ctx.CreateRadialGradient(0, 0, -1, 0, 0, 1)).Code); + } + + [Test] + public void RoundRectRadiiAreValidated() + { + var ctx = Create(); + + Assert.Throws(() => ctx.RoundRect(0, 0, 10, 10, 1, 2, 3, 4, 5)); + Assert.Throws(() => ctx.RoundRect(0, 0, 10, 10, Array.Empty())); + Assert.Throws(() => ctx.RoundRect(0, 0, 10, 10, -1)); + ctx.RoundRect(0, 0, 10, 10, 1, 2); + Assert.AreEqual("roundRect(0, 0, 10, 10, [1, 2])", Commands(ctx).Single()); + } + + [Test] + public void GradientAsFillStyle() + { + var ctx = Create(); + var gradient = ctx.CreateLinearGradient(0, 0, 100, 0); + gradient.AddColorStop(0, "red"); + gradient.AddColorStop(1, "rgba(0, 0, 255, 0.5)"); + ctx.FillStyle = gradient; + + Assert.AreSame(gradient, ctx.FillStyle); + Assert.AreEqual(CanvasGradientKind.Linear, gradient.Kind); + CollectionAssert.AreEqual(new[] { 0.0, 0.0, 100.0, 0.0 }, gradient.Parameters); + CollectionAssert.AreEqual(new[] { "#ff0000", "rgba(0, 0, 255, 0.5)" }, gradient.ColorStops.Select(m => m.Color)); + Assert.AreSame(gradient, ctx.Commands.Single().Arguments[0]); + } + + [Test] + public void GradientColorStopsAreValidated() + { + var gradient = Create().CreateConicGradient(0, 50, 50); + + Assert.AreEqual((Int32)DomError.IndexSizeError, Assert.Throws(() => gradient.AddColorStop(1.5, "red")).Code); + Assert.AreEqual((Int32)DomError.Syntax, Assert.Throws(() => gradient.AddColorStop(0.5, "nope")).Code); + CollectionAssert.IsEmpty(gradient.ColorStops); + } + + [Test] + public void PatternOfImage() + { + var ctx = Create(); + var image = (CssImageValue)CssStyleValue.Parse("background-image", "url(a.png)"); + + Assert.AreEqual("repeat", ctx.CreatePattern(image, null).Repetition); + Assert.AreEqual("repeat", ctx.CreatePattern(image, "").Repetition); + Assert.AreEqual("no-repeat", ctx.CreatePattern(image, "no-repeat").Repetition); + Assert.AreEqual((Int32)DomError.Syntax, Assert.Throws(() => ctx.CreatePattern(image, "space")).Code); + } + + [Test] + public void DrawImageIsRecorded() + { + var ctx = Create(); + var image = (CssImageValue)CssStyleValue.Parse("background-image", "url(a.png)"); + ctx.DrawImage(image, 1, 2); + ctx.DrawImage(image, 1, 2, 3, 4); + ctx.DrawImage(image, 1, 2, 3, 4, 5, 6, 7, 8); + + Assert.AreEqual(3, ctx.Commands.Count); + Assert.AreSame(image, ctx.Commands[0].Arguments[0]); + Assert.AreEqual(9, ctx.Commands[2].Arguments.Count); + } + + [Test] + public void DrawnPathIsASnapshot() + { + var ctx = Create(); + var path = new Path2D(); + path.MoveTo(0, 0); + ctx.Fill(path); + path.LineTo(10, 10); + + var drawn = (Path2D)ctx.Commands.Single().Arguments[0]; + Assert.AreEqual("Path2D(moveTo(0, 0))", drawn.ToString()); + Assert.AreEqual(2, path.Commands.Count); + } + + [Test] + public void Path2DCanBeCopiedAndCombined() + { + var a = new Path2D(); + a.Rect(0, 0, 10, 10); + var b = new Path2D(a); + b.Rect(20, 20, 10, 10); + var c = new Path2D("M 0 0 L 10 10"); + c.AddPath(b); + var ctx = Create(); + + Assert.AreEqual(1, a.Commands.Count); + Assert.AreEqual(2, b.Commands.Count); + Assert.AreEqual("d(\"M 0 0 L 10 10\")", c.Commands[0].ToString()); + Assert.IsTrue(ctx.IsPointInPath(c, 25, 25)); + Assert.IsFalse(ctx.IsPointInPath(a, 25, 25)); + } + } +} diff --git a/src/AngleSharp.Css/Constants/FunctionNames.cs b/src/AngleSharp.Css/Constants/FunctionNames.cs index df42327c..f0b6a8bc 100644 --- a/src/AngleSharp.Css/Constants/FunctionNames.cs +++ b/src/AngleSharp.Css/Constants/FunctionNames.cs @@ -322,6 +322,11 @@ public static class FunctionNames ///
public static readonly String ImageSet = "image-set"; + /// + /// The paint function (CSS Painting API 1). + /// + public static readonly String Paint = "paint"; + /// /// The type function of an image-set option. /// diff --git a/src/AngleSharp.Css/Dom/CssHelpers.Paint.cs b/src/AngleSharp.Css/Dom/CssHelpers.Paint.cs new file mode 100644 index 00000000..ef637c54 --- /dev/null +++ b/src/AngleSharp.Css/Dom/CssHelpers.Paint.cs @@ -0,0 +1,45 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Painting; + using AngleSharp.Dom; + using System; + + /// + /// The paint worklet (CSS Painting API). + /// https://www.w3.org/TR/css-paint-api-1/#dom-css-paintworklet + /// + public static partial class CssHelpers + { + /// + /// Gets the paint worklet of the document of the window (CSS.paintWorklet), which + /// holds the paint definitions used by the paint() functions of its styles. + /// + /// The hosting window. + /// The paint worklet, which is created when it is first used. + [DomName("paintWorklet")] + [DomAccessor(Accessors.Getter)] + public static PaintWorklet GetPaintWorklet(this IWindow window) + { + if (window is null) + throw new ArgumentNullException(nameof(window)); + + return window.Document.GetPaintWorklet(); + } + + /// + /// Gets the paint worklet of the document, which holds the paint definitions used + /// by the paint() functions of its styles. + /// + /// The document. + /// The paint worklet, which is created when it is first used. + public static PaintWorklet GetPaintWorklet(this IDocument document) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); + + return PaintWorklet.For(document); + } + } +} diff --git a/src/AngleSharp.Css/Painting/CanvasColor.cs b/src/AngleSharp.Css/Painting/CanvasColor.cs new file mode 100644 index 00000000..74022cf2 --- /dev/null +++ b/src/AngleSharp.Css/Painting/CanvasColor.cs @@ -0,0 +1,50 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.Parser; + using AngleSharp.Text; + using System; + using System.Globalization; + + /// + /// Parses and serializes the colors of the canvas API. + /// https://html.spec.whatwg.org/multipage/canvas.html#serialisation-of-a-color + /// + static class CanvasColor + { + public const String Black = "#000000"; + + public const String TransparentBlack = "rgba(0, 0, 0, 0)"; + + /// + /// Parses the CSS color and gives its serialization, i.e., #rrggbb if it is + /// opaque and rgba(r, g, b, a) otherwise. + /// + /// The serialization or null if the text is no color. + public static String? Normalize(String? text) + { + if (text is null) + { + return null; + } + + var source = new StringSource(text); + source.SkipSpacesAndComments(); + var color = source.ParseColor(); + source.SkipSpacesAndComments(); + + if (color is null || !source.IsDone) + { + return null; + } + + var value = color.Value; + + if (value.A == 255) + { + return String.Concat("#", value.R.ToString("x2"), value.G.ToString("x2"), value.B.ToString("x2")); + } + + return String.Format(CultureInfo.InvariantCulture, "rgba({0}, {1}, {2}, {3})", value.R, value.G, value.B, value.Alpha); + } + } +} diff --git a/src/AngleSharp.Css/Painting/CanvasEnums.cs b/src/AngleSharp.Css/Painting/CanvasEnums.cs new file mode 100644 index 00000000..9d3bff2b --- /dev/null +++ b/src/AngleSharp.Css/Painting/CanvasEnums.cs @@ -0,0 +1,91 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + + /// + /// The rule deciding if a point is inside a path. + /// + [DomName("CanvasFillRule")] + public enum CanvasFillRule : byte + { + /// + /// The non-zero winding rule. + /// + [DomName("nonzero")] + NonZero, + /// + /// The even-odd rule. + /// + [DomName("evenodd")] + EvenOdd, + } + + /// + /// The shape of the ends of lines. + /// + [DomName("CanvasLineCap")] + public enum CanvasLineCap : byte + { + /// + /// The line ends at its end point. + /// + [DomName("butt")] + Butt, + /// + /// A half circle is added to the end. + /// + [DomName("round")] + Round, + /// + /// A half square is added to the end. + /// + [DomName("square")] + Square, + } + + /// + /// The shape of the corners where lines meet. + /// + [DomName("CanvasLineJoin")] + public enum CanvasLineJoin : byte + { + /// + /// The corner is rounded. + /// + [DomName("round")] + Round, + /// + /// The corner is cut off. + /// + [DomName("bevel")] + Bevel, + /// + /// The corner is extended to a point (up to the miter limit). + /// + [DomName("miter")] + Miter, + } + + /// + /// The quality of smoothing scaled images. + /// + [DomName("ImageSmoothingQuality")] + public enum ImageSmoothingQuality : byte + { + /// + /// Low quality. + /// + [DomName("low")] + Low, + /// + /// Medium quality. + /// + [DomName("medium")] + Medium, + /// + /// High quality. + /// + [DomName("high")] + High, + } +} diff --git a/src/AngleSharp.Css/Painting/CanvasGradient.cs b/src/AngleSharp.Css/Painting/CanvasGradient.cs new file mode 100644 index 00000000..97d3d4f6 --- /dev/null +++ b/src/AngleSharp.Css/Painting/CanvasGradient.cs @@ -0,0 +1,97 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + + /// + /// The kind of a gradient. + /// + public enum CanvasGradientKind : byte + { + /// + /// Along the line between two points (x0, y0, x1, y1). + /// + Linear, + /// + /// Between two circles (x0, y0, r0, x1, y1, r1). + /// + Radial, + /// + /// Around a point (startAngle, x, y). + /// + Conic, + } + + /// + /// A color stop of a gradient. + /// + public sealed class CanvasColorStop + { + internal CanvasColorStop(Double offset, String color) + { + Offset = offset; + Color = color; + } + + /// + /// Gets the offset, from 0 to 1. + /// + public Double Offset { get; } + + /// + /// Gets the serialized color, e.g., #ff0000. + /// + public String Color { get; } + } + + /// + /// A gradient, which can be used as a fill or stroke style. + /// https://html.spec.whatwg.org/multipage/canvas.html#canvasgradient + /// + [DomName("CanvasGradient")] + public sealed class CanvasGradient + { + private readonly List _stops = new(); + + internal CanvasGradient(CanvasGradientKind kind, params Double[] parameters) + { + Kind = kind; + Parameters = parameters; + } + + /// + /// Gets the kind of the gradient. + /// + public CanvasGradientKind Kind { get; } + + /// + /// Gets the parameters the gradient has been created with, as described by its kind. + /// + public IReadOnlyList Parameters { get; } + + /// + /// Gets the color stops in the order they have been added. + /// + public IReadOnlyList ColorStops => _stops; + + /// + /// Adds a color stop. + /// + /// The offset, from 0 to 1. + /// The CSS color. + /// + /// An IndexSizeError if the offset is out of range, or a SyntaxError if the color is not valid. + /// + [DomName("addColorStop")] + public void AddColorStop(Double offset, String color) + { + if (Double.IsNaN(offset) || offset < 0 || offset > 1) + throw new DomException(DomError.IndexSizeError); + + var normalized = CanvasColor.Normalize(color) ?? throw new DomException(DomError.Syntax); + _stops.Add(new CanvasColorStop(offset, normalized)); + } + } +} diff --git a/src/AngleSharp.Css/Painting/CanvasPathBuilder.cs b/src/AngleSharp.Css/Painting/CanvasPathBuilder.cs new file mode 100644 index 00000000..da9cbc43 --- /dev/null +++ b/src/AngleSharp.Css/Painting/CanvasPathBuilder.cs @@ -0,0 +1,155 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + + /// + /// Validates and records the operations of the CanvasPath mixin, and builds the + /// geometry of the path from them, which is shared by the rendering context (in the + /// coordinates of the output, i.e., with the current transform) and Path2D (in its + /// own coordinates). + /// + sealed class CanvasPathBuilder + { + private readonly List _commands; + + public CanvasPathBuilder(List commands, PathGeometry geometry) + { + _commands = commands; + Geometry = geometry; + } + + public PathGeometry Geometry { get; } + + public void ClosePath() + { + Geometry.ClosePath(); + Record("closePath"); + } + + public void MoveTo(Double x, Double y, PaintMatrix m) + { + if (Finite(x, y)) + { + Geometry.MoveTo(m.Apply(x, y)); + Record("moveTo", x, y); + } + } + + public void LineTo(Double x, Double y, PaintMatrix m) + { + if (Finite(x, y)) + { + Geometry.LineTo(m.Apply(x, y)); + Record("lineTo", x, y); + } + } + + public void QuadraticCurveTo(Double cpx, Double cpy, Double x, Double y, PaintMatrix m) + { + if (Finite(cpx, cpy, x, y)) + { + Geometry.QuadraticCurveTo(m.Apply(cpx, cpy), m.Apply(x, y)); + Record("quadraticCurveTo", cpx, cpy, x, y); + } + } + + public void BezierCurveTo(Double cp1x, Double cp1y, Double cp2x, Double cp2y, Double x, Double y, PaintMatrix m) + { + if (Finite(cp1x, cp1y, cp2x, cp2y, x, y)) + { + Geometry.BezierCurveTo(m.Apply(cp1x, cp1y), m.Apply(cp2x, cp2y), m.Apply(x, y)); + Record("bezierCurveTo", cp1x, cp1y, cp2x, cp2y, x, y); + } + } + + public void ArcTo(Double x1, Double y1, Double x2, Double y2, Double radius, PaintMatrix m) + { + if (Finite(x1, y1, x2, y2, radius)) + { + if (radius < 0) + throw new DomException(DomError.IndexSizeError); + + Geometry.ArcTo(x1, y1, x2, y2, radius, m); + Record("arcTo", x1, y1, x2, y2, radius); + } + } + + public void Rect(Double x, Double y, Double w, Double h, PaintMatrix m) + { + if (Finite(x, y, w, h)) + { + Geometry.Rect(x, y, w, h, m); + Record("rect", x, y, w, h); + } + } + + public void RoundRect(Double x, Double y, Double w, Double h, Double[] radii, PaintMatrix m) + { + radii ??= new Double[] { 0 }; + + if (radii.Length < 1 || radii.Length > 4) + throw new ArgumentOutOfRangeException(nameof(radii), "Between one and four radii are required."); + + if (Finite(x, y, w, h) && Finite(radii)) + { + foreach (var radius in radii) + { + if (radius < 0) + throw new ArgumentOutOfRangeException(nameof(radii), "A radius must not be negative."); + } + + var corners = radii.Length switch + { + 1 => new[] { radii[0], radii[0], radii[0], radii[0] }, + 2 => new[] { radii[0], radii[1], radii[0], radii[1] }, + 3 => new[] { radii[0], radii[1], radii[2], radii[1] }, + _ => new[] { radii[0], radii[1], radii[2], radii[3] }, + }; + + Geometry.RoundRect(x, y, w, h, corners, m); + Record("roundRect", x, y, w, h, (Double[])radii.Clone()); + } + } + + public void Arc(Double x, Double y, Double radius, Double startAngle, Double endAngle, Boolean counterclockwise, PaintMatrix m) + { + if (Finite(x, y, radius, startAngle, endAngle)) + { + if (radius < 0) + throw new DomException(DomError.IndexSizeError); + + Geometry.Ellipse(x, y, radius, radius, 0, startAngle, endAngle, counterclockwise, m); + Record("arc", x, y, radius, startAngle, endAngle, counterclockwise); + } + } + + public void Ellipse(Double x, Double y, Double radiusX, Double radiusY, Double rotation, Double startAngle, Double endAngle, Boolean counterclockwise, PaintMatrix m) + { + if (Finite(x, y, radiusX, radiusY, rotation, startAngle, endAngle)) + { + if (radiusX < 0 || radiusY < 0) + throw new DomException(DomError.IndexSizeError); + + Geometry.Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise, m); + Record("ellipse", x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise); + } + } + + private void Record(String name, params Object[] arguments) => _commands.Add(new PaintCommand(name, arguments)); + + public static Boolean Finite(params Double[] values) + { + foreach (var value in values) + { + if (Double.IsNaN(value) || Double.IsInfinity(value)) + { + return false; + } + } + + return true; + } + } +} diff --git a/src/AngleSharp.Css/Painting/CanvasPattern.cs b/src/AngleSharp.Css/Painting/CanvasPattern.cs new file mode 100644 index 00000000..db3d2b41 --- /dev/null +++ b/src/AngleSharp.Css/Painting/CanvasPattern.cs @@ -0,0 +1,30 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using AngleSharp.Css.TypedOm; + using System; + + /// + /// A pattern of an image, which can be used as a fill or stroke style. + /// https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern + /// + [DomName("CanvasPattern")] + public sealed class CanvasPattern + { + internal CanvasPattern(CssImageValue image, String repetition) + { + Image = image; + Repetition = repetition; + } + + /// + /// Gets the image of the pattern. + /// + public CssImageValue Image { get; } + + /// + /// Gets how the image is repeated: repeat, repeat-x, repeat-y, or no-repeat. + /// + public String Repetition { get; } + } +} diff --git a/src/AngleSharp.Css/Painting/ICanvasPath.cs b/src/AngleSharp.Css/Painting/ICanvasPath.cs new file mode 100644 index 00000000..b4aa213f --- /dev/null +++ b/src/AngleSharp.Css/Painting/ICanvasPath.cs @@ -0,0 +1,81 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using System; + + /// + /// The operations building a path (the CanvasPath mixin), shared by the rendering + /// context and . Operations with non-finite arguments are ignored. + /// https://html.spec.whatwg.org/multipage/canvas.html#canvaspath + /// + public interface ICanvasPath + { + /// + /// Closes the current subpath, i.e., adds a line to its start. + /// + [DomName("closePath")] + void ClosePath(); + + /// + /// Starts a new subpath at the given point. + /// + [DomName("moveTo")] + void MoveTo(Double x, Double y); + + /// + /// Adds a straight line to the given point. + /// + [DomName("lineTo")] + void LineTo(Double x, Double y); + + /// + /// Adds a quadratic Bézier curve to the given point. + /// + [DomName("quadraticCurveTo")] + void QuadraticCurveTo(Double cpx, Double cpy, Double x, Double y); + + /// + /// Adds a cubic Bézier curve to the given point. + /// + [DomName("bezierCurveTo")] + void BezierCurveTo(Double cp1x, Double cp1y, Double cp2x, Double cp2y, Double x, Double y); + + /// + /// Adds an arc with the given radius touching the lines to both points. + /// + /// An IndexSizeError for a negative radius. + [DomName("arcTo")] + void ArcTo(Double x1, Double y1, Double x2, Double y2, Double radius); + + /// + /// Adds a closed subpath of the rectangle. + /// + [DomName("rect")] + void Rect(Double x, Double y, Double w, Double h); + + /// + /// Adds a closed subpath of the rectangle with rounded corners, which has one to + /// four radii (all corners; top-left and bottom-right, top-right and bottom-left; + /// top-left, top-right and bottom-left, bottom-right; each corner). + /// + /// + /// The RangeError for a negative radius or not one to four radii. + /// + [DomName("roundRect")] + void RoundRect(Double x, Double y, Double w, Double h, params Double[] radii); + + /// + /// Adds an arc of the circle. + /// + /// An IndexSizeError for a negative radius. + [DomName("arc")] + void Arc(Double x, Double y, Double radius, Double startAngle, Double endAngle, Boolean counterclockwise = false); + + /// + /// Adds an arc of the ellipse. + /// + /// An IndexSizeError for a negative radius. + [DomName("ellipse")] + void Ellipse(Double x, Double y, Double radiusX, Double radiusY, Double rotation, Double startAngle, Double endAngle, Boolean counterclockwise = false); + } +} diff --git a/src/AngleSharp.Css/Painting/IPaintDefinition.cs b/src/AngleSharp.Css/Painting/IPaintDefinition.cs new file mode 100644 index 00000000..232429da --- /dev/null +++ b/src/AngleSharp.Css/Painting/IPaintDefinition.cs @@ -0,0 +1,47 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.TypedOm; + using System; + using System.Collections.Generic; + + /// + /// A paint definition, i.e., what registerPaint() is given: the class of a paint + /// worklet, which draws the paint images of the paint() functions using its name. + /// A scripting engine implements it for a class of a script, e.g., by constructing + /// the class and calling its paint method, and an application may implement it + /// directly in .NET (or use ). + /// https://www.w3.org/TR/css-paint-api-1/#paint-definition + /// + public interface IPaintDefinition + { + /// + /// Gets the properties (standard or custom) of the element the definition reads, + /// i.e., the static inputProperties of the class. They are read once, when the + /// definition is registered. Unknown properties are ignored. + /// + IEnumerable InputProperties { get; } + + /// + /// Gets the syntax (as for @property, e.g., <length> or <color>+) of + /// each argument of the paint() function, i.e., the static inputArguments of the + /// class. They are read once, when the definition is registered. If there are + /// none, the arguments are given as they are written (CssUnparsedValue). + /// + IEnumerable InputArguments { get; } + + /// + /// Gets the options of the rendering context, i.e., the static contextOptions of + /// the class. They are read once, when the definition is registered. + /// + PaintRenderingContext2DSettings ContextOptions { get; } + + /// + /// Draws the paint image, i.e., calls the paint method of the class. + /// + /// The rendering context to draw with. + /// The size of the image. + /// The input properties of the element. + /// The arguments of the paint() function. + void Paint(IPaintRenderingContext2D context, PaintSize size, IStylePropertyMapReadOnly properties, IReadOnlyList arguments); + } +} diff --git a/src/AngleSharp.Css/Painting/IPaintRenderingContext2D.cs b/src/AngleSharp.Css/Painting/IPaintRenderingContext2D.cs new file mode 100644 index 00000000..09b2674c --- /dev/null +++ b/src/AngleSharp.Css/Painting/IPaintRenderingContext2D.cs @@ -0,0 +1,345 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using AngleSharp.Css.TypedOm; + using System; + using System.Collections.Generic; + + /// + /// The rendering context of a paint definition, which is a subset of the one of a + /// canvas: there is no text, no access to the pixels, and only images given as CSS + /// values (CssImageValue) can be drawn. Its implementation decides what drawing + /// produces, e.g., recorded operations or a bitmap. + /// https://www.w3.org/TR/css-paint-api-1/#paintrenderingcontext2d + /// + [DomName("PaintRenderingContext2D")] + public interface IPaintRenderingContext2D : ICanvasPath + { + #region CanvasState + + /// + /// Pushes the drawing state (transform, clip, styles) onto the stack. + /// + [DomName("save")] + void Save(); + + /// + /// Pops the drawing state from the stack, if there is one. + /// + [DomName("restore")] + void Restore(); + + /// + /// Resets the context: clears the image, the path, the stack and the state. + /// + [DomName("reset")] + void Reset(); + + #endregion + + #region CanvasTransform + + /// + /// Scales the current transform. + /// + [DomName("scale")] + void Scale(Double x, Double y); + + /// + /// Rotates the current transform clockwise by the angle (in radians). + /// + [DomName("rotate")] + void Rotate(Double angle); + + /// + /// Translates the current transform. + /// + [DomName("translate")] + void Translate(Double x, Double y); + + /// + /// Multiplies the current transform with the given matrix. + /// + [DomName("transform")] + void Transform(Double a, Double b, Double c, Double d, Double e, Double f); + + /// + /// Replaces the current transform with the given matrix. + /// + [DomName("setTransform")] + void SetTransform(Double a, Double b, Double c, Double d, Double e, Double f); + + /// + /// Resets the current transform to the identity. + /// + [DomName("resetTransform")] + void ResetTransform(); + + #endregion + + #region CanvasCompositing + + /// + /// Gets or sets the alpha applied to drawing, from 0 to 1. + /// + [DomName("globalAlpha")] + Double GlobalAlpha { get; set; } + + /// + /// Gets or sets the composite operation or blend mode, e.g., source-over. + /// + [DomName("globalCompositeOperation")] + String GlobalCompositeOperation { get; set; } + + #endregion + + #region CanvasImageSmoothing + + /// + /// Gets or sets if scaled images are smoothed. + /// + [DomName("imageSmoothingEnabled")] + Boolean ImageSmoothingEnabled { get; set; } + + /// + /// Gets or sets the quality of smoothing scaled images. + /// + [DomName("imageSmoothingQuality")] + ImageSmoothingQuality ImageSmoothingQuality { get; set; } + + #endregion + + #region CanvasFillStrokeStyles + + /// + /// Gets or sets the style of strokes: a color (as a string, serialized when read), + /// a , or a . + /// + [DomName("strokeStyle")] + Object StrokeStyle { get; set; } + + /// + /// Gets or sets the style of fills: a color (as a string, serialized when read), + /// a , or a . + /// + [DomName("fillStyle")] + Object FillStyle { get; set; } + + /// + /// Creates a linear gradient along the line between both points. + /// + [DomName("createLinearGradient")] + CanvasGradient CreateLinearGradient(Double x0, Double y0, Double x1, Double y1); + + /// + /// Creates a radial gradient between both circles. + /// + /// An IndexSizeError for a negative radius. + [DomName("createRadialGradient")] + CanvasGradient CreateRadialGradient(Double x0, Double y0, Double r0, Double x1, Double y1, Double r1); + + /// + /// Creates a conic gradient around the point. + /// + [DomName("createConicGradient")] + CanvasGradient CreateConicGradient(Double startAngle, Double x, Double y); + + /// + /// Creates a pattern of the image, which is repeated as given by the repetition + /// (repeat, repeat-x, repeat-y, no-repeat, or empty for repeat). + /// + /// A SyntaxError for an unknown repetition. + [DomName("createPattern")] + CanvasPattern? CreatePattern(CssImageValue image, String? repetition); + + #endregion + + #region CanvasShadowStyles + + /// + /// Gets or sets the horizontal offset of shadows. + /// + [DomName("shadowOffsetX")] + Double ShadowOffsetX { get; set; } + + /// + /// Gets or sets the vertical offset of shadows. + /// + [DomName("shadowOffsetY")] + Double ShadowOffsetY { get; set; } + + /// + /// Gets or sets the blur of shadows. + /// + [DomName("shadowBlur")] + Double ShadowBlur { get; set; } + + /// + /// Gets or sets the color of shadows (serialized when read). + /// + [DomName("shadowColor")] + String ShadowColor { get; set; } + + #endregion + + #region CanvasRect + + /// + /// Clears the rectangle to transparent black. + /// + [DomName("clearRect")] + void ClearRect(Double x, Double y, Double w, Double h); + + /// + /// Fills the rectangle with the fill style. + /// + [DomName("fillRect")] + void FillRect(Double x, Double y, Double w, Double h); + + /// + /// Strokes the rectangle with the stroke style. + /// + [DomName("strokeRect")] + void StrokeRect(Double x, Double y, Double w, Double h); + + #endregion + + #region CanvasDrawPath + + /// + /// Empties the current path. + /// + [DomName("beginPath")] + void BeginPath(); + + /// + /// Fills the current path with the fill style. + /// + [DomName("fill")] + void Fill(CanvasFillRule fillRule = CanvasFillRule.NonZero); + + /// + /// Fills the given path with the fill style. + /// + [DomName("fill")] + void Fill(Path2D path, CanvasFillRule fillRule = CanvasFillRule.NonZero); + + /// + /// Strokes the current path with the stroke style. + /// + [DomName("stroke")] + void Stroke(); + + /// + /// Strokes the given path with the stroke style. + /// + [DomName("stroke")] + void Stroke(Path2D path); + + /// + /// Intersects the clipping region with the current path. + /// + [DomName("clip")] + void Clip(CanvasFillRule fillRule = CanvasFillRule.NonZero); + + /// + /// Intersects the clipping region with the given path. + /// + [DomName("clip")] + void Clip(Path2D path, CanvasFillRule fillRule = CanvasFillRule.NonZero); + + /// + /// Checks if the point (unaffected by the current transform) is inside the current path. + /// + [DomName("isPointInPath")] + Boolean IsPointInPath(Double x, Double y, CanvasFillRule fillRule = CanvasFillRule.NonZero); + + /// + /// Checks if the point (unaffected by the current transform) is inside the given path. + /// + [DomName("isPointInPath")] + Boolean IsPointInPath(Path2D path, Double x, Double y, CanvasFillRule fillRule = CanvasFillRule.NonZero); + + /// + /// Checks if the point (unaffected by the current transform) is on the stroke of the current path. + /// + [DomName("isPointInStroke")] + Boolean IsPointInStroke(Double x, Double y); + + /// + /// Checks if the point (unaffected by the current transform) is on the stroke of the given path. + /// + [DomName("isPointInStroke")] + Boolean IsPointInStroke(Path2D path, Double x, Double y); + + #endregion + + #region CanvasDrawImage + + /// + /// Draws the image at its natural size at the given point. + /// + [DomName("drawImage")] + void DrawImage(CssImageValue image, Double dx, Double dy); + + /// + /// Draws the image into the given rectangle. + /// + [DomName("drawImage")] + void DrawImage(CssImageValue image, Double dx, Double dy, Double dw, Double dh); + + /// + /// Draws the source rectangle of the image into the destination rectangle. + /// + [DomName("drawImage")] + void DrawImage(CssImageValue image, Double sx, Double sy, Double sw, Double sh, Double dx, Double dy, Double dw, Double dh); + + #endregion + + #region CanvasPathDrawingStyles + + /// + /// Gets or sets the width of lines. + /// + [DomName("lineWidth")] + Double LineWidth { get; set; } + + /// + /// Gets or sets the shape of the ends of lines. + /// + [DomName("lineCap")] + CanvasLineCap LineCap { get; set; } + + /// + /// Gets or sets the shape of the corners of lines. + /// + [DomName("lineJoin")] + CanvasLineJoin LineJoin { get; set; } + + /// + /// Gets or sets the limit of the ratio of the miter length to half the line width. + /// + [DomName("miterLimit")] + Double MiterLimit { get; set; } + + /// + /// Sets the dash pattern of lines, which is repeated to have an even count. + /// + [DomName("setLineDash")] + void SetLineDash(IEnumerable segments); + + /// + /// Gets the dash pattern of lines. + /// + [DomName("getLineDash")] + Double[] GetLineDash(); + + /// + /// Gets or sets the offset of the dash pattern. + /// + [DomName("lineDashOffset")] + Double LineDashOffset { get; set; } + + #endregion + } +} diff --git a/src/AngleSharp.Css/Painting/IPaintRenderingContextFactory.cs b/src/AngleSharp.Css/Painting/IPaintRenderingContextFactory.cs new file mode 100644 index 00000000..b741fc77 --- /dev/null +++ b/src/AngleSharp.Css/Painting/IPaintRenderingContextFactory.cs @@ -0,0 +1,25 @@ +namespace AngleSharp.Css.Painting +{ + using System; + + /// + /// Creates the rendering contexts paint definitions draw with, e.g., one drawing into + /// a bitmap of a graphics library. Register an implementation as a service of the + /// configuration to replace the default one, which records the drawing operations + /// (). + /// + public interface IPaintRenderingContextFactory + { + /// + /// Creates a new rendering context for drawing a single paint image. + /// + /// The size of the image in CSS pixels. + /// + /// The number of device pixels per CSS pixel, by which the output bitmap should be + /// scaled for a crisp image. + /// + /// The options of the paint definition. + /// The rendering context, which is the result of drawing. + IPaintRenderingContext2D Create(PaintSize size, Double devicePixelRatio, PaintRenderingContext2DSettings settings); + } +} diff --git a/src/AngleSharp.Css/Painting/IPaintWorkletModuleLoader.cs b/src/AngleSharp.Css/Painting/IPaintWorkletModuleLoader.cs new file mode 100644 index 00000000..d359fea7 --- /dev/null +++ b/src/AngleSharp.Css/Painting/IPaintWorkletModuleLoader.cs @@ -0,0 +1,29 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Dom; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Loads the modules of paint worklets, i.e., runs a script in the global scope of a + /// paint worklet, which registers its paint definitions with registerPaint(). This is + /// the extension point for scripting engines (e.g., AngleSharp.Js): register an + /// implementation as a service of the configuration. Without one, addModule() fails + /// with a NotSupportedError, while paint definitions can still be registered directly. + /// https://www.w3.org/TR/css-paint-api-1/#paint-worklet + /// + public interface IPaintWorkletModuleLoader + { + /// + /// Fetches and runs the module in the given global scope. + /// + /// + /// The global scope to run the module in, which gives registerPaint(), the + /// devicePixelRatio, and the document the worklet belongs to. + /// + /// The (absolute) URL of the module. + /// The token to cancel loading. + /// The task completing once the module has been run. + Task LoadAsync(PaintWorkletGlobalScope scope, Url moduleUrl, CancellationToken cancellationToken); + } +} diff --git a/src/AngleSharp.Css/Painting/PaintCommand.cs b/src/AngleSharp.Css/Painting/PaintCommand.cs new file mode 100644 index 00000000..2cc277e6 --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintCommand.cs @@ -0,0 +1,50 @@ +namespace AngleSharp.Css.Painting +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + /// + /// A recorded operation of a rendering context or a path, named like the operation + /// of the canvas API (e.g., fillRect, or fillStyle for setting the fill style), with + /// the (validated and normalized) arguments it has been called with. Operations that + /// were ignored, e.g., for non-finite arguments, are not recorded. + /// + public sealed class PaintCommand + { + internal PaintCommand(String name, params Object[] arguments) + { + Name = name; + Arguments = arguments; + } + + /// + /// Gets the name of the operation, e.g., fillRect. + /// + public String Name { get; } + + /// + /// Gets the arguments of the operation, e.g., four numbers for fillRect, a string, + /// a gradient or a pattern for fillStyle, or a path for fill. + /// + public IReadOnlyList Arguments { get; } + + /// + /// Gets the operation as it would be written in script, e.g., fillRect(0, 0, 10, 10). + /// + public override String ToString() => + $"{Name}({String.Join(", ", Arguments.Select(Format))})"; + + private static String Format(Object argument) => argument switch + { + Double d => d.ToString("R", CultureInfo.InvariantCulture), + String s => "\"" + s + "\"", + Boolean b => b ? "true" : "false", + Double[] list => "[" + String.Join(", ", list.Select(m => m.ToString("R", CultureInfo.InvariantCulture))) + "]", + Enum e => "\"" + e.ToString().ToLowerInvariant() + "\"", + null => "null", + _ => argument.ToString() ?? String.Empty, + }; + } +} diff --git a/src/AngleSharp.Css/Painting/PaintDefinition.cs b/src/AngleSharp.Css/Painting/PaintDefinition.cs new file mode 100644 index 00000000..bc6fe93a --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintDefinition.cs @@ -0,0 +1,46 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.TypedOm; + using System; + using System.Collections.Generic; + + /// + /// Draws a paint image. + /// + /// The rendering context to draw with. + /// The size of the image. + /// The input properties of the element. + /// The arguments of the paint() function. + public delegate void PaintCallback(IPaintRenderingContext2D context, PaintSize size, IStylePropertyMapReadOnly properties, IReadOnlyList arguments); + + /// + /// A paint definition implemented in .NET by a callback, e.g., to provide + /// painters without any scripting engine. + /// + public sealed class PaintDefinition : IPaintDefinition + { + private readonly PaintCallback _paint; + + /// + /// Creates a new paint definition. + /// + /// The callback drawing the image. + public PaintDefinition(PaintCallback paint) + { + _paint = paint ?? throw new ArgumentNullException(nameof(paint)); + } + + /// + public IEnumerable InputProperties { get; set; } = Array.Empty(); + + /// + public IEnumerable InputArguments { get; set; } = Array.Empty(); + + /// + public PaintRenderingContext2DSettings ContextOptions { get; set; } = new(); + + /// + public void Paint(IPaintRenderingContext2D context, PaintSize size, IStylePropertyMapReadOnly properties, IReadOnlyList arguments) => + _paint.Invoke(context, size, properties, arguments); + } +} diff --git a/src/AngleSharp.Css/Painting/PaintImage.cs b/src/AngleSharp.Css/Painting/PaintImage.cs new file mode 100644 index 00000000..b4f4e34c --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintImage.cs @@ -0,0 +1,47 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.Values; + using System; + + /// + /// A drawn paint image: the rendering context the paint definition drew with, which + /// holds the output, e.g., the drawing operations of a + /// or the bitmap of a context created + /// by a custom . + /// + public sealed class PaintImage + { + internal PaintImage(CssPaintValue source, PaintSize size, Double devicePixelRatio, IPaintRenderingContext2D context) + { + Source = source; + Size = size; + DevicePixelRatio = devicePixelRatio; + Context = context; + } + + /// + /// Gets the paint() function the image was drawn for. + /// + public CssPaintValue Source { get; } + + /// + /// Gets the name of the paint definition that drew the image. + /// + public String Name => Source.PainterName; + + /// + /// Gets the size of the image in CSS pixels. + /// + public PaintSize Size { get; } + + /// + /// Gets the number of device pixels per CSS pixel the image was drawn for. + /// + public Double DevicePixelRatio { get; } + + /// + /// Gets the rendering context that has been drawn with, i.e., the output. + /// + public IPaintRenderingContext2D Context { get; } + } +} diff --git a/src/AngleSharp.Css/Painting/PaintImageExtensions.cs b/src/AngleSharp.Css/Painting/PaintImageExtensions.cs new file mode 100644 index 00000000..63a57721 --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintImageExtensions.cs @@ -0,0 +1,227 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.RenderTree; + using AngleSharp.Css.TypedOm; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Draws the images of paint() functions with the paint definitions registered in the + /// paint worklet of the document. AngleSharp.Css does no layout, so the size of the + /// image is given by the caller, e.g., a renderer that knows the box of the element. + /// https://www.w3.org/TR/css-paint-api-1/#drawing-an-image + /// + public static class PaintImageExtensions + { + // the name the arguments are matched and reified with, as for a custom property + private const String ArgumentName = "--paint-argument"; + + /// + /// Draws the image of the paint() function for the element. + /// + /// The element the image is drawn for. + /// The paint() function. + /// The size of the image in CSS pixels. + /// + /// The image or null if it is invalid, i.e., if no paint definition has been + /// registered under its name, its arguments do not match the input arguments, + /// or the paint definition failed. An invalid image is drawn as transparent black. + /// + public static PaintImage? DrawPaintImage(this IElement element, CssPaintValue paint, PaintSize size) => + element.DrawPaintImage(paint, size, null); + + /// + /// Draws the image of the paint() function for the element, whose input properties + /// are taken from the given computed style, e.g., the one of a render tree. + /// + /// The element the image is drawn for. + /// The paint() function. + /// The size of the image in CSS pixels. + /// The computed style of the element, if known. + /// The image or null if it is invalid. + public static PaintImage? DrawPaintImage(this IElement element, CssPaintValue paint, PaintSize size, ICssStyleDeclaration? computedStyle) + { + if (element is null) + throw new ArgumentNullException(nameof(element)); + + if (paint is null) + throw new ArgumentNullException(nameof(paint)); + + if (size is null) + throw new ArgumentNullException(nameof(size)); + + var document = element.Owner; + var worklet = document is not null ? PaintWorklet.Find(document) : null; + var registration = worklet?.Find(paint.PainterName); + + if (registration is null) + { + return null; + } + + var arguments = GetArguments(registration, paint); + + if (arguments is null) + { + return null; + } + + var style = computedStyle is not null ? ForScript(computedStyle) : GetComputedStyle(element); + var properties = new PaintInputPropertyMap(new StylePropertyMapReadOnly(style, document!.Context, true, document), registration.InputProperties); + var ratio = worklet!.DevicePixelRatio; + var factory = document.Context?.GetService(); + var options = new PaintRenderingContext2DSettings { Alpha = registration.ContextOptions.Alpha }; + + try + { + var context = factory?.Create(size, ratio, options) ?? new RecordingPaintRenderingContext2D(size, ratio, options); + registration.Definition.Paint(context, size, properties, arguments); + return new PaintImage(paint, size, ratio, context); + } + catch (Exception) + { + // a paint definition that throws gives an invalid image (as with script) + return null; + } + } + + /// + /// Draws the images of the paint() functions in the computed value of the property + /// of the element, e.g., of background-image, all with the same size. + /// + /// The element the images are drawn for. + /// The name of the property, e.g., background-image. + /// The size of the images in CSS pixels. + /// + /// One entry per paint() function in the order of the value, which is null if + /// the image is invalid. + /// + public static IReadOnlyList DrawPaintImages(this IElement element, String propertyName, PaintSize size) + { + if (element is null) + throw new ArgumentNullException(nameof(element)); + + return DrawPaintImages(element, GetComputedStyle(element), propertyName, size); + } + + /// + /// Draws the images of the paint() functions in the computed value of the property + /// of the rendered element, e.g., of background-image, all with the same size. + /// + /// The rendered element the images are drawn for. + /// The name of the property, e.g., background-image. + /// The size of the images in CSS pixels. + /// + /// One entry per paint() function in the order of the value, which is null if + /// the image is invalid. + /// + public static IReadOnlyList DrawPaintImages(this ElementRenderNode node, String propertyName, PaintSize size) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); + + return DrawPaintImages(node.Ref, ForScript(node.ComputedStyle), propertyName, size); + } + + /// + /// Gets the paint() functions of the value, e.g., of the layers of a background-image + /// or the options of an image-set. + /// + /// The value to search. + /// The paint() functions in the order of the value. + public static IEnumerable GetPaintValues(this ICssValue? value) + { + switch (value) + { + case CssPaintValue paint: + yield return paint; + break; + case ICssMultipleValue multiple: + foreach (var item in multiple) + { + foreach (var paint in item.GetPaintValues()) + { + yield return paint; + } + } + break; + case ICssFunctionValue function when function.Arguments is not null: + foreach (var argument in function.Arguments) + { + foreach (var paint in argument.GetPaintValues()) + { + yield return paint; + } + } + break; + } + } + + private static IReadOnlyList DrawPaintImages(IElement element, ICssStyleDeclaration style, String propertyName, PaintSize size) + { + if (propertyName is null) + throw new ArgumentNullException(nameof(propertyName)); + + var value = style.GetProperty(propertyName)?.RawValue; + return value.GetPaintValues().Select(paint => element.DrawPaintImage(paint, size, style)).ToArray(); + } + + private static ICssStyleDeclaration GetComputedStyle(IElement element) + { + var window = element.Owner?.DefaultView; + return window is not null ? window.GetComputedStyleOfScript(element) : ForScript(element.ComputeCurrentStyle()); + } + + // a property that was not declared has its initial value, as script sees it + private static ICssStyleDeclaration ForScript(ICssStyleDeclaration style) => + style is CssStyleDeclaration declaration ? declaration.WithInitialValues(null!) : style; + + private static IReadOnlyList? GetArguments(PaintRegistration registration, CssPaintValue paint) + { + var arguments = paint.Arguments; + var syntaxes = registration.ArgumentSyntaxes; + + // without input arguments, the arguments are given as written + if (syntaxes.Length == 0) + { + return arguments.Select(m => (CssStyleValue)CssUnparsedValue.FromText(m.CssText)).ToArray(); + } + + if (syntaxes.Length != arguments.Length) + { + return null; + } + + var result = new CssStyleValue[arguments.Length]; + + for (var i = 0; i < arguments.Length; i++) + { + var text = arguments[i].CssText; + var syntax = syntaxes[i]; + + if (syntax.IsUniversal) + { + result[i] = CssUnparsedValue.FromText(text); + continue; + } + + var argument = new CssPropertyRegistration(ArgumentName, syntax, false, null); + var value = argument.MatchDeclared(new CssAnyValue(text)); + + if (value is null) + { + return null; + } + + var values = CssStyleValueReifier.ReifyAll(ArgumentName, value, argument); + result[i] = values.Count == 1 ? values[0] : CssUnparsedValue.FromText(text); + } + + return result; + } + } +} diff --git a/src/AngleSharp.Css/Painting/PaintInputPropertyMap.cs b/src/AngleSharp.Css/Painting/PaintInputPropertyMap.cs new file mode 100644 index 00000000..11d8196a --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintInputPropertyMap.cs @@ -0,0 +1,55 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.TypedOm; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + /// + /// The typed computed style of an element limited to the input properties of a paint + /// definition: other properties are not in the map. + /// https://www.w3.org/TR/css-paint-api-1/#invoke-a-paint-callback + /// + sealed class PaintInputPropertyMap : IStylePropertyMapReadOnly + { + private readonly IStylePropertyMapReadOnly _computed; + private readonly String[] _names; + + public PaintInputPropertyMap(IStylePropertyMapReadOnly computed, String[] names) + { + _computed = computed; + _names = names; + } + + public Int32 Size => _names.Count(name => _computed.GetAll(name).Count > 0); + + public CssStyleValue? Get(String property) => Find(property) is String name ? _computed.Get(name) : null; + + public IReadOnlyList GetAll(String property) => + Find(property) is String name ? _computed.GetAll(name) : Array.Empty(); + + public Boolean Has(String property) => Find(property) is String name && _computed.Has(name); + + public IEnumerator>> GetEnumerator() + { + foreach (var name in _names) + { + var values = _computed.GetAll(name); + + if (values.Count > 0) + { + yield return new KeyValuePair>(name, values); + } + } + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + private String? Find(String property) + { + var name = TypedOmProperties.Normalize(property); + return Array.IndexOf(_names, name) >= 0 ? name : null; + } + } +} diff --git a/src/AngleSharp.Css/Painting/PaintMatrix.cs b/src/AngleSharp.Css/Painting/PaintMatrix.cs new file mode 100644 index 00000000..a4e1eb11 --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintMatrix.cs @@ -0,0 +1,84 @@ +namespace AngleSharp.Css.Painting +{ + using System; + + /// + /// A 2D affine transform (a, b, c, d, e, f) as used by the canvas API, which maps + /// (x, y) to (a x + c y + e, b x + d y + f). + /// + readonly struct PaintMatrix + { + public static readonly PaintMatrix Identity = new(1, 0, 0, 1, 0, 0); + + public PaintMatrix(Double a, Double b, Double c, Double d, Double e, Double f) + { + A = a; + B = b; + C = c; + D = d; + E = e; + F = f; + } + + public Double A { get; } + + public Double B { get; } + + public Double C { get; } + + public Double D { get; } + + public Double E { get; } + + public Double F { get; } + + public Double Determinant => A * D - B * C; + + public Boolean IsInvertible => Determinant != 0 && !Double.IsNaN(Determinant) && !Double.IsInfinity(Determinant); + + /// + /// Gets the factor lengths are scaled with (exactly for a uniform scale). + /// + public Double Scale => Math.Sqrt(Math.Abs(Determinant)); + + /// + /// Gets the transform that first applies the other one and then this one. + /// + public PaintMatrix Multiply(PaintMatrix m) => new( + A * m.A + C * m.B, + B * m.A + D * m.B, + A * m.C + C * m.D, + B * m.C + D * m.D, + A * m.E + C * m.F + E, + B * m.E + D * m.F + F); + + public PaintMatrix Invert() + { + var det = Determinant; + return new( + D / det, + -B / det, + -C / det, + A / det, + (C * F - D * E) / det, + (B * E - A * F) / det); + } + + public PaintPoint Apply(Double x, Double y) => new(A * x + C * y + E, B * x + D * y + F); + + public PaintPoint Apply(PaintPoint p) => Apply(p.X, p.Y); + } + + readonly struct PaintPoint + { + public PaintPoint(Double x, Double y) + { + X = x; + Y = y; + } + + public Double X { get; } + + public Double Y { get; } + } +} diff --git a/src/AngleSharp.Css/Painting/PaintRenderingContext2DSettings.cs b/src/AngleSharp.Css/Painting/PaintRenderingContext2DSettings.cs new file mode 100644 index 00000000..1585a2d9 --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintRenderingContext2DSettings.cs @@ -0,0 +1,20 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using System; + + /// + /// The options of the rendering context a paint definition draws with. + /// https://www.w3.org/TR/css-paint-api-1/#dictdef-paintrenderingcontext2dsettings + /// + [DomName("PaintRenderingContext2DSettings")] + public sealed class PaintRenderingContext2DSettings + { + /// + /// Gets or sets if the image has an alpha channel. Without one, + /// the image is opaque. True by default. + /// + [DomName("alpha")] + public Boolean Alpha { get; set; } = true; + } +} diff --git a/src/AngleSharp.Css/Painting/PaintSize.cs b/src/AngleSharp.Css/Painting/PaintSize.cs new file mode 100644 index 00000000..0361501f --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintSize.cs @@ -0,0 +1,44 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using System; + + /// + /// The size of the paint image to draw (the "paint size" of the specification) in + /// CSS pixels, e.g., the size of the background positioning area of a background. + /// AngleSharp.Css does no layout, so the size is given by whoever draws the image. + /// https://www.w3.org/TR/css-paint-api-1/#paintsize + /// + [DomName("PaintSize")] + public sealed class PaintSize + { + /// + /// Creates a new paint size. + /// + /// The width in CSS pixels. + /// The height in CSS pixels. + public PaintSize(Double width, Double height) + { + if (Double.IsNaN(width) || Double.IsInfinity(width) || width < 0) + throw new ArgumentOutOfRangeException(nameof(width)); + + if (Double.IsNaN(height) || Double.IsInfinity(height) || height < 0) + throw new ArgumentOutOfRangeException(nameof(height)); + + Width = width; + Height = height; + } + + /// + /// Gets the width in CSS pixels. + /// + [DomName("width")] + public Double Width { get; } + + /// + /// Gets the height in CSS pixels. + /// + [DomName("height")] + public Double Height { get; } + } +} diff --git a/src/AngleSharp.Css/Painting/PaintWorklet.cs b/src/AngleSharp.Css/Painting/PaintWorklet.cs new file mode 100644 index 00000000..12bb2806 --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintWorklet.cs @@ -0,0 +1,262 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using AngleSharp.Css.TypedOm; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; + + /// + /// The paint worklet of a document (CSS.paintWorklet), which is the registry of its + /// paint definitions. Modules (scripts calling registerPaint()) are run by the + /// of the configuration, e.g., one provided + /// by a scripting engine. Paint definitions implemented in .NET can be registered + /// directly, without any scripting engine. + /// https://www.w3.org/TR/css-paint-api-1/#paint-worklet + /// + [DomName("Worklet")] + public sealed class PaintWorklet + { + #region Fields + + private static readonly ConditionalWeakTable Worklets = new(); + + private readonly Object _lock = new(); + private Dictionary _registrations = new(StringComparer.Ordinal); + + #endregion + + #region ctor + + private PaintWorklet(IDocument document) + { + Document = document; + GlobalScope = new PaintWorkletGlobalScope(this); + } + + /// + /// Gets the paint worklet of the document, which is created when it is first used. + /// + internal static PaintWorklet For(IDocument document) => + Worklets.GetValue(document, doc => new PaintWorklet(doc)); + + /// + /// Gets the paint worklet of the document, if it has been used. + /// + internal static PaintWorklet? Find(IDocument document) => + Worklets.TryGetValue(document, out var worklet) ? worklet : null; + + #endregion + + #region Properties + + /// + /// Gets the document the paint worklet belongs to. + /// + public IDocument Document { get; } + + /// + /// Gets the global scope modules run in. + /// + public PaintWorkletGlobalScope GlobalScope { get; } + + /// + /// Gets the number of device pixels per CSS pixel, which is the resolution of the + /// render device divided by 96 (or 1 without a render device). + /// + public Double DevicePixelRatio + { + get + { + var resolution = Document.Context?.GetService()?.Resolution ?? 0; + return resolution > 0 ? resolution / 96.0 : 1.0; + } + } + + /// + /// Gets the names of the registered paint definitions. + /// + public IReadOnlyCollection Names => _registrations.Keys.ToArray(); + + #endregion + + #region Methods + + /// + /// Loads the module, i.e., runs the script, which registers paint definitions, + /// with the of the configuration. + /// + /// The URL of the module, relative to the document. + /// The token to cancel loading. + /// + /// The task completing once the module has been run, which fails with a + /// NotSupportedError if no module loader has been registered, or a + /// SyntaxError if the URL is not valid. + /// + [DomName("addModule")] + public Task AddModule(String moduleUrl, CancellationToken cancellationToken = default) + { + if (moduleUrl is null) + throw new ArgumentNullException(nameof(moduleUrl)); + + var baseUrl = Document.BaseUrl; + var url = baseUrl is not null ? new Url(baseUrl, moduleUrl) : Url.Create(moduleUrl); + + if (url.IsInvalid) + { + return Task.FromException(new DomException(DomError.Syntax)); + } + + var loader = Document.Context?.GetService(); + + if (loader is null) + { + return Task.FromException(new DomException(DomError.NotSupported)); + } + + return loader.LoadAsync(GlobalScope, url, cancellationToken); + } + + /// + /// Registers a paint definition under the given name (registerPaint() of the + /// global scope), which is used by the paint() functions with this name from now + /// on. Unknown input properties are ignored. + /// + /// The name of the paint definition. + /// The paint definition. + /// + /// The TypeError for an empty name or a syntax of the input arguments that is not valid. + /// + /// + /// An InvalidModificationError if the name has been registered already. + /// + public void RegisterPaint(String name, IPaintDefinition definition) + { + if (name is null) + throw new ArgumentNullException(nameof(name)); + + if (definition is null) + throw new ArgumentNullException(nameof(definition)); + + if (name.Length == 0) + throw new ArgumentException("The name of a paint definition must not be empty.", nameof(name)); + + if (Contains(name)) + throw new DomException(DomError.InvalidModification); + + var registration = PaintRegistration.Create(Document.Context, name, definition); + + lock (_lock) + { + if (_registrations.ContainsKey(name)) + throw new DomException(DomError.InvalidModification); + + // replaced rather than changed, as images may be drawn meanwhile + _registrations = new Dictionary(_registrations, StringComparer.Ordinal) + { + [name] = registration, + }; + } + } + + /// + /// Checks if a paint definition has been registered under the given name. + /// + /// The name of the paint definition. + /// True if one has been registered, otherwise false. + public Boolean Contains(String name) => name is not null && _registrations.ContainsKey(name); + + /// + /// Gets the paint definition registered under the given name. + /// + /// The name of the paint definition. + /// The paint definition or null if none has been registered. + public IPaintDefinition? Get(String name) => Find(name)?.Definition; + + /// + /// Gets the input properties of the paint definition as they have been registered, + /// i.e., without unknown properties. + /// + /// The name of the paint definition. + /// The input properties or null if no paint definition has been registered. + public IReadOnlyList? GetInputProperties(String name) => Find(name)?.InputProperties; + + internal PaintRegistration? Find(String name) => + name is not null && _registrations.TryGetValue(name, out var registration) ? registration : null; + + #endregion + } + + /// + /// A registered paint definition with what has been read from it at registration. + /// + sealed class PaintRegistration + { + private PaintRegistration(String name, IPaintDefinition definition, String[] inputProperties, CssPropertySyntax[] argumentSyntaxes, PaintRenderingContext2DSettings contextOptions) + { + Name = name; + Definition = definition; + InputProperties = inputProperties; + ArgumentSyntaxes = argumentSyntaxes; + ContextOptions = contextOptions; + } + + public static PaintRegistration Create(IBrowsingContext? context, String name, IPaintDefinition definition) + { + var inputProperties = new List(); + + foreach (var property in definition.InputProperties ?? Enumerable.Empty()) + { + if (property is not null && IsSupported(context, property)) + { + var normalized = TypedOmProperties.Normalize(property); + + if (!inputProperties.Contains(normalized)) + { + inputProperties.Add(normalized); + } + } + } + + var syntaxes = (definition.InputArguments ?? Enumerable.Empty()) + .Select(text => CssPropertySyntax.Parse(text ?? String.Empty) ?? + throw new ArgumentException($"The syntax '{text}' of an input argument is not valid.", nameof(definition))) + .ToArray(); + var options = definition.ContextOptions ?? new PaintRenderingContext2DSettings(); + return new PaintRegistration(name, definition, inputProperties.ToArray(), syntaxes, new PaintRenderingContext2DSettings { Alpha = options.Alpha }); + } + + public String Name { get; } + + public IPaintDefinition Definition { get; } + + public String[] InputProperties { get; } + + public CssPropertySyntax[] ArgumentSyntaxes { get; } + + public PaintRenderingContext2DSettings ContextOptions { get; } + + private static Boolean IsSupported(IBrowsingContext? context, String property) + { + if (CssPropertyRegistration.IsCustomPropertyName(property)) + { + return true; + } + + try + { + TypedOmProperties.GetInfo(context, property.ToLowerInvariant()); + return true; + } + catch (ArgumentException) + { + return false; + } + } + } +} diff --git a/src/AngleSharp.Css/Painting/PaintWorkletGlobalScope.cs b/src/AngleSharp.Css/Painting/PaintWorkletGlobalScope.cs new file mode 100644 index 00000000..ad8f4ed0 --- /dev/null +++ b/src/AngleSharp.Css/Painting/PaintWorkletGlobalScope.cs @@ -0,0 +1,53 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using AngleSharp.Dom; + using System; + + /// + /// The global scope the modules of a paint worklet run in, which is what a scripting + /// engine exposes to a module: registerPaint() and devicePixelRatio. + /// https://www.w3.org/TR/css-paint-api-1/#paintworkletglobalscope + /// + [DomName("PaintWorkletGlobalScope")] + public sealed class PaintWorkletGlobalScope + { + internal PaintWorkletGlobalScope(PaintWorklet worklet) + { + Worklet = worklet; + } + + /// + /// Gets the paint worklet the scope belongs to. + /// + public PaintWorklet Worklet { get; } + + /// + /// Gets the document the paint worklet belongs to, e.g., to fetch modules with + /// its browsing context. + /// + public IDocument Document => Worklet.Document; + + /// + /// Gets the number of device pixels per CSS pixel, which is the resolution of the + /// render device divided by 96 (or 1 without a render device). + /// + [DomName("devicePixelRatio")] + public Double DevicePixelRatio => Worklet.DevicePixelRatio; + + /// + /// Registers a paint definition under the given name, which is used by the paint() + /// functions with this name from now on. + /// + /// The name of the paint definition. + /// The paint definition. + /// + /// The TypeError for an empty name or a syntax of the input arguments that is not valid. + /// + /// + /// An InvalidModificationError if the name has been registered already. + /// + [DomName("registerPaint")] + public void RegisterPaint(String name, IPaintDefinition definition) => Worklet.RegisterPaint(name, definition); + } +} diff --git a/src/AngleSharp.Css/Painting/Path2D.cs b/src/AngleSharp.Css/Painting/Path2D.cs new file mode 100644 index 00000000..51ecf501 --- /dev/null +++ b/src/AngleSharp.Css/Painting/Path2D.cs @@ -0,0 +1,119 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + + /// + /// A path that can be built once and then filled, stroked, or used for clipping and + /// hit testing. Its operations are recorded, e.g., to replay them in a renderer. + /// https://html.spec.whatwg.org/multipage/canvas.html#path2d-objects + /// + [DomName("Path2D")] + public sealed class Path2D : ICanvasPath + { + private readonly List _commands; + private readonly CanvasPathBuilder _builder; + + /// + /// Creates a new empty path. + /// + [DomConstructor] + public Path2D() + { + _commands = new List(); + _builder = new CanvasPathBuilder(_commands, new PathGeometry()); + } + + /// + /// Creates a copy of the given path. + /// + /// The path to copy. + [DomConstructor] + public Path2D(Path2D path) + { + if (path is null) + throw new ArgumentNullException(nameof(path)); + + _commands = new List(path._commands); + _builder = new CanvasPathBuilder(_commands, path.Geometry.Clone()); + } + + /// + /// Creates a path of the given SVG path data, which is kept as it is (as a command + /// named d) for the renderer. The data does not contribute to hit testing. + /// + /// The SVG path data, e.g., M 0 0 L 10 10. + [DomConstructor] + public Path2D(String d) + : this() + { + if (d is null) + throw new ArgumentNullException(nameof(d)); + + _commands.Add(new PaintCommand("d", d)); + } + + /// + /// Gets the recorded operations that built the path. + /// + public IReadOnlyList Commands => _commands; + + internal PathGeometry Geometry => _builder.Geometry; + + /// + /// Adds the subpaths of the given path. + /// + /// The path to add. + [DomName("addPath")] + public void AddPath(Path2D path) + { + if (path is null) + throw new ArgumentNullException(nameof(path)); + + Geometry.Append(path.Geometry, PaintMatrix.Identity); + _commands.Add(new PaintCommand("addPath", new Path2D(path))); + } + + /// + public void ClosePath() => _builder.ClosePath(); + + /// + public void MoveTo(Double x, Double y) => _builder.MoveTo(x, y, PaintMatrix.Identity); + + /// + public void LineTo(Double x, Double y) => _builder.LineTo(x, y, PaintMatrix.Identity); + + /// + public void QuadraticCurveTo(Double cpx, Double cpy, Double x, Double y) => + _builder.QuadraticCurveTo(cpx, cpy, x, y, PaintMatrix.Identity); + + /// + public void BezierCurveTo(Double cp1x, Double cp1y, Double cp2x, Double cp2y, Double x, Double y) => + _builder.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y, PaintMatrix.Identity); + + /// + public void ArcTo(Double x1, Double y1, Double x2, Double y2, Double radius) => + _builder.ArcTo(x1, y1, x2, y2, radius, PaintMatrix.Identity); + + /// + public void Rect(Double x, Double y, Double w, Double h) => _builder.Rect(x, y, w, h, PaintMatrix.Identity); + + /// + public void RoundRect(Double x, Double y, Double w, Double h, params Double[] radii) => + _builder.RoundRect(x, y, w, h, radii, PaintMatrix.Identity); + + /// + public void Arc(Double x, Double y, Double radius, Double startAngle, Double endAngle, Boolean counterclockwise = false) => + _builder.Arc(x, y, radius, startAngle, endAngle, counterclockwise, PaintMatrix.Identity); + + /// + public void Ellipse(Double x, Double y, Double radiusX, Double radiusY, Double rotation, Double startAngle, Double endAngle, Boolean counterclockwise = false) => + _builder.Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise, PaintMatrix.Identity); + + /// + /// Gets the operations of the path, e.g., Path2D(moveTo(0, 0), lineTo(10, 10)). + /// + public override String ToString() => $"Path2D({String.Join(", ", _commands)})"; + } +} diff --git a/src/AngleSharp.Css/Painting/PathGeometry.cs b/src/AngleSharp.Css/Painting/PathGeometry.cs new file mode 100644 index 00000000..3c0e7b0a --- /dev/null +++ b/src/AngleSharp.Css/Painting/PathGeometry.cs @@ -0,0 +1,394 @@ +namespace AngleSharp.Css.Painting +{ + using System; + using System.Collections.Generic; + + /// + /// The geometry of a path, flattened to polygons, which is only used for hit testing + /// (isPointInPath and isPointInStroke). The points are given in the coordinates of + /// the path, i.e., after applying the transform the operations were called with. + /// + sealed class PathGeometry + { + private const Int32 CurveSegments = 16; + private const Int32 CircleSegments = 64; + private const Double Epsilon = 1e-9; + + private readonly List _subpaths = new(); + private Boolean _needsNewSubpath = true; + + public Boolean IsEmpty => _subpaths.Count == 0; + + public PathGeometry Clone() + { + var clone = new PathGeometry(); + clone.Append(this, PaintMatrix.Identity); + return clone; + } + + public void Clear() + { + _subpaths.Clear(); + _needsNewSubpath = true; + } + + public void Append(PathGeometry other, PaintMatrix m) + { + foreach (var subpath in other._subpaths) + { + var copy = new SubPath { Closed = subpath.Closed }; + + foreach (var point in subpath.Points) + { + copy.Points.Add(m.Apply(point)); + } + + _subpaths.Add(copy); + } + + _needsNewSubpath = _needsNewSubpath && other._needsNewSubpath; + } + + #region Building + + public void MoveTo(PaintPoint p) + { + var subpath = new SubPath(); + subpath.Points.Add(p); + _subpaths.Add(subpath); + _needsNewSubpath = false; + } + + public void LineTo(PaintPoint p) + { + if (_needsNewSubpath) + { + MoveTo(p); + } + else + { + Current.Points.Add(p); + } + } + + public void ClosePath() + { + if (!_needsNewSubpath && _subpaths.Count > 0) + { + var current = Current; + current.Closed = true; + MoveTo(current.Points[0]); + } + } + + public void QuadraticCurveTo(PaintPoint cp, PaintPoint end) + { + EnsureSubpath(cp); + var start = Last; + + for (var i = 1; i <= CurveSegments; i++) + { + var t = (Double)i / CurveSegments; + var u = 1 - t; + LineTo(new PaintPoint( + u * u * start.X + 2 * u * t * cp.X + t * t * end.X, + u * u * start.Y + 2 * u * t * cp.Y + t * t * end.Y)); + } + } + + public void BezierCurveTo(PaintPoint cp1, PaintPoint cp2, PaintPoint end) + { + EnsureSubpath(cp1); + var start = Last; + + for (var i = 1; i <= CurveSegments; i++) + { + var t = (Double)i / CurveSegments; + var u = 1 - t; + LineTo(new PaintPoint( + u * u * u * start.X + 3 * u * u * t * cp1.X + 3 * u * t * t * cp2.X + t * t * t * end.X, + u * u * u * start.Y + 3 * u * u * t * cp1.Y + 3 * u * t * t * cp2.Y + t * t * t * end.Y)); + } + } + + public void ArcTo(Double x1, Double y1, Double x2, Double y2, Double radius, PaintMatrix m) + { + EnsureSubpath(m.Apply(x1, y1)); + + if (!m.IsInvertible) + { + LineTo(m.Apply(x1, y1)); + return; + } + + var p0 = m.Invert().Apply(Last); + var v1x = p0.X - x1; + var v1y = p0.Y - y1; + var v2x = x2 - x1; + var v2y = y2 - y1; + var l1 = Math.Sqrt(v1x * v1x + v1y * v1y); + var l2 = Math.Sqrt(v2x * v2x + v2y * v2y); + var cross = v1x * v2y - v1y * v2x; + + // the same points, no radius, or a straight line: just a line to the first point + if (l1 < Epsilon || l2 < Epsilon || radius == 0 || Math.Abs(cross) < Epsilon * l1 * l2) + { + LineTo(m.Apply(x1, y1)); + return; + } + + var u1x = v1x / l1; + var u1y = v1y / l1; + var u2x = v2x / l2; + var u2y = v2y / l2; + var theta = Math.Acos(Math.Max(-1, Math.Min(1, u1x * u2x + u1y * u2y))); + var distance = radius / Math.Tan(theta / 2); + var bx = u1x + u2x; + var by = u1y + u2y; + var bl = Math.Sqrt(bx * bx + by * by); + var centerDistance = radius / Math.Sin(theta / 2); + var cx = x1 + bx / bl * centerDistance; + var cy = y1 + by / bl * centerDistance; + var t1x = x1 + u1x * distance; + var t1y = y1 + u1y * distance; + var t2x = x1 + u2x * distance; + var t2y = y1 + u2y * distance; + var start = Math.Atan2(t1y - cy, t1x - cx); + var end = Math.Atan2(t2y - cy, t2x - cx); + Ellipse(cx, cy, radius, radius, 0, start, end, cross > 0, m); + } + + public void Ellipse(Double x, Double y, Double rx, Double ry, Double rotation, Double start, Double end, Boolean counterclockwise, PaintMatrix m) + { + var sweep = GetSweep(start, end, counterclockwise); + var segments = Math.Max(1, (Int32)Math.Ceiling(Math.Abs(sweep) / (2 * Math.PI) * CircleSegments)); + var cos = Math.Cos(rotation); + var sin = Math.Sin(rotation); + + for (var i = 0; i <= segments; i++) + { + var t = start + sweep * i / segments; + var px = rx * Math.Cos(t); + var py = ry * Math.Sin(t); + var point = m.Apply(x + px * cos - py * sin, y + px * sin + py * cos); + + // the arc is connected to the current subpath, if there is one + if (i == 0) + { + LineTo(point); + } + else + { + Current.Points.Add(point); + } + } + } + + public void Rect(Double x, Double y, Double w, Double h, PaintMatrix m) + { + MoveTo(m.Apply(x, y)); + Current.Points.Add(m.Apply(x + w, y)); + Current.Points.Add(m.Apply(x + w, y + h)); + Current.Points.Add(m.Apply(x, y + h)); + Current.Closed = true; + MoveTo(m.Apply(x, y)); + } + + /// + /// Adds the rectangle with the (normalized) radii of the top-left, top-right, + /// bottom-right, and bottom-left corners. + /// + public void RoundRect(Double x, Double y, Double w, Double h, Double[] radii, PaintMatrix m) + { + var tl = radii[0]; + var tr = radii[1]; + var br = radii[2]; + var bl = radii[3]; + + // a negative size flips the rectangle, and the corners with it + if (w < 0) + { + x += w; + w = -w; + (tl, tr) = (tr, tl); + (bl, br) = (br, bl); + } + + if (h < 0) + { + y += h; + h = -h; + (tl, bl) = (bl, tl); + (tr, br) = (br, tr); + } + + // overlapping corners are scaled down + var scale = Math.Min(1, Math.Min( + Math.Min(Ratio(w, tl + tr), Ratio(h, tr + br)), + Math.Min(Ratio(w, bl + br), Ratio(h, tl + bl)))); + tl *= scale; + tr *= scale; + br *= scale; + bl *= scale; + + MoveTo(m.Apply(x + tl, y)); + Corner(x + w - tr, y + tr, tr, -Math.PI / 2, m); + Corner(x + w - br, y + h - br, br, 0, m); + Corner(x + bl, y + h - bl, bl, Math.PI / 2, m); + Corner(x + tl, y + tl, tl, Math.PI, m); + Current.Closed = true; + MoveTo(m.Apply(x, y)); + } + + private void Corner(Double cx, Double cy, Double r, Double start, PaintMatrix m) + { + const Int32 segments = CircleSegments / 4; + + for (var i = 0; i <= segments; i++) + { + var t = start + Math.PI / 2 * i / segments; + Current.Points.Add(m.Apply(cx + r * Math.Cos(t), cy + r * Math.Sin(t))); + + if (r == 0) + { + break; + } + } + } + + private static Double Ratio(Double length, Double sum) => sum > 0 ? length / sum : 1; + + private static Double GetSweep(Double start, Double end, Boolean counterclockwise) + { + const Double Tau = 2 * Math.PI; + + if (!counterclockwise && end - start >= Tau) + { + return Tau; + } + else if (counterclockwise && start - end >= Tau) + { + return -Tau; + } + + var sweep = (end - start) % Tau; + + if (!counterclockwise && sweep < 0) + { + sweep += Tau; + } + else if (counterclockwise && sweep > 0) + { + sweep -= Tau; + } + + return sweep; + } + + private void EnsureSubpath(PaintPoint p) + { + if (_needsNewSubpath) + { + MoveTo(p); + } + } + + private SubPath Current => _subpaths[_subpaths.Count - 1]; + + private PaintPoint Last => Current.Points[Current.Points.Count - 1]; + + #endregion + + #region Hit Testing + + /// + /// Checks if the point is inside the area of the path, where each subpath is + /// closed implicitly. Points on the path are inside. + /// + public Boolean Contains(PaintPoint p, CanvasFillRule rule) + { + var winding = 0; + var crossings = 0; + + foreach (var subpath in _subpaths) + { + var points = subpath.Points; + + for (var i = 0; i < points.Count; i++) + { + var a = points[i]; + var b = points[(i + 1) % points.Count]; + + if (DistanceToSegment(p, a, b) < Epsilon) + { + return true; + } + + if (a.Y <= p.Y) + { + if (b.Y > p.Y && IsLeft(a, b, p) > 0) + { + winding++; + crossings++; + } + } + else if (b.Y <= p.Y && IsLeft(a, b, p) < 0) + { + winding--; + crossings++; + } + } + } + + return rule == CanvasFillRule.EvenOdd ? crossings % 2 == 1 : winding != 0; + } + + /// + /// Checks if the point is on a line of the path with the given width. The joins, + /// caps and dashes of the lines are not considered. + /// + public Boolean StrokeContains(PaintPoint p, Double width) + { + var half = width / 2; + + foreach (var subpath in _subpaths) + { + var points = subpath.Points; + var count = subpath.Closed ? points.Count : points.Count - 1; + + for (var i = 0; i < count; i++) + { + if (DistanceToSegment(p, points[i], points[(i + 1) % points.Count]) <= half) + { + return true; + } + } + } + + return false; + } + + private static Double IsLeft(PaintPoint a, PaintPoint b, PaintPoint p) => + (b.X - a.X) * (p.Y - a.Y) - (p.X - a.X) * (b.Y - a.Y); + + private static Double DistanceToSegment(PaintPoint p, PaintPoint a, PaintPoint b) + { + var dx = b.X - a.X; + var dy = b.Y - a.Y; + var length = dx * dx + dy * dy; + var t = length > 0 ? Math.Max(0, Math.Min(1, ((p.X - a.X) * dx + (p.Y - a.Y) * dy) / length)) : 0; + var x = a.X + t * dx - p.X; + var y = a.Y + t * dy - p.Y; + return Math.Sqrt(x * x + y * y); + } + + #endregion + + private sealed class SubPath + { + public List Points { get; } = new(); + + public Boolean Closed { get; set; } + } + } +} diff --git a/src/AngleSharp.Css/Painting/RecordingPaintRenderingContext2D.cs b/src/AngleSharp.Css/Painting/RecordingPaintRenderingContext2D.cs new file mode 100644 index 00000000..9e420da6 --- /dev/null +++ b/src/AngleSharp.Css/Painting/RecordingPaintRenderingContext2D.cs @@ -0,0 +1,708 @@ +namespace AngleSharp.Css.Painting +{ + using AngleSharp.Css.TypedOm; + using AngleSharp.Dom; + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// The default rendering context of paint definitions, which draws nothing but records + /// the operations (a display list), so that any renderer can replay them, e.g., onto a + /// bitmap of a graphics library. It keeps the drawing state (styles, transform, path) + /// as the canvas API does, so reading a style gives what has been set, invalid values + /// are ignored, and hit testing works on the current path. The coordinates are CSS + /// pixels, i.e., the device pixel ratio is left to the renderer. + /// + public sealed class RecordingPaintRenderingContext2D : IPaintRenderingContext2D + { + #region Fields + + private static readonly HashSet CompositeOperations = new(StringComparer.Ordinal) + { + "source-over", "source-in", "source-out", "source-atop", + "destination-over", "destination-in", "destination-out", "destination-atop", + "lighter", "copy", "xor", + "normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", + "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", + "saturation", "color", "luminosity", + }; + + private static readonly HashSet Repetitions = new(StringComparer.Ordinal) + { + "repeat", "repeat-x", "repeat-y", "no-repeat", + }; + + private readonly List _commands = new(); + private readonly Stack _stack = new(); + private readonly CanvasPathBuilder _path; + private DrawingState _state = new(); + + #endregion + + #region ctor + + /// + /// Creates a new recording context. + /// + /// The size of the image in CSS pixels. + /// The number of device pixels per CSS pixel. + /// The options of the paint definition, if any. + public RecordingPaintRenderingContext2D(PaintSize size, Double devicePixelRatio = 1, PaintRenderingContext2DSettings? settings = null) + { + Size = size ?? throw new ArgumentNullException(nameof(size)); + DevicePixelRatio = devicePixelRatio; + Settings = settings ?? new PaintRenderingContext2DSettings(); + _path = new CanvasPathBuilder(_commands, new PathGeometry()); + } + + #endregion + + #region Properties + + /// + /// Gets the size of the image in CSS pixels. + /// + public PaintSize Size { get; } + + /// + /// Gets the number of device pixels per CSS pixel the image is drawn for. + /// + public Double DevicePixelRatio { get; } + + /// + /// Gets the options of the paint definition, e.g., if the image is opaque. + /// + public PaintRenderingContext2DSettings Settings { get; } + + /// + /// Gets the recorded operations in the order they have been called. + /// + public IReadOnlyList Commands => _commands; + + #endregion + + #region CanvasState + + /// + public void Save() + { + _stack.Push(_state.Clone()); + Record("save"); + } + + /// + public void Restore() + { + if (_stack.Count > 0) + { + _state = _stack.Pop(); + Record("restore"); + } + } + + /// + public void Reset() + { + // nothing drawn before is visible anymore, so there is nothing to replay + _commands.Clear(); + _stack.Clear(); + _path.Geometry.Clear(); + _state = new DrawingState(); + } + + #endregion + + #region CanvasTransform + + /// + public void Scale(Double x, Double y) + { + if (Finite(x, y)) + { + _state.Transform = _state.Transform.Multiply(new PaintMatrix(x, 0, 0, y, 0, 0)); + Record("scale", x, y); + } + } + + /// + public void Rotate(Double angle) + { + if (Finite(angle)) + { + var cos = Math.Cos(angle); + var sin = Math.Sin(angle); + _state.Transform = _state.Transform.Multiply(new PaintMatrix(cos, sin, -sin, cos, 0, 0)); + Record("rotate", angle); + } + } + + /// + public void Translate(Double x, Double y) + { + if (Finite(x, y)) + { + _state.Transform = _state.Transform.Multiply(new PaintMatrix(1, 0, 0, 1, x, y)); + Record("translate", x, y); + } + } + + /// + public void Transform(Double a, Double b, Double c, Double d, Double e, Double f) + { + if (Finite(a, b, c, d, e, f)) + { + _state.Transform = _state.Transform.Multiply(new PaintMatrix(a, b, c, d, e, f)); + Record("transform", a, b, c, d, e, f); + } + } + + /// + public void SetTransform(Double a, Double b, Double c, Double d, Double e, Double f) + { + if (Finite(a, b, c, d, e, f)) + { + _state.Transform = new PaintMatrix(a, b, c, d, e, f); + Record("setTransform", a, b, c, d, e, f); + } + } + + /// + public void ResetTransform() + { + _state.Transform = PaintMatrix.Identity; + Record("resetTransform"); + } + + #endregion + + #region CanvasCompositing + + /// + public Double GlobalAlpha + { + get => _state.GlobalAlpha; + set + { + if (Finite(value) && value >= 0 && value <= 1) + { + _state.GlobalAlpha = value; + Record("globalAlpha", value); + } + } + } + + /// + public String GlobalCompositeOperation + { + get => _state.GlobalCompositeOperation; + set + { + if (value is not null && CompositeOperations.Contains(value)) + { + _state.GlobalCompositeOperation = value; + Record("globalCompositeOperation", value); + } + } + } + + #endregion + + #region CanvasImageSmoothing + + /// + public Boolean ImageSmoothingEnabled + { + get => _state.ImageSmoothingEnabled; + set + { + _state.ImageSmoothingEnabled = value; + Record("imageSmoothingEnabled", value); + } + } + + /// + public ImageSmoothingQuality ImageSmoothingQuality + { + get => _state.ImageSmoothingQuality; + set + { + if (value <= ImageSmoothingQuality.High) + { + _state.ImageSmoothingQuality = value; + Record("imageSmoothingQuality", value); + } + } + } + + #endregion + + #region CanvasFillStrokeStyles + + /// + public Object StrokeStyle + { + get => _state.StrokeStyle; + set + { + var style = NormalizeStyle(value); + + if (style is not null) + { + _state.StrokeStyle = style; + Record("strokeStyle", style); + } + } + } + + /// + public Object FillStyle + { + get => _state.FillStyle; + set + { + var style = NormalizeStyle(value); + + if (style is not null) + { + _state.FillStyle = style; + Record("fillStyle", style); + } + } + } + + /// + public CanvasGradient CreateLinearGradient(Double x0, Double y0, Double x1, Double y1) + { + if (!Finite(x0, y0, x1, y1)) + throw new ArgumentException("The coordinates must be finite."); + + return new CanvasGradient(CanvasGradientKind.Linear, x0, y0, x1, y1); + } + + /// + public CanvasGradient CreateRadialGradient(Double x0, Double y0, Double r0, Double x1, Double y1, Double r1) + { + if (!Finite(x0, y0, r0, x1, y1, r1)) + throw new ArgumentException("The coordinates must be finite."); + + if (r0 < 0 || r1 < 0) + throw new DomException(DomError.IndexSizeError); + + return new CanvasGradient(CanvasGradientKind.Radial, x0, y0, r0, x1, y1, r1); + } + + /// + public CanvasGradient CreateConicGradient(Double startAngle, Double x, Double y) + { + if (!Finite(startAngle, x, y)) + throw new ArgumentException("The coordinates must be finite."); + + return new CanvasGradient(CanvasGradientKind.Conic, startAngle, x, y); + } + + /// + public CanvasPattern? CreatePattern(CssImageValue image, String? repetition) + { + if (image is null) + throw new ArgumentNullException(nameof(image)); + + var mode = String.IsNullOrEmpty(repetition) ? "repeat" : repetition!; + + if (!Repetitions.Contains(mode)) + throw new DomException(DomError.Syntax); + + return new CanvasPattern(image, mode); + } + + #endregion + + #region CanvasShadowStyles + + /// + public Double ShadowOffsetX + { + get => _state.ShadowOffsetX; + set + { + if (Finite(value)) + { + _state.ShadowOffsetX = value; + Record("shadowOffsetX", value); + } + } + } + + /// + public Double ShadowOffsetY + { + get => _state.ShadowOffsetY; + set + { + if (Finite(value)) + { + _state.ShadowOffsetY = value; + Record("shadowOffsetY", value); + } + } + } + + /// + public Double ShadowBlur + { + get => _state.ShadowBlur; + set + { + if (Finite(value) && value >= 0) + { + _state.ShadowBlur = value; + Record("shadowBlur", value); + } + } + } + + /// + public String ShadowColor + { + get => _state.ShadowColor; + set + { + var color = CanvasColor.Normalize(value); + + if (color is not null) + { + _state.ShadowColor = color; + Record("shadowColor", color); + } + } + } + + #endregion + + #region CanvasRect + + /// + public void ClearRect(Double x, Double y, Double w, Double h) + { + if (Finite(x, y, w, h)) + { + Record("clearRect", x, y, w, h); + } + } + + /// + public void FillRect(Double x, Double y, Double w, Double h) + { + if (Finite(x, y, w, h)) + { + Record("fillRect", x, y, w, h); + } + } + + /// + public void StrokeRect(Double x, Double y, Double w, Double h) + { + if (Finite(x, y, w, h)) + { + Record("strokeRect", x, y, w, h); + } + } + + #endregion + + #region CanvasDrawPath + + /// + public void BeginPath() + { + _path.Geometry.Clear(); + Record("beginPath"); + } + + /// + public void Fill(CanvasFillRule fillRule = CanvasFillRule.NonZero) => Record("fill", fillRule); + + /// + public void Fill(Path2D path, CanvasFillRule fillRule = CanvasFillRule.NonZero) => + Record("fill", Snapshot(path), fillRule); + + /// + public void Stroke() => Record("stroke"); + + /// + public void Stroke(Path2D path) => Record("stroke", Snapshot(path)); + + /// + public void Clip(CanvasFillRule fillRule = CanvasFillRule.NonZero) => Record("clip", fillRule); + + /// + public void Clip(Path2D path, CanvasFillRule fillRule = CanvasFillRule.NonZero) => + Record("clip", Snapshot(path), fillRule); + + /// + public Boolean IsPointInPath(Double x, Double y, CanvasFillRule fillRule = CanvasFillRule.NonZero) => + Finite(x, y) && _path.Geometry.Contains(new PaintPoint(x, y), fillRule); + + /// + public Boolean IsPointInPath(Path2D path, Double x, Double y, CanvasFillRule fillRule = CanvasFillRule.NonZero) + { + if (path is null) + throw new ArgumentNullException(nameof(path)); + + var transform = _state.Transform; + return Finite(x, y) && transform.IsInvertible && path.Geometry.Contains(transform.Invert().Apply(x, y), fillRule); + } + + /// + public Boolean IsPointInStroke(Double x, Double y) => + Finite(x, y) && _path.Geometry.StrokeContains(new PaintPoint(x, y), _state.LineWidth * _state.Transform.Scale); + + /// + public Boolean IsPointInStroke(Path2D path, Double x, Double y) + { + if (path is null) + throw new ArgumentNullException(nameof(path)); + + var transform = _state.Transform; + return Finite(x, y) && transform.IsInvertible && path.Geometry.StrokeContains(transform.Invert().Apply(x, y), _state.LineWidth); + } + + #endregion + + #region CanvasDrawImage + + /// + public void DrawImage(CssImageValue image, Double dx, Double dy) + { + if (image is null) + throw new ArgumentNullException(nameof(image)); + + if (Finite(dx, dy)) + { + Record("drawImage", image, dx, dy); + } + } + + /// + public void DrawImage(CssImageValue image, Double dx, Double dy, Double dw, Double dh) + { + if (image is null) + throw new ArgumentNullException(nameof(image)); + + if (Finite(dx, dy, dw, dh)) + { + Record("drawImage", image, dx, dy, dw, dh); + } + } + + /// + public void DrawImage(CssImageValue image, Double sx, Double sy, Double sw, Double sh, Double dx, Double dy, Double dw, Double dh) + { + if (image is null) + throw new ArgumentNullException(nameof(image)); + + if (Finite(sx, sy, sw, sh, dx, dy, dw, dh)) + { + Record("drawImage", image, sx, sy, sw, sh, dx, dy, dw, dh); + } + } + + #endregion + + #region CanvasPathDrawingStyles + + /// + public Double LineWidth + { + get => _state.LineWidth; + set + { + if (Finite(value) && value > 0) + { + _state.LineWidth = value; + Record("lineWidth", value); + } + } + } + + /// + public CanvasLineCap LineCap + { + get => _state.LineCap; + set + { + if (value <= CanvasLineCap.Square) + { + _state.LineCap = value; + Record("lineCap", value); + } + } + } + + /// + public CanvasLineJoin LineJoin + { + get => _state.LineJoin; + set + { + if (value <= CanvasLineJoin.Miter) + { + _state.LineJoin = value; + Record("lineJoin", value); + } + } + } + + /// + public Double MiterLimit + { + get => _state.MiterLimit; + set + { + if (Finite(value) && value > 0) + { + _state.MiterLimit = value; + Record("miterLimit", value); + } + } + } + + /// + public void SetLineDash(IEnumerable segments) + { + if (segments is null) + throw new ArgumentNullException(nameof(segments)); + + var list = segments.ToList(); + + if (list.Any(m => !Finite(m) || m < 0)) + { + return; + } + + if (list.Count % 2 == 1) + { + list.AddRange(list.ToArray()); + } + + _state.LineDash = list.ToArray(); + Record("setLineDash", (Double[])_state.LineDash.Clone()); + } + + /// + public Double[] GetLineDash() => (Double[])_state.LineDash.Clone(); + + /// + public Double LineDashOffset + { + get => _state.LineDashOffset; + set + { + if (Finite(value)) + { + _state.LineDashOffset = value; + Record("lineDashOffset", value); + } + } + } + + #endregion + + #region CanvasPath + + /// + public void ClosePath() => _path.ClosePath(); + + /// + public void MoveTo(Double x, Double y) => _path.MoveTo(x, y, _state.Transform); + + /// + public void LineTo(Double x, Double y) => _path.LineTo(x, y, _state.Transform); + + /// + public void QuadraticCurveTo(Double cpx, Double cpy, Double x, Double y) => + _path.QuadraticCurveTo(cpx, cpy, x, y, _state.Transform); + + /// + public void BezierCurveTo(Double cp1x, Double cp1y, Double cp2x, Double cp2y, Double x, Double y) => + _path.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y, _state.Transform); + + /// + public void ArcTo(Double x1, Double y1, Double x2, Double y2, Double radius) => + _path.ArcTo(x1, y1, x2, y2, radius, _state.Transform); + + /// + public void Rect(Double x, Double y, Double w, Double h) => _path.Rect(x, y, w, h, _state.Transform); + + /// + public void RoundRect(Double x, Double y, Double w, Double h, params Double[] radii) => + _path.RoundRect(x, y, w, h, radii, _state.Transform); + + /// + public void Arc(Double x, Double y, Double radius, Double startAngle, Double endAngle, Boolean counterclockwise = false) => + _path.Arc(x, y, radius, startAngle, endAngle, counterclockwise, _state.Transform); + + /// + public void Ellipse(Double x, Double y, Double radiusX, Double radiusY, Double rotation, Double startAngle, Double endAngle, Boolean counterclockwise = false) => + _path.Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise, _state.Transform); + + #endregion + + #region Helpers + + private void Record(String name, params Object[] arguments) => _commands.Add(new PaintCommand(name, arguments)); + + private static Boolean Finite(params Double[] values) => CanvasPathBuilder.Finite(values); + + // a path may change after it has been drawn, which does not change the drawing + private static Path2D Snapshot(Path2D path) => new(path ?? throw new ArgumentNullException(nameof(path))); + + private static Object? NormalizeStyle(Object? value) => value switch + { + String text => CanvasColor.Normalize(text), + CanvasGradient or CanvasPattern => value, + _ => null, + }; + + private sealed class DrawingState + { + public PaintMatrix Transform { get; set; } = PaintMatrix.Identity; + + public Object FillStyle { get; set; } = CanvasColor.Black; + + public Object StrokeStyle { get; set; } = CanvasColor.Black; + + public Double GlobalAlpha { get; set; } = 1; + + public String GlobalCompositeOperation { get; set; } = "source-over"; + + public Boolean ImageSmoothingEnabled { get; set; } = true; + + public ImageSmoothingQuality ImageSmoothingQuality { get; set; } = ImageSmoothingQuality.Low; + + public Double LineWidth { get; set; } = 1; + + public CanvasLineCap LineCap { get; set; } = CanvasLineCap.Butt; + + public CanvasLineJoin LineJoin { get; set; } = CanvasLineJoin.Miter; + + public Double MiterLimit { get; set; } = 10; + + public Double[] LineDash { get; set; } = Array.Empty(); + + public Double LineDashOffset { get; set; } + + public Double ShadowOffsetX { get; set; } + + public Double ShadowOffsetY { get; set; } + + public Double ShadowBlur { get; set; } + + public String ShadowColor { get; set; } = CanvasColor.TransparentBlack; + + public DrawingState Clone() => (DrawingState)MemberwiseClone(); + } + + #endregion + } +} diff --git a/src/AngleSharp.Css/Parser/Micro/CompoundParser.cs b/src/AngleSharp.Css/Parser/Micro/CompoundParser.cs index ca21f624..bc1e1b11 100644 --- a/src/AngleSharp.Css/Parser/Micro/CompoundParser.cs +++ b/src/AngleSharp.Css/Parser/Micro/CompoundParser.cs @@ -128,7 +128,7 @@ public static ICssImageValue ParseImageSource(this StringSource source) if (url == null) { - return source.ParseGradient() ?? source.ParseImageSet(); + return source.ParseGradient() ?? source.ParseImageSet() ?? source.ParsePaint(); } return url; @@ -149,7 +149,7 @@ internal static ICssImageValue ParseImageSet(this StringSource source) while (true) { var parts = new List(); - var image = source.ParseUri() ?? source.ParseGradient() ?? (ICssValue)ParseStringValue(source); + var image = source.ParseUri() ?? source.ParseGradient() ?? source.ParsePaint() ?? (ICssValue)ParseStringValue(source); if (image is null) { @@ -196,6 +196,127 @@ internal static ICssImageValue ParseImageSet(this StringSource source) return null; } + /// + /// Parses a paint function, i.e., paint( <ident>, <declaration-value>? ), + /// where the arguments are kept as written (split at the top-level commas), as only + /// the paint definition knows their syntax. + /// https://www.w3.org/TR/css-paint-api-1/#paint-notation + /// + internal static ICssImageValue ParsePaint(this StringSource source) + { + var pos = source.Index; + + if (source.IsFunction(FunctionNames.Paint)) + { + var name = source.ParseIdent(); + + if (name is not null) + { + var c = source.SkipSpacesAndComments(); + + if (c == Symbols.RoundBracketClose) + { + source.SkipCurrentAndSpaces(); + return new CssPaintValue(name, Array.Empty()); + } + else if (c == Symbols.Comma) + { + source.SkipCurrentAndSpaces(); + var arguments = ParsePaintArguments(source); + + if (arguments is not null) + { + return new CssPaintValue(name, arguments); + } + } + } + } + + source.BackTo(pos); + return null; + } + + private static ICssValue[] ParsePaintArguments(StringSource source) + { + var arguments = new List(); + var closers = new Stack(); + var content = source.Content; + var start = source.Index; + var current = source.Current; + + while (!source.IsDone) + { + if (closers.Count == 0 && current is Symbols.Comma or Symbols.RoundBracketClose) + { + var text = content.Substring(start, source.Index - start).Trim(); + + if (text.Length == 0) + { + return null; + } + + arguments.Add(new CssAnyValue(text, isResolved: true)); + + if (current == Symbols.RoundBracketClose) + { + source.SkipCurrentAndSpaces(); + return arguments.ToArray(); + } + + source.SkipCurrentAndSpaces(); + start = source.Index; + current = source.Current; + continue; + } + else if (current == Symbols.RoundBracketOpen) + { + closers.Push(Symbols.RoundBracketClose); + } + else if (current == Symbols.SquareBracketOpen) + { + closers.Push(Symbols.SquareBracketClose); + } + else if (current == Symbols.CurlyBracketOpen) + { + closers.Push(Symbols.CurlyBracketClose); + } + else if (current is Symbols.RoundBracketClose or Symbols.SquareBracketClose or Symbols.CurlyBracketClose) + { + if (closers.Count == 0 || closers.Pop() != current) + { + return null; + } + } + else if (current is Symbols.SingleQuote or Symbols.DoubleQuote) + { + if (source.ParseString() is null) + { + return null; + } + + current = source.Current; + continue; + } + else if (current == Symbols.Solidus && source.Peek() == Symbols.Asterisk) + { + source.Next(); + current = source.SkipCssComment(); + continue; + } + else if (current == Symbols.ReverseSolidus && source.IsValidEscape()) + { + source.ConsumeEscape(); + current = source.Current; + continue; + } + + current = source.Next(); + } + + // the function has not been closed + return null; + } + private static ICssValue ParseStringValue(StringSource source) { var str = source.ParseString(); diff --git a/src/AngleSharp.Css/ValueConverters.cs b/src/AngleSharp.Css/ValueConverters.cs index 5b066089..feb6920d 100644 --- a/src/AngleSharp.Css/ValueConverters.cs +++ b/src/AngleSharp.Css/ValueConverters.cs @@ -1699,6 +1699,7 @@ static class ValueConverters UrlConverter, GradientConverter, FromParser(CompoundParser.ParseImageSet), + FromParser(CompoundParser.ParsePaint), None); /// diff --git a/src/AngleSharp.Css/Values/CssPropertySyntax.cs b/src/AngleSharp.Css/Values/CssPropertySyntax.cs index 585c1dbc..9bd42f9c 100644 --- a/src/AngleSharp.Css/Values/CssPropertySyntax.cs +++ b/src/AngleSharp.Css/Values/CssPropertySyntax.cs @@ -24,7 +24,7 @@ sealed class CssPropertySyntax { "percentage", ValueConverters.PercentConverter }, { "length-percentage", ValueConverters.LengthOrPercentConverter }, { "color", ValueConverters.CurrentColorConverter }, - { "image", ValueConverters.Or(ValueConverters.UrlConverter, ValueConverters.GradientConverter, new ClassValueConverter(CompoundParser.ParseImageSet)) }, + { "image", ValueConverters.Or(ValueConverters.UrlConverter, ValueConverters.GradientConverter, new ClassValueConverter(CompoundParser.ParseImageSet), new ClassValueConverter(CompoundParser.ParsePaint)) }, { "url", ValueConverters.UrlConverter }, { "integer", ValueConverters.IntegerConverter }, { "angle", new ClassValueConverter(UnitParser.ParseAngleOrCalc) }, diff --git a/src/AngleSharp.Css/Values/Functions/CssPaintValue.cs b/src/AngleSharp.Css/Values/Functions/CssPaintValue.cs new file mode 100644 index 00000000..0a76fedb --- /dev/null +++ b/src/AngleSharp.Css/Values/Functions/CssPaintValue.cs @@ -0,0 +1,103 @@ +#nullable enable +namespace AngleSharp.Css.Values +{ + using AngleSharp.Css.Dom; + using AngleSharp.Text; + using System; + using System.Linq; + + /// + /// Represents the paint function, i.e., an image drawn by a paint definition that + /// has been registered under the given name, e.g., paint(checkerboard, 10px). + /// The arguments are kept as written, since only the paint definition knows their + /// syntax: parsing the value never requires the paint definition to be available. + /// https://www.w3.org/TR/css-paint-api-1/#paint-notation + /// + public sealed class CssPaintValue : ICssImageValue, IEquatable + { + #region Fields + + private readonly String _painterName; + private readonly ICssValue[] _arguments; + + #endregion + + #region ctor + + /// + /// Creates a new paint function. + /// + /// The name of the paint definition. + /// The (unparsed) arguments for the paint definition. + public CssPaintValue(String painterName, ICssValue[] arguments) + { + _painterName = painterName ?? throw new ArgumentNullException(nameof(painterName)); + _arguments = arguments ?? Array.Empty(); + } + + #endregion + + #region Properties + + /// + /// Gets the name of the function, i.e., paint. + /// + public String Name => FunctionNames.Paint; + + /// + /// Gets the name of the paint definition (the ident of the function), which + /// is looked up in the paint worklet of the document when the image is drawn. + /// + public String PainterName => _painterName; + + /// + /// Gets the arguments following the name, each one as written, e.g., the + /// two arguments 10px and "a, b" of paint(x, 10px, "a, b"). + /// + public ICssValue[] Arguments => _arguments; + + /// + /// Gets the CSS text representation. + /// + public String CssText + { + get + { + var parts = new String[_arguments.Length + 1]; + parts[0] = _painterName; + + for (var i = 0; i < _arguments.Length; i++) + { + parts[i + 1] = _arguments[i].CssText; + } + + return Name.CssFunction(String.Join(", ", parts)); + } + } + + #endregion + + #region Methods + + /// + /// Checks if the current value is equal to the provided one. + /// + /// The value to check against. + /// True if both are equal, otherwise false. + public Boolean Equals(CssPaintValue? other) => + other is not null && + _painterName.Is(other._painterName) && + _arguments.Length == other._arguments.Length && + _arguments.Select((m, i) => m.CssText.Is(other._arguments[i].CssText)).All(m => m); + + Boolean IEquatable.Equals(ICssValue? other) => other is CssPaintValue value && Equals(value); + + /// + /// The computed value is as specified: the arguments are only interpreted by + /// the paint definition, when the image is drawn. + /// + ICssValue ICssValue.Compute(ICssComputeContext context) => this; + + #endregion + } +} From cd3310119d529e02729f0d175a93f17b79106533 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 17:43:30 +0100 Subject: [PATCH 05/12] Performance improvements --- CHANGELOG.md | 3 +- .../Styling/RenderTreeReuseTests.cs | 109 +++++++++ src/AngleSharp.Css/DeclarationInfo.cs | 32 +++ .../Dom/ElementCssInlineStyleExtensions.cs | 9 + .../Dom/Internal/CssProperty.cs | 224 ++++++++++++++++-- .../Dom/Internal/CssStyleDeclaration.cs | 10 +- .../Dom/Internal/StyleRuleIndex.cs | 128 ++++++++-- .../Extensions/CssOmExtensions.cs | 61 +++-- .../Extensions/StyleCollectionExtensions.cs | 4 +- .../RenderTree/RenderTreeBuilder.cs | 8 +- .../Values/CssComputedValues.cs | 71 ++++++ .../Values/Functions/CssNoneValue.cs | 4 +- .../Values/Functions/CssUrlValue.cs | 4 +- .../Values/ICssComputedValue.cs | 18 ++ .../Values/Multiples/CssListValue.cs | 11 +- .../Values/Multiples/CssTupleValue.cs | 12 +- .../Values/Primitives/CssColorValue.cs | 4 +- .../Values/Primitives/CssConstantValue.cs | 4 +- .../Values/Primitives/CssIdentifierValue.cs | 4 +- .../Values/Primitives/CssIntegerValue.cs | 4 +- .../Values/Primitives/CssLengthValue.cs | 6 +- .../Values/Primitives/CssNumberValue.cs | 4 +- .../Values/Primitives/CssPercentageValue.cs | 4 +- .../Values/Primitives/CssStringValue.cs | 4 +- .../Values/Raws/CssInheritValue.cs | 4 +- .../Values/Raws/CssInitialValue.cs | 4 +- .../Values/Raws/CssUnsetValue.cs | 4 +- .../LargeSheetRenderBenchmarks.cs | 125 ++++++++++ 28 files changed, 809 insertions(+), 70 deletions(-) create mode 100644 src/AngleSharp.Css.Tests/Styling/RenderTreeReuseTests.cs create mode 100644 src/AngleSharp.Css/Values/CssComputedValues.cs create mode 100644 src/AngleSharp.Css/Values/ICssComputedValue.cs create mode 100644 src/AngleSharp.Performance.Css/LargeSheetRenderBenchmarks.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 13adba26..d394f439 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,8 @@ # 1.5.0 -Released on Wednesday, November 18. +Released on Wednesday, November 18 2026. +- Improved CSS render tree construction performance - gains up to 50% - Added the CSS Painting API with the `paint()` image function (#277) - Added support for registered custom properties via `@property` (#274) - Added `CSS.registerProperty()` diff --git a/src/AngleSharp.Css.Tests/Styling/RenderTreeReuseTests.cs b/src/AngleSharp.Css.Tests/Styling/RenderTreeReuseTests.cs new file mode 100644 index 00000000..3f25350e --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/RenderTreeReuseTests.cs @@ -0,0 +1,109 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.RenderTree; + using AngleSharp.Dom; + using AngleSharp.Html.Parser; + using NUnit.Framework; + using System.Linq; + using System.Text; + + /// + /// Building a render tree remembers what is the same for many elements: the rules the + /// ancestors of an element bring, and the computed value of a declaration with the same + /// font sizes. Neither may outlive a change of the DOM or differ between elements. + /// + [TestFixture] + public class RenderTreeReuseTests + { + private static IDocument Parse(string html) + { + var config = Configuration.Default.WithCss().WithRenderDevice(new DefaultRenderDevice { ViewPortWidth = 1000, ViewPortHeight = 800 }); + return BrowsingContext.New(config).GetService().ParseDocument(html); + } + + private static ElementRenderNode Find(IRenderNode node, string id) + { + if (node is ElementRenderNode element && node.Ref is IElement { Id: var elementId } && elementId == id) + { + return element; + } + + return node.Children.Select(child => Find(child, id)).FirstOrDefault(found => found is not null); + } + + [Test] + public void RulesOfAncestorsFollowChangesOfTheDomBetweenRenders() + { + var document = Parse("" + + "

x

y
"); + var tree = document.DefaultView.Render(); + + Assert.AreEqual("rgba(255, 0, 0, 1)", Find(tree, "b").ComputedStyle.GetPropertyValue("color")); + Assert.AreNotEqual("rgba(0, 0, 255, 1)", Find(tree, "c").ComputedStyle.GetPropertyValue("color")); + + document.GetElementById("a").ClassName = "other"; + tree = document.DefaultView.Render(); + + Assert.AreNotEqual("rgba(255, 0, 0, 1)", Find(tree, "b").ComputedStyle.GetPropertyValue("color")); + Assert.AreEqual("rgba(0, 0, 255, 1)", Find(tree, "c").ComputedStyle.GetPropertyValue("color")); + } + + [Test] + public void RulesOfAncestorsApplyInLargeDocuments() + { + // enough elements to compute the styles on several threads + var html = new StringBuilder(""); + + for (var i = 0; i < 100; i++) + { + html.Append("
  • x
    • y
"); + } + + var tree = Parse(html.ToString()).DefaultView.Render(); + + for (var i = 0; i < 100; i++) + { + Assert.AreEqual("3px", Find(tree, "a" + i).ComputedStyle.GetPropertyValue("margin-left")); + Assert.AreEqual("5px", Find(tree, "b" + i).ComputedStyle.GetPropertyValue("margin-left")); + } + } + + [Test] + public void SameDeclarationComputesPerFontSize() + { + var document = Parse("" + + "

x

y

z

"); + var tree = document.DefaultView.Render(); + + Assert.AreEqual("20px", Find(tree, "a").ComputedStyle.GetPropertyValue("margin-left")); + Assert.AreEqual("40px", Find(tree, "b").ComputedStyle.GetPropertyValue("margin-left")); + Assert.AreEqual("20px", Find(tree, "c").ComputedStyle.GetPropertyValue("margin-left")); + Assert.AreEqual("15px", Find(tree, "a").ComputedStyle.GetPropertyValue("line-height")); + Assert.AreEqual("30px", Find(tree, "b").ComputedStyle.GetPropertyValue("line-height")); + + document.GetElementById("c").SetAttribute("style", "font-size: 30px"); + tree = document.DefaultView.Render(); + + Assert.AreEqual("60px", Find(tree, "c").ComputedStyle.GetPropertyValue("margin-left")); + Assert.AreEqual("20px", Find(tree, "a").ComputedStyle.GetPropertyValue("margin-left")); + } + + [Test] + public void InlineStyleSetByScriptApplies() + { + var document = Parse("

x

y

"); + document.GetElementById("a").GetStyle().SetProperty("color", "blue"); + var tree = document.DefaultView.Render(); + + Assert.AreEqual("rgba(0, 0, 255, 1)", Find(tree, "a").ComputedStyle.GetPropertyValue("color")); + Assert.AreEqual("rgba(255, 0, 0, 1)", Find(tree, "b").ComputedStyle.GetPropertyValue("color")); + + document.GetElementById("b").RemoveAttribute("style"); + tree = document.DefaultView.Render(); + + Assert.AreNotEqual("rgba(255, 0, 0, 1)", Find(tree, "b").ComputedStyle.GetPropertyValue("color")); + } + } +} diff --git a/src/AngleSharp.Css/DeclarationInfo.cs b/src/AngleSharp.Css/DeclarationInfo.cs index 832f9b68..bfb9d63f 100644 --- a/src/AngleSharp.Css/DeclarationInfo.cs +++ b/src/AngleSharp.Css/DeclarationInfo.cs @@ -4,6 +4,7 @@ namespace AngleSharp.Css using AngleSharp.Css.Converters; using AngleSharp.Css.Dom; using System; + using System.Threading; using static ValueConverters; /// @@ -72,5 +73,36 @@ public DeclarationInfo(String name, IValueConverter converter, PropertyFlags fla /// Gets the names of related required longhand declarations. /// public String[] Longhands { get; } + + // the initial value as the converter reads it from its text (see ConvertInitialValue) + private ICssValue? _convertedInitialValue; + private Boolean _hasConvertedInitialValue; + + /// + /// Gets the initial value as the given converter reads its text, which is what a + /// declaration computing to its initial value gets. Values are immutable, hence the one + /// of the converter of the declaration is converted once instead of for every element. + /// + internal ICssValue? ConvertInitialValue(IValueConverter converter) + { + var initial = InitialValue; + + if (initial is null) + { + return null; + } + else if (!ReferenceEquals(converter, Converter)) + { + return converter.Convert(initial.CssText); + } + else if (!Volatile.Read(ref _hasConvertedInitialValue)) + { + // a race converts it twice, with equal results + _convertedInitialValue = converter.Convert(initial.CssText); + Volatile.Write(ref _hasConvertedInitialValue, true); + } + + return _convertedInitialValue; + } } } diff --git a/src/AngleSharp.Css/Dom/ElementCssInlineStyleExtensions.cs b/src/AngleSharp.Css/Dom/ElementCssInlineStyleExtensions.cs index d37adfaa..647c3dbe 100644 --- a/src/AngleSharp.Css/Dom/ElementCssInlineStyleExtensions.cs +++ b/src/AngleSharp.Css/Dom/ElementCssInlineStyleExtensions.cs @@ -31,6 +31,15 @@ public static class ElementCssInlineStyleExtensions [DomAccessor(Accessors.Setter)] public static void SetStyle(this IElement element, String value) => element.SetAttribute(AttributeNames.Style, value); + /// + /// Gets the style declaration of an element for the cascade: null if the element has + /// none yet and no style attribute, i.e., nothing to declare, which spares creating + /// (and remembering) an empty declaration for every element that is styled. + /// + internal static ICssStyleDeclaration GetStyleIfDeclared(this IElement element) => + _styles.TryGetValue(element, out var style) ? style : + element.HasAttribute(AttributeNames.Style) ? element.GetStyle() : null; + internal static void UpdateStyle(this IElement element, String value) => element.GetStyle()?.Update(value); private static ICssStyleDeclaration CreateStyle(IElement element) => CreateStyle(element, null); diff --git a/src/AngleSharp.Css/Dom/Internal/CssProperty.cs b/src/AngleSharp.Css/Dom/Internal/CssProperty.cs index efb247b0..f0032f94 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssProperty.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssProperty.cs @@ -8,6 +8,7 @@ namespace AngleSharp.Css.Dom using AngleSharp.Text; using System; using System.IO; + using System.Threading; /// /// Fore more information about CSS properties see: @@ -24,6 +25,8 @@ internal class CssProperty : ICssProperty private Boolean _important; private ICssValue _value; private KeywordState _keyword; + // the last computed declaration with what its value depended on, see Compute + private ComputedMemo _computed; #endregion @@ -120,6 +123,7 @@ private void SetValue(ICssValue value) { _value = value; _keyword = KeywordState.Unknown; + _computed = null; } private KeywordState GetKeyword() @@ -131,6 +135,7 @@ private KeywordState GetKeyword() null => KeywordState.Initial, CssInitialValue => KeywordState.Initial, CssInheritValue => KeywordState.Inherit, + _ when !MaySerializeAsKeyword(_value) => KeywordState.Other, _ => _value.CssText switch { var text when text.Is(CssKeywords.Initial) => KeywordState.Initial, @@ -143,20 +148,127 @@ var text when text.Is(CssKeywords.Inherit) => KeywordState.Inherit, return _keyword; } + /// + /// Gets if the text of the value may be a CSS-wide keyword (e.g., initial), which is + /// false for the kinds of values serialized from numbers, lengths, colors or functions: + /// telling it from their text would serialize them (for every element computed). + /// + internal static Boolean MaySerializeAsKeyword(ICssValue value) + { + switch (value) + { + case null: + case ICssFunctionValue: + case CssLengthValue: + case CssColorValue: + case CssNumberValue: + case CssPercentageValue: + case CssIntegerValue: + case CssAngleValue: + case CssTimeValue: + case CssStringValue: + return false; + case ICssMultipleValue multiple: + // the text of a multiple value is made of the texts of its items + for (var i = 0; i < multiple.Count; i++) + { + if (MaySerializeAsKeyword(multiple[i])) + { + return true; + } + } + + return false; + default: + return true; + } + } + public ICssProperty Compute(ICssComputeContext context) { + if (CssComputedValues.IsComputed(_value) && !_name.StartsWith("--", StringComparison.Ordinal)) + { + // e.g., a color or a keyword: computing it would just give a copy of it + return this; + } + + // the declaration of a rule is computed for every element the rule matches, mostly + // to the same value, e.g., `margin: 1em` for all elements with the same font size + var memo = Volatile.Read(ref _computed); + + if (memo is not null && memo.Important == _important && memo.Matches(context, _name)) + { + return memo.Result; + } + var propertyContext = new PropertyComputeContext(context, _converter, _name); var computedValue = _name.StartsWith("--", StringComparison.Ordinal) ? context.Resolve(_name) ?? CssInvalidValue.Instance : _value is CssChildValue child ? child.Compute(propertyContext, _name) : _value is CssReferenceValue reference ? reference.ComputeSubstituted(propertyContext) : _value?.Compute(propertyContext); + var result = computedValue != _value ? new CssProperty(_name, _converter, _flags, computedValue, _important) : this; - if (computedValue != _value) + if (propertyContext.IsRemembered && context is CssComputeContext && _value is not CssChildValue && _value is not CssReferenceValue && !_name.StartsWith("--", StringComparison.Ordinal)) { - return new CssProperty(_name, _converter, _flags, computedValue, _important); + Volatile.Write(ref _computed, new ComputedMemo(propertyContext, _important, result)); } - return this; + return result; + } + + /// + /// A computed declaration and what the computation read from the context: as the value + /// is computed from these (e.g., em from the font size), the same declaration is the + /// computed one for every element giving the same. + /// + private sealed class ComputedMemo + { + private readonly ReadInputs _reads; + private readonly Double? _emBase; + private readonly Double? _rootFontSize; + private readonly Boolean _keepsPercentages; + private readonly Double? _percentageBasis; + + public ComputedMemo(PropertyComputeContext context, Boolean important, ICssProperty result) + { + _reads = context.Reads; + _emBase = context.ReadEmBase; + _rootFontSize = context.ReadRootFontSize; + _keepsPercentages = context.ReadKeepsPercentages; + _percentageBasis = context.ReadPercentageBasis; + Important = important; + Result = result; + } + + public Boolean Important { get; } + + public ICssProperty Result { get; } + + public Boolean Matches(ICssComputeContext context, String name) + { + if (context is not CssComputeContext) + { + return false; + } + + var fonts = context as IFontComputeContext; + return ((_reads & ReadInputs.EmBase) == 0 || _emBase == PropertyComputeContext.GetEmBase(fonts, name)) && + ((_reads & ReadInputs.RootFontSize) == 0 || _rootFontSize == PropertyComputeContext.GetRootFontSize(fonts, name)) && + ((_reads & ReadInputs.KeepsPercentages) == 0 || _keepsPercentages == PropertyComputeContext.GetKeepsPercentages(fonts, name)) && + ((_reads & ReadInputs.PercentageBasis) == 0 || _percentageBasis == PropertyComputeContext.GetPercentageBasis(fonts, name)); + } + } + + [Flags] + private enum ReadInputs : Byte + { + None = 0, + EmBase = 1, + RootFontSize = 2, + KeepsPercentages = 4, + PercentageBasis = 8, + // anything else, e.g., other properties or the device: not remembered + Other = 128, } /// @@ -195,32 +307,114 @@ public PropertyComputeContext(ICssComputeContext parent, IValueConverter convert _name = name; } - public IRenderDevice Device => _parent.Device; + /// + /// Gets what has been read, i.e., what the computed value depends on. + /// + public ReadInputs Reads { get; private set; } + + public Boolean IsRemembered => (Reads & ReadInputs.Other) == 0; + + public Double? ReadEmBase { get; private set; } + + public Double? ReadRootFontSize { get; private set; } - public ICssProperties Properties => _parent is ILocalComputeContext local ? local.Properties : null; + public Boolean ReadKeepsPercentages { get; private set; } - public IBrowsingContext Context => _parent.Context; + public Double? ReadPercentageBasis { get; private set; } + + public IRenderDevice Device + { + get + { + Reads |= ReadInputs.Other; + return _parent.Device; + } + } + + public ICssProperties Properties + { + get + { + Reads |= ReadInputs.Other; + return _parent is ILocalComputeContext local ? local.Properties : null; + } + } + + public IBrowsingContext Context + { + get + { + Reads |= ReadInputs.Other; + return _parent.Context; + } + } public IValueConverter Converter => _converter; - public ICssValue Resolve(String name) => - _parent is CssComputeContext context && _name.Is(PropertyNames.FontSize) ? context.ResolveForFontSize(name) : _parent.Resolve(name); + public ICssValue Resolve(String name) + { + Reads |= ReadInputs.Other; + return _parent is CssComputeContext context && _name.Is(PropertyNames.FontSize) ? context.ResolveForFontSize(name) : _parent.Resolve(name); + } - public ICssValue InheritedValue(String name) => (_parent as IInheritingComputeContext)?.InheritedValue(name); + public ICssValue InheritedValue(String name) + { + Reads |= ReadInputs.Other; + return (_parent as IInheritingComputeContext)?.InheritedValue(name); + } private IFontComputeContext Fonts => _parent as IFontComputeContext; + public Double? EmBase + { + get + { + Reads |= ReadInputs.EmBase; + return ReadEmBase = GetEmBase(Fonts, _name); + } + } + + public Double? RootFontSize + { + get + { + Reads |= ReadInputs.RootFontSize; + return ReadRootFontSize = GetRootFontSize(Fonts, _name); + } + } + + public Boolean KeepsPercentages + { + get + { + Reads |= ReadInputs.KeepsPercentages; + return ReadKeepsPercentages = GetKeepsPercentages(Fonts, _name); + } + } + + public Double? PercentageBasis + { + get + { + Reads |= ReadInputs.PercentageBasis; + return ReadPercentageBasis = GetPercentageBasis(Fonts, _name); + } + } + // em in font-size refers to the font size of the parent, everywhere else to the one of the element. - public Double? EmBase => _name.Is(PropertyNames.FontSize) ? Fonts?.ParentFontSize : Fonts?.FontSize; + public static Double? GetEmBase(IFontComputeContext fonts, String name) => + name.Is(PropertyNames.FontSize) ? fonts?.ParentFontSize : fonts?.FontSize; - public Double? RootFontSize => _name.Is(PropertyNames.FontSize) ? Fonts?.FontSizeRemBase : Fonts?.RootFontSize; + public static Double? GetRootFontSize(IFontComputeContext fonts, String name) => + name.Is(PropertyNames.FontSize) ? fonts?.FontSizeRemBase : fonts?.RootFontSize; // Except for font-size and line-height, percentages refer to a box (or a length) that is only known during layout. - public Boolean KeepsPercentages => Fonts is not null && PercentageBasis is null; + public static Boolean GetKeepsPercentages(IFontComputeContext fonts, String name) => + fonts is not null && GetPercentageBasis(fonts, name) is null; - public Double? PercentageBasis => - _name.Is(PropertyNames.FontSize) ? Fonts?.ParentFontSize : - _name.Is(PropertyNames.LineHeight) ? Fonts?.FontSize : + public static Double? GetPercentageBasis(IFontComputeContext fonts, String name) => + name.Is(PropertyNames.FontSize) ? fonts?.ParentFontSize : + name.Is(PropertyNames.LineHeight) ? fonts?.FontSize : null; } diff --git a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs index b9db64be..3d7dfaa0 100644 --- a/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs +++ b/src/AngleSharp.Css/Dom/Internal/CssStyleDeclaration.cs @@ -62,8 +62,9 @@ public CssStyleDeclaration(IBrowsingContext context) /// internal CssStyleDeclaration(IBrowsingContext context, Int32 capacity) { + // the index is only created once there are too many declarations to scan (see Indexed): + // the capacity is an upper bound, e.g., the declarations of all matching rules _declarations = new List(capacity); - _declarationIndex = capacity > MaxUnindexed ? new Dictionary(capacity, StringComparer.Ordinal) : null; _context = context; } @@ -728,7 +729,7 @@ internal void InheritLike(CssStyleDeclaration style) // IsInherited also holds for an explicit `initial` on an inherited property, // which must still resolve to the initial value rather than the parent's. private static Boolean IsExplicitInitial(ICssProperty property) => - property.RawValue is not null && property.RawValue.CssText.Is(CssKeywords.Initial); + property.RawValue is not null && CssProperty.MaySerializeAsKeyword(property.RawValue) && property.RawValue.CssText.Is(CssKeywords.Initial); #endregion @@ -1280,7 +1281,7 @@ private ICssProperty GetPropertyFromShorthand(String name) } // below, a scan of the declarations is about as fast as an index, which is a lot larger - private const Int32 MaxUnindexed = 16; + private const Int32 MaxUnindexed = 32; private void RebuildIndex() { @@ -1290,7 +1291,8 @@ private void RebuildIndex() return; } - var index = _declarationIndex ?? new Dictionary(_declarations.Count, StringComparer.Ordinal); + // sized for the room of the list, e.g., the declarations of all matching rules + var index = _declarationIndex ?? new Dictionary(_declarations.Capacity, StringComparer.Ordinal); index.Clear(); for (var i = 0; i < _declarations.Count; i++) diff --git a/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs b/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs index df028575..8f203137 100644 --- a/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs +++ b/src/AngleSharp.Css/Dom/Internal/StyleRuleIndex.cs @@ -4,6 +4,7 @@ namespace AngleSharp.Css.Dom using AngleSharp.Dom; using AngleSharp.Text; using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; @@ -60,6 +61,19 @@ public Candidates GetCandidates(IElement element) return Collect(element, _keys); } + /// + /// Starts or stops remembering the candidates the ancestors of an element bring (rules + /// such as `.prose *`), which are the same for all children of an element: without, + /// they are looked up through all ancestors for every element. The DOM must not change + /// while they are remembered, e.g., while a render tree is built. + /// + public void RememberAncestors(Boolean remember) + { + _keys.RememberAncestors(remember); + _pseudoKeys.RememberAncestors(remember); + _contentKeys.RememberAncestors(remember); + } + /// /// Checks if a rule that may match the given pseudo-element declares its /// content. Without content a ::before or ::after has no box, and rules @@ -131,33 +145,113 @@ private static Candidates Collect(IElement element, KeyedRules keyed) // the rules for descendants of an element with a key, e.g., .prose * if (keyed.AncestorRules is { } ancestorRules) { - for (var ancestor = element.ParentElement; ancestor is not null; ancestor = ancestor.ParentElement) + if (keyed.AncestorGroups is { } remembered) { - AddGroups(ancestor, ancestorRules, ref first, ref combined); + if (element.ParentElement is { } parentElement) + { + var groups = GetAncestorGroups(parentElement, ancestorRules, remembered); + + if (groups.Count > 0) + { + AddGroup(ref first, ref combined, groups); + } + } } + else + { + for (var ancestor = element.ParentElement; ancestor is not null; ancestor = ancestor.ParentElement) + { + AddGroups(ancestor, ancestorRules, ref first, ref combined); + } + } + } + + return new Candidates(keyed.Ungrouped, Distinct(first, combined)); + } + + /// + /// Gets the (ascending) rules keyed by the element or one of its ancestors, which are + /// remembered for every element (see RememberAncestors). The ancestors are taken from + /// the nearest one already known, without recursion, as the tree may be deep. + /// + private static List GetAncestorGroups(IElement element, KeyedRules ancestorRules, ConcurrentDictionary> remembered) + { + if (remembered.TryGetValue(element, out var known)) + { + return known; } - if (combined is not null) + var parent = element.ParentElement; + List inherited; + + if (parent is null) + { + inherited = NoRules; + } + else if (!remembered.TryGetValue(parent, out inherited!)) { - // a rule may be found via several keys, e.g., ".a, .b" for class="a b" - combined.Sort(); - var count = 0; + // e.g., the first element styled, or one styled out of order on another thread + var pending = new Stack(); - for (var i = 0; i < combined.Count; i++) + for (var ancestor = parent; ancestor is not null && !remembered.ContainsKey(ancestor); ancestor = ancestor.ParentElement) { - if (count == 0 || combined[count - 1] != combined[i]) - { - combined[count++] = combined[i]; - } + pending.Push(ancestor); } - combined.RemoveRange(count, combined.Count - count); - first = combined; + while (pending.Count > 0) + { + var ancestor = pending.Pop(); + var groups = ancestor.ParentElement is { } grandParent && remembered.TryGetValue(grandParent, out var outer) ? outer : NoRules; + remembered[ancestor] = CombineGroups(groups, ancestor, ancestorRules); + } + + inherited = remembered[parent]; } - return new Candidates(keyed.Ungrouped, first); + var result = CombineGroups(inherited, element, ancestorRules); + // another thread may have been faster, with the same result + remembered[element] = result; + return result; + } + + private static List CombineGroups(List inherited, IElement element, KeyedRules ancestorRules) + { + var first = inherited.Count > 0 ? inherited : null; + var combined = default(List); + AddGroups(element, ancestorRules, ref first, ref combined); + return Distinct(first, combined) ?? NoRules; } + /// + /// Gives the rules of the groups as one ascending list without duplicates: the only + /// group, or the combined ones, as a rule may be found via several keys (e.g., ".a, .b" + /// for class="a b"). + /// + private static List? Distinct(List? first, List? combined) + { + if (combined is null) + { + return first; + } + + combined.Sort(); + var count = 0; + + for (var i = 0; i < combined.Count; i++) + { + if (count == 0 || combined[count - 1] != combined[i]) + { + combined[count++] = combined[i]; + } + } + + combined.RemoveRange(count, combined.Count - count); + return combined; + } + + // shared, never modified + private static readonly List NoRules = new(); + /// /// Adds the groups of the keys the element has. /// @@ -318,6 +412,12 @@ private sealed class KeyedRules public KeyedRules? AncestorRules { get; private set; } + // the rules the ancestors (and the element) bring for each element, see RememberAncestors + public ConcurrentDictionary>? AncestorGroups { get; private set; } + + public void RememberAncestors(Boolean remember) => + AncestorGroups = remember && AncestorRules is not null ? new ConcurrentDictionary>() : null; + public void Add(SubjectKey[]? keys, Int32 index) { if (keys is null) diff --git a/src/AngleSharp.Css/Extensions/CssOmExtensions.cs b/src/AngleSharp.Css/Extensions/CssOmExtensions.cs index 232ae3f2..cab72093 100644 --- a/src/AngleSharp.Css/Extensions/CssOmExtensions.cs +++ b/src/AngleSharp.Css/Extensions/CssOmExtensions.cs @@ -7,6 +7,7 @@ namespace AngleSharp.Css.Dom using AngleSharp.Css.Values; using AngleSharp.Dom; using System; + using System.Collections.Generic; using System.Linq; /// @@ -89,26 +90,44 @@ public static ICssValue GetValueOf(this ICssStyleRule rule, String propertyName) /// A new style declaration with the existing or computed values. public static ICssStyleDeclaration Compute(this ICssStyleDeclaration style, ICssComputeContext context) { - var computedStyle = new CssStyleDeclaration(context.Context); var cascaded = style as CssStyleDeclaration; + // The declarations inherited from the parent's computed style are already computed, + // hence only the local ones are computed - the inherited ones are shared. + var local = cascaded?.GetLocalDeclarations() ?? style; + var localList = local as IReadOnlyList; + var computedStyle = new CssStyleDeclaration(context.Context, localList?.Count ?? 0); + var factory = context.Context.GetDeclarationFactory(); + var preservedShorthands = default(List); if (context is IFontComputeContext fonts) { computedStyle.RootFontSize = fonts.RootFontSize; } - // The declarations inherited from the parent's computed style are already computed, - // hence only the local ones are computed - the inherited ones are shared. - var local = cascaded?.GetLocalDeclarations() ?? style; + if (localList is not null) + { + // by index, as enumerating the list through its interface allocates (for every element) + for (var i = 0; i < localList.Count; i++) + { + ComputeLocal(localList[i]); + } + } + else + { + foreach (var property in local) + { + ComputeLocal(property); + } + } - foreach (var property in local) + void ComputeLocal(ICssProperty property) { var computed = property.Compute(context); - var substitutedKeyword = property.RawValue is not ICssSpecialValue && computed.RawValue is ICssSpecialValue; - var info = context.Context.GetDeclarationInfo(property.Name); + // the info is only needed for a value that may be a keyword + var info = default(DeclarationInfo); var initialValue = computed.RawValue is CssInitialValue || - (info.Shorthands.Length > 0 && computed.Value.Isi(CssKeywords.Initial)); + (CssProperty.MaySerializeAsKeyword(computed.RawValue) && (info = factory.Create(property.Name)).Shorthands.Length > 0 && computed.Value.Isi(CssKeywords.Initial)); if ((computed.RawValue is null || substitutedKeyword || initialValue) && property.RawValue is not null && property is CssProperty cssProperty) { @@ -116,18 +135,30 @@ public static ICssStyleDeclaration Compute(this ICssStyleDeclaration style, ICss (computed.RawValue is not CssInitialValue && property.CanBeInherited); var inherited = inherit && context is CssComputeContext cssContext ? cssContext.InheritedValue(property.Name) : null; - var initial = context.Context.GetDeclarationInfo(property.Name).InitialValue; - var value = inherited ?? (initial is null ? null : cssProperty.Converter.Convert(initial.CssText)?.Compute(context)); + var value = inherited ?? (info ?? factory.Create(property.Name)).ConvertInitialValue(cssProperty.Converter)?.Compute(context); computed = new CssProperty(property.Name, cssProperty.Converter, cssProperty.Flags, value, property.IsImportant); } computedStyle.AddProperty(computed); + + // the flags of a declaration are the ones of its info + var flags = property is CssProperty declaration ? declaration.Flags : factory.Create(property.Name).Flags; + + if ((flags & PropertyFlags.PreserveShorthand) != 0) + { + (preservedShorthands ??= new List()).Add(property); + } } - var factory = context.Context.GetDeclarationFactory(); - var preservedShorthands = local - .Where(property => (factory.Create(property.Name).Flags & PropertyFlags.PreserveShorthand) != 0) - .ToArray(); + if (preservedShorthands is null) + { + if (cascaded is not null) + { + computedStyle.InheritLike(cascaded); + } + + return computedStyle; + } foreach (var shorthand in preservedShorthands) { @@ -165,7 +196,7 @@ public static ICssStyleDeclaration Compute(this ICssStyleDeclaration style, ICss internal static CssStyleDeclaration PrepareComputedDeclarations(this ICssStyleDeclaration style, ICssStyleDeclaration parent, ICssComputeContext context) { - var declarations = new CssStyleDeclaration(context.Context); + var declarations = new CssStyleDeclaration(context.Context, style.Length); // Resolve local custom declarations before merging the parent. In // particular, initial must not disappear through IsInherited. diff --git a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs index 31f3dc41..e3fac74d 100644 --- a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs @@ -173,7 +173,7 @@ public static ICssStyleDeclaration ComputeExplicitStyle(this IStyleCollection st if (element is IHtmlElement || element is ISvgElement) { - computedStyle.SetDeclarations(element.GetStyle()); + computedStyle.SetDeclarations(element.GetStyleIfDeclared()); } computedStyle.TrimExcess(); @@ -246,7 +246,7 @@ internal static ICssStyleDeclaration ComputeHostStyle(this IStyleCollection styl ApplyImportantLayerOrder(computedStyle, matches); ReturnMatches(styles, matches); - computedStyle.SetDeclarations(host.GetStyle()); + computedStyle.SetDeclarations(host.GetStyleIfDeclared()); computedStyle.SetDeclarations(shadowStyle.Where(m => m.IsImportant).ToList()); return computedStyle; } diff --git a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs index 58adbb9e..9c86cabf 100644 --- a/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs +++ b/src/AngleSharp.Css/RenderTree/RenderTreeBuilder.cs @@ -63,15 +63,19 @@ public ElementRenderNode RenderDocument(IStyleCollection styles) _cascadedStyles.Clear(); _renderedNodes.Clear(); - _explicitStyles = ComputeExplicitStyles(root, collection); - _explicitStylesCollection = collection; + // the DOM does not change while the tree is built + var index = collection.GetIndex(); + index.RememberAncestors(true); try { + _explicitStyles = ComputeExplicitStyles(root, collection); + _explicitStylesCollection = collection; return RenderElement(root, collection, null, null, null); } finally { + index.RememberAncestors(false); _explicitStyles = null; _explicitStylesCollection = null; } diff --git a/src/AngleSharp.Css/Values/CssComputedValues.cs b/src/AngleSharp.Css/Values/CssComputedValues.cs new file mode 100644 index 00000000..f6d56f7f --- /dev/null +++ b/src/AngleSharp.Css/Values/CssComputedValues.cs @@ -0,0 +1,71 @@ +#nullable enable +namespace AngleSharp.Css.Values +{ + using AngleSharp.Css.Dom; + using System; + + /// + /// Computes the items of multiple values, see ICssComputedValue. + /// + static class CssComputedValues + { + /// + /// Gets if computing the value gives the value itself. + /// + public static Boolean IsComputed(ICssValue? value) => value is ICssComputedValue { IsComputed: true }; + + /// + /// Gets if all items (null ones are left out) are computed already. + /// + public static Boolean AreComputed(T[] items) + where T : ICssValue + { + for (var i = 0; i < items.Length; i++) + { + var item = items[i]; + + if (item is not null && !IsComputed(item)) + { + return false; + } + } + + return true; + } + + /// + /// Computes the items (null ones stay null), or gives null if they are all computed + /// already, i.e., the value is its own computed value. + /// + public static T?[]? Compute(T?[] items, ICssComputeContext context) + where T : ICssValue + { + var computed = default(T?[]); + + for (var i = 0; i < items.Length; i++) + { + var item = items[i]; + + if (item is null || IsComputed(item)) + { + if (computed is not null) + { + computed[i] = item; + } + + continue; + } + + if (computed is null) + { + computed = new T?[items.Length]; + Array.Copy(items, computed, i); + } + + computed[i] = (T?)item.Compute(context); + } + + return computed; + } + } +} diff --git a/src/AngleSharp.Css/Values/Functions/CssNoneValue.cs b/src/AngleSharp.Css/Values/Functions/CssNoneValue.cs index 2e2cb485..c8160d89 100644 --- a/src/AngleSharp.Css/Values/Functions/CssNoneValue.cs +++ b/src/AngleSharp.Css/Values/Functions/CssNoneValue.cs @@ -4,7 +4,7 @@ namespace AngleSharp.Css.Values using AngleSharp.Css.Dom; using System; - sealed class CssNoneValue : ICssImageValue + sealed class CssNoneValue : ICssImageValue, ICssComputedValue { #region Properties @@ -20,6 +20,8 @@ sealed class CssNoneValue : ICssImageValue Boolean IEquatable.Equals(ICssValue other) => Object.ReferenceEquals(this, other); + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) => this; #endregion diff --git a/src/AngleSharp.Css/Values/Functions/CssUrlValue.cs b/src/AngleSharp.Css/Values/Functions/CssUrlValue.cs index c0fc51c8..48673f3d 100644 --- a/src/AngleSharp.Css/Values/Functions/CssUrlValue.cs +++ b/src/AngleSharp.Css/Values/Functions/CssUrlValue.cs @@ -9,7 +9,7 @@ namespace AngleSharp.Css.Values /// Represents an URL object. /// https://developer.mozilla.org/en-US/docs/Web/CSS/uri /// - public sealed class CssUrlValue : ICssImageValue, ICssFunctionValue, IEquatable + public sealed class CssUrlValue : ICssImageValue, ICssFunctionValue, IEquatable, ICssComputedValue { #region Fields @@ -70,6 +70,8 @@ public Boolean Equals(CssUrlValue other) Boolean IEquatable.Equals(ICssValue other) => other is CssUrlValue value && Equals(value); + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/ICssComputedValue.cs b/src/AngleSharp.Css/Values/ICssComputedValue.cs new file mode 100644 index 00000000..66d4dd2f --- /dev/null +++ b/src/AngleSharp.Css/Values/ICssComputedValue.cs @@ -0,0 +1,18 @@ +namespace AngleSharp.Css.Values +{ + using System; + + /// + /// A value that may already be its own computed value, e.g., a color or a length in + /// pixels. Computing such a value gives the value itself, i.e., it does not need to be + /// computed for every element (which boxes a copy of a struct value, and creates the + /// context to compute with and a declaration holding the copy). + /// + interface ICssComputedValue + { + /// + /// Gets if computing the value gives the value itself, in any context. + /// + Boolean IsComputed { get; } + } +} diff --git a/src/AngleSharp.Css/Values/Multiples/CssListValue.cs b/src/AngleSharp.Css/Values/Multiples/CssListValue.cs index d065aa91..229a375f 100644 --- a/src/AngleSharp.Css/Values/Multiples/CssListValue.cs +++ b/src/AngleSharp.Css/Values/Multiples/CssListValue.cs @@ -11,7 +11,7 @@ namespace AngleSharp.Css.Values /// /// Represents a CSS value list. /// - public class CssListValue : ICssMultipleValue, IEquatable> + public class CssListValue : ICssMultipleValue, IEquatable>, ICssComputedValue where T : ICssValue { #region Fields @@ -88,9 +88,16 @@ IEnumerator IEnumerable.GetEnumerator() => IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator(); + Boolean ICssComputedValue.IsComputed => CssComputedValues.AreComputed(_items); + ICssValue ICssValue.Compute(ICssComputeContext context) { - var items = _items.Select(v => (T)v.Compute(context)).ToArray(); + var items = CssComputedValues.Compute(_items, context); + + if (items is null) + { + return this; + } // Keep the specific type, e.g., such that shorthands can merge the computed list. if (this is CssListValue) diff --git a/src/AngleSharp.Css/Values/Multiples/CssTupleValue.cs b/src/AngleSharp.Css/Values/Multiples/CssTupleValue.cs index d02ae7bf..6d79c1c9 100644 --- a/src/AngleSharp.Css/Values/Multiples/CssTupleValue.cs +++ b/src/AngleSharp.Css/Values/Multiples/CssTupleValue.cs @@ -11,7 +11,7 @@ namespace AngleSharp.Css.Values /// /// Represents a tuple of CSS values. /// - public class CssTupleValue : ICssMultipleValue, IEquatable> + public class CssTupleValue : ICssMultipleValue, IEquatable>, ICssComputedValue where T : ICssValue { #region Fields @@ -96,12 +96,20 @@ IEnumerator IEnumerable.GetEnumerator() => IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator(); + Boolean ICssComputedValue.IsComputed => CssComputedValues.AreComputed(_items); + ICssValue ICssValue.Compute(ICssComputeContext context) { // An item can legitimately be null - e.g. `grid-column: 2 / span 2` (the omitted end // line) - calling .Compute() on it unconditionally threw a NullReferenceException for // that ordinary case. - var items = _items.Select(v => v == null ? v : (T)v.Compute(context)).ToArray(); + var items = CssComputedValues.Compute(_items, context); + + if (items is null) + { + return this; + } + // Keep the specific type, e.g., such that shorthands can merge the computed tuple. if (this is CssTupleValue) { diff --git a/src/AngleSharp.Css/Values/Primitives/CssColorValue.cs b/src/AngleSharp.Css/Values/Primitives/CssColorValue.cs index 46be0a84..8c2e301d 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssColorValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssColorValue.cs @@ -12,7 +12,7 @@ namespace AngleSharp.Css.Values /// Represents a color value. /// [StructLayout(LayoutKind.Explicit, Pack = 1, CharSet = CharSet.Unicode)] - public struct CssColorValue : IEquatable, IComparable, ICssPrimitiveValue + public struct CssColorValue : IEquatable, IComparable, ICssPrimitiveValue, ICssComputedValue { #region Basic colors @@ -615,6 +615,8 @@ public override Boolean Equals(Object obj) #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Primitives/CssConstantValue.cs b/src/AngleSharp.Css/Values/Primitives/CssConstantValue.cs index a54f0537..b880bd11 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssConstantValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssConstantValue.cs @@ -7,7 +7,7 @@ namespace AngleSharp.Css.Values /// /// Represents a selected CSS enum value. /// - public readonly struct CssConstantValue : ICssPrimitiveValue, IEquatable> + public readonly struct CssConstantValue : ICssPrimitiveValue, IEquatable>, ICssComputedValue { #region Fields @@ -71,6 +71,8 @@ public override Boolean Equals(Object obj) => /// The hash code of the object. public override Int32 GetHashCode() => _data.GetHashCode(); + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Primitives/CssIdentifierValue.cs b/src/AngleSharp.Css/Values/Primitives/CssIdentifierValue.cs index 35f00269..4960f9e7 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssIdentifierValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssIdentifierValue.cs @@ -8,7 +8,7 @@ namespace AngleSharp.Css.Values /// /// Represents a CSS identifier value. /// - public readonly struct CssIdentifierValue : ICssPrimitiveValue, IEquatable + public readonly struct CssIdentifierValue : ICssPrimitiveValue, IEquatable, ICssComputedValue { #region Fields @@ -70,6 +70,8 @@ public override Boolean Equals(Object obj) => /// The computed hash code. public override Int32 GetHashCode() => _text.GetHashCode(); + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Primitives/CssIntegerValue.cs b/src/AngleSharp.Css/Values/Primitives/CssIntegerValue.cs index 17b02749..ec8f1767 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssIntegerValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssIntegerValue.cs @@ -7,7 +7,7 @@ namespace AngleSharp.Css.Values /// /// Represents an integer value. /// - public readonly struct CssIntegerValue : IEquatable, IComparable, ICssMetricValue + public readonly struct CssIntegerValue : IEquatable, IComparable, ICssMetricValue, ICssComputedValue { #region Basic lengths @@ -77,6 +77,8 @@ public CssIntegerValue(Int32 value) #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Primitives/CssLengthValue.cs b/src/AngleSharp.Css/Values/Primitives/CssLengthValue.cs index 8470c822..23492059 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssLengthValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssLengthValue.cs @@ -8,7 +8,7 @@ namespace AngleSharp.Css.Values /// /// Represents an absolute length value. /// - public readonly struct CssLengthValue : IEquatable, IComparable, ICssMetricValue + public readonly struct CssLengthValue : IEquatable, IComparable, ICssMetricValue, ICssComputedValue { #region Basic lengths @@ -249,6 +249,10 @@ public Int32 CompareTo(CssLengthValue other) #region Methods + // see Compute: a number, a keyword or a length in pixels (a zero one marked as computed) + Boolean ICssComputedValue.IsComputed => + _unit == Unit.None || Double.IsNaN(_value) || (_unit == Unit.Px && (_value != 0.0 || _computed)); + ICssValue ICssValue.Compute(ICssComputeContext context) { if (_unit == Unit.None || Double.IsNaN(_value)) diff --git a/src/AngleSharp.Css/Values/Primitives/CssNumberValue.cs b/src/AngleSharp.Css/Values/Primitives/CssNumberValue.cs index 63a660f2..4ccc5f2e 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssNumberValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssNumberValue.cs @@ -7,7 +7,7 @@ namespace AngleSharp.Css.Values /// /// Represents a number value. /// - public readonly struct CssNumberValue : IEquatable, IComparable, ICssMetricValue + public readonly struct CssNumberValue : IEquatable, IComparable, ICssMetricValue, ICssComputedValue { #region Basic lengths @@ -63,6 +63,8 @@ public CssNumberValue(Double value) #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Primitives/CssPercentageValue.cs b/src/AngleSharp.Css/Values/Primitives/CssPercentageValue.cs index 805d870a..d0890c10 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssPercentageValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssPercentageValue.cs @@ -7,7 +7,7 @@ namespace AngleSharp.Css.Values /// /// Represents a percentage value. /// - public readonly struct CssPercentageValue : IEquatable, IComparable, ICssMetricValue + public readonly struct CssPercentageValue : IEquatable, IComparable, ICssMetricValue, ICssComputedValue { #region Basic percentages @@ -95,6 +95,8 @@ public String UnitString #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Primitives/CssStringValue.cs b/src/AngleSharp.Css/Values/Primitives/CssStringValue.cs index 69c5ac68..d3a0a75e 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssStringValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssStringValue.cs @@ -8,7 +8,7 @@ namespace AngleSharp.Css.Values /// /// Represents a CSS string value. /// - public readonly struct CssStringValue : ICssPrimitiveValue, IEquatable + public readonly struct CssStringValue : ICssPrimitiveValue, IEquatable, ICssComputedValue { #region Fields @@ -45,6 +45,8 @@ public CssStringValue(String value) #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Css/Values/Raws/CssInheritValue.cs b/src/AngleSharp.Css/Values/Raws/CssInheritValue.cs index c3b8c427..28cf3cb4 100644 --- a/src/AngleSharp.Css/Values/Raws/CssInheritValue.cs +++ b/src/AngleSharp.Css/Values/Raws/CssInheritValue.cs @@ -7,7 +7,7 @@ namespace AngleSharp.Css.Values /// /// Represents the CSS inherit value. /// - sealed class CssInheritValue : ICssSpecialValue + sealed class CssInheritValue : ICssSpecialValue, ICssComputedValue { #region ctor @@ -38,6 +38,8 @@ private CssInheritValue() #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) => this; Boolean IEquatable.Equals(ICssValue other) => Object.ReferenceEquals(this, other); diff --git a/src/AngleSharp.Css/Values/Raws/CssInitialValue.cs b/src/AngleSharp.Css/Values/Raws/CssInitialValue.cs index 1078ce4c..037c3d29 100644 --- a/src/AngleSharp.Css/Values/Raws/CssInitialValue.cs +++ b/src/AngleSharp.Css/Values/Raws/CssInitialValue.cs @@ -8,7 +8,7 @@ namespace AngleSharp.Css.Values /// /// Represents the CSS initial value. /// - readonly struct CssInitialValue : ICssSpecialValue + readonly struct CssInitialValue : ICssSpecialValue, ICssComputedValue { #region Fields @@ -45,6 +45,8 @@ public CssInitialValue(ICssValue value) #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) => this; Boolean IEquatable.Equals(ICssValue other) => other is CssInitialValue o && EqualityComparer.Default.Equals(_value, o.Value); diff --git a/src/AngleSharp.Css/Values/Raws/CssUnsetValue.cs b/src/AngleSharp.Css/Values/Raws/CssUnsetValue.cs index 92ea6db2..0d78568d 100644 --- a/src/AngleSharp.Css/Values/Raws/CssUnsetValue.cs +++ b/src/AngleSharp.Css/Values/Raws/CssUnsetValue.cs @@ -8,7 +8,7 @@ namespace AngleSharp.Css.Values /// /// Represents a CSS unset value. /// - readonly struct CssUnsetValue : ICssSpecialValue + readonly struct CssUnsetValue : ICssSpecialValue, ICssComputedValue { #region Fields @@ -45,6 +45,8 @@ public CssUnsetValue(ICssValue value) #region Methods + Boolean ICssComputedValue.IsComputed => true; + ICssValue ICssValue.Compute(ICssComputeContext context) { return this; diff --git a/src/AngleSharp.Performance.Css/LargeSheetRenderBenchmarks.cs b/src/AngleSharp.Performance.Css/LargeSheetRenderBenchmarks.cs new file mode 100644 index 00000000..77548160 --- /dev/null +++ b/src/AngleSharp.Performance.Css/LargeSheetRenderBenchmarks.cs @@ -0,0 +1,125 @@ +namespace AngleSharp.Performance.Css +{ + using AngleSharp; + using AngleSharp.Css; + using AngleSharp.Dom; + using BenchmarkDotNet.Attributes; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + + /// + /// Builds the render tree of a document styled by a large real-world sheet (one of the + /// samples). The markup is generated from the class and id names the sheet uses, so that + /// a good share of its rules actually match and the cascade has real work to do. + /// + [MemoryDiagnoser] + public class LargeSheetRenderBenchmarks + { + private static readonly String[] Tags = { "div", "section", "article", "ul", "li", "p", "span", "a", "button", "nav" }; + + private String _html = null!; + private IWindow _window = null!; + + [Params("maxcdn.bootstrapcdn", "florian-rappl", "s.yimg")] + public String CssFileName { get; set; } = null!; + + [GlobalSetup] + public void Setup() + { + var path = Path.Combine(AppContext.BaseDirectory, "Samples", CssFileName + ".css"); + var source = File.ReadAllText(path); + _html = BuildDocument(source); + _window = Load(_html).DefaultView!; + } + + /// + /// Rendering a document that is already loaded (sheet parsed, rule index warm). + /// + [Benchmark] + public Object RenderTree() => _window.Render(); + + /// + /// Loading the document (including the sheet) and rendering it once. + /// + [Benchmark] + public Object LoadAndRenderTree() => Load(_html).DefaultView!.Render(); + + private static IDocument Load(String html) + { + var config = Configuration.Default + .WithRenderDevice(new DefaultRenderDevice + { + ViewPortWidth = 1280, + ViewPortHeight = 800, + }) + .WithCss(); + var context = BrowsingContext.New(config); + return context.OpenAsync(req => req.Content(html)).GetAwaiter().GetResult(); + } + + private static String BuildDocument(String css) + { + var classes = Regex.Matches(css, @"\.(-?[_a-zA-Z][_a-zA-Z0-9-]*)") + .Cast() + .Select(m => m.Groups[1].Value) + .Distinct() + .ToArray(); + var ids = Regex.Matches(css, @"#(-?[_a-zA-Z][_a-zA-Z0-9-]*)\s*[{,.:\[ >+~]") + .Cast() + .Select(m => m.Groups[1].Value) + .Distinct() + .ToArray(); + var random = new Random(42); + var sb = new StringBuilder(); + sb.Append(""); + var count = 0; + AppendChildren(sb, random, classes, ids, 0, ref count); + sb.Append(""); + return sb.ToString(); + } + + private static void AppendChildren(StringBuilder sb, Random random, String[] classes, String[] ids, Int32 depth, ref Int32 count) + { + var children = depth == 0 ? 30 : random.Next(1, 5); + + for (var i = 0; i < children && count < 3000; i++) + { + var tag = Tags[random.Next(Tags.Length)]; + count++; + sb.Append('<').Append(tag); + + if (classes.Length > 0) + { + sb.Append(" class='"); + var n = random.Next(1, 4); + + for (var k = 0; k < n; k++) + { + sb.Append(classes[random.Next(classes.Length)]).Append(' '); + } + + sb.Append('\''); + } + + if (ids.Length > 0 && random.Next(20) == 0) + { + sb.Append(" id='").Append(ids[random.Next(ids.Length)]).Append('\''); + } + + sb.Append('>'); + + if (depth < 8) + { + AppendChildren(sb, random, classes, ids, depth + 1, ref count); + } + + sb.Append("Text ").Append(count); + sb.Append("'); + } + } + } +} From ba841d2d52f39889711c6f2f45517df4994c35de Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 17:47:08 +0100 Subject: [PATCH 06/12] Removed value tuple --- .../Declarations/SetPropertyOverwriteTests.cs | 75 +++++++++++-------- .../Extensions/MatchMedia.cs | 29 +++++-- .../Styling/InheritanceChainTests.cs | 21 +++++- .../Styling/PartialRenderTreeTests.cs | 23 ++++-- 4 files changed, 107 insertions(+), 41 deletions(-) diff --git a/src/AngleSharp.Css.Tests/Declarations/SetPropertyOverwriteTests.cs b/src/AngleSharp.Css.Tests/Declarations/SetPropertyOverwriteTests.cs index a3b2b8b4..32865324 100644 --- a/src/AngleSharp.Css.Tests/Declarations/SetPropertyOverwriteTests.cs +++ b/src/AngleSharp.Css.Tests/Declarations/SetPropertyOverwriteTests.cs @@ -21,36 +21,49 @@ namespace AngleSharp.Css.Tests.Declarations [TestFixture] public class SetPropertyOverwriteTests { - private static readonly (String Input, String Expected)[] Cases = + private readonly struct OverwriteCase { - ("color:red;color:blue", "color: rgba(0, 0, 255, 1)"), - ("color:blue;color:red", "color: rgba(255, 0, 0, 1)"), - ("color:red;color:notacolor", "color: rgba(255, 0, 0, 1)"), - ("color:red !important;color:blue", "color: rgba(255, 0, 0, 1) !important"), - ("color:red;color:blue !important", "color: rgba(0, 0, 255, 1) !important"), - ("color:red !important;color:blue !important", "color: rgba(0, 0, 255, 1) !important"), - ("--x:1;--x:2", "--x: 2"), - ("--x:1;color:red", "--x: 1; color: rgba(255, 0, 0, 1)"), - ("margin:1px;margin-top:2px", "margin-bottom: 1px; margin-left: 1px; margin-right: 1px; margin-top: 2px"), - ("margin-top:2px;margin:1px", "margin-bottom: 1px; margin-left: 1px; margin-right: 1px; margin-top: 1px"), - ("margin:1px;margin:notalength", "margin-bottom: 1px; margin-left: 1px; margin-right: 1px; margin-top: 1px"), - ("margin:1px !important;margin-top:2px", "margin-bottom: 1px !important; margin-left: 1px !important; margin-right: 1px !important; margin-top: 1px !important"), - ("padding:1px 2px;padding-left:9px;padding:3px", "padding-bottom: 3px; padding-left: 3px; padding-right: 3px; padding-top: 3px"), - ("border-radius:4px;border-top-left-radius:9px", "border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-left-radius: 9px; border-top-right-radius: 4px"), - ("flex:1 1 auto;flex-grow:5", "flex-basis: auto; flex-grow: 5; flex-shrink: 1"), - ("overflow:hidden;overflow-x:scroll", "overflow-x: scroll; overflow: hidden"), - ("grid-area:a;grid-row:2", "grid-column-end: a; grid-column-start: a; grid-row-end: auto; grid-row-start: 2"), - ("grid-row:2;grid-area:a", "grid-column-end: a; grid-column-start: a; grid-row-end: a; grid-row-start: a"), - ("transition:all .3s;transition-duration:1s", "transition-delay: initial; transition-duration: 1s; transition-property: all; transition-timing-function: initial"), - ("font:bold 14px/1.2 Arial;font-size:20px", "font-family: Arial; font-size: 20px; font-stretch: ; font-style: ; font-variant-caps: ; font-weight: bold; line-height: 1.2"), - ("font-size:20px;font:bold 14px/1.2 Arial", "font-family: Arial; font-size: 14px; font-stretch: ; font-style: ; font-variant-caps: ; font-weight: bold; line-height: 1.2"), - ("border:1px solid red;border-width:3px", "border-bottom-color: rgba(255, 0, 0, 1); border-bottom-style: solid; border-bottom-width: 3px; border-left-color: rgba(255, 0, 0, 1); border-left-style: solid; border-left-width: 3px; border-right-color: rgba(255, 0, 0, 1); border-right-style: solid; border-right-width: 3px; border-top-color: rgba(255, 0, 0, 1); border-top-style: solid; border-top-width: 3px"), - ("border-width:3px;border:1px solid red", "border-bottom-color: rgba(255, 0, 0, 1); border-bottom-style: solid; border-bottom-width: 1px; border-left-color: rgba(255, 0, 0, 1); border-left-style: solid; border-left-width: 1px; border-right-color: rgba(255, 0, 0, 1); border-right-style: solid; border-right-width: 1px; border-top-color: rgba(255, 0, 0, 1); border-top-style: solid; border-top-width: 1px"), - ("background:red;background:blue", "background-attachment: initial; background-clip: initial; background-color: rgba(0, 0, 255, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), - ("background:red;background-color:blue", "background-attachment: initial; background-clip: initial; background-color: rgba(0, 0, 255, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), - ("background-color:blue;background:red", "background-attachment: initial; background-clip: initial; background-color: rgba(255, 0, 0, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), - ("background:red;background:", "background-attachment: initial; background-clip: initial; background-color: rgba(255, 0, 0, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), - ("background:linear-gradient(red,blue);background:none", "background-attachment: initial; background-clip: initial; background-color: initial; background-image: none; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), + public OverwriteCase(String input, String expected) + { + Input = input; + Expected = expected; + } + + public String Input { get; } + + public String Expected { get; } + } + + private static readonly OverwriteCase[] Cases = + { + new OverwriteCase("color:red;color:blue", "color: rgba(0, 0, 255, 1)"), + new OverwriteCase("color:blue;color:red", "color: rgba(255, 0, 0, 1)"), + new OverwriteCase("color:red;color:notacolor", "color: rgba(255, 0, 0, 1)"), + new OverwriteCase("color:red !important;color:blue", "color: rgba(255, 0, 0, 1) !important"), + new OverwriteCase("color:red;color:blue !important", "color: rgba(0, 0, 255, 1) !important"), + new OverwriteCase("color:red !important;color:blue !important", "color: rgba(0, 0, 255, 1) !important"), + new OverwriteCase("--x:1;--x:2", "--x: 2"), + new OverwriteCase("--x:1;color:red", "--x: 1; color: rgba(255, 0, 0, 1)"), + new OverwriteCase("margin:1px;margin-top:2px", "margin-bottom: 1px; margin-left: 1px; margin-right: 1px; margin-top: 2px"), + new OverwriteCase("margin-top:2px;margin:1px", "margin-bottom: 1px; margin-left: 1px; margin-right: 1px; margin-top: 1px"), + new OverwriteCase("margin:1px;margin:notalength", "margin-bottom: 1px; margin-left: 1px; margin-right: 1px; margin-top: 1px"), + new OverwriteCase("margin:1px !important;margin-top:2px", "margin-bottom: 1px !important; margin-left: 1px !important; margin-right: 1px !important; margin-top: 1px !important"), + new OverwriteCase("padding:1px 2px;padding-left:9px;padding:3px", "padding-bottom: 3px; padding-left: 3px; padding-right: 3px; padding-top: 3px"), + new OverwriteCase("border-radius:4px;border-top-left-radius:9px", "border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-left-radius: 9px; border-top-right-radius: 4px"), + new OverwriteCase("flex:1 1 auto;flex-grow:5", "flex-basis: auto; flex-grow: 5; flex-shrink: 1"), + new OverwriteCase("overflow:hidden;overflow-x:scroll", "overflow-x: scroll; overflow: hidden"), + new OverwriteCase("grid-area:a;grid-row:2", "grid-column-end: a; grid-column-start: a; grid-row-end: auto; grid-row-start: 2"), + new OverwriteCase("grid-row:2;grid-area:a", "grid-column-end: a; grid-column-start: a; grid-row-end: a; grid-row-start: a"), + new OverwriteCase("transition:all .3s;transition-duration:1s", "transition-delay: initial; transition-duration: 1s; transition-property: all; transition-timing-function: initial"), + new OverwriteCase("font:bold 14px/1.2 Arial;font-size:20px", "font-family: Arial; font-size: 20px; font-stretch: ; font-style: ; font-variant-caps: ; font-weight: bold; line-height: 1.2"), + new OverwriteCase("font-size:20px;font:bold 14px/1.2 Arial", "font-family: Arial; font-size: 14px; font-stretch: ; font-style: ; font-variant-caps: ; font-weight: bold; line-height: 1.2"), + new OverwriteCase("border:1px solid red;border-width:3px", "border-bottom-color: rgba(255, 0, 0, 1); border-bottom-style: solid; border-bottom-width: 3px; border-left-color: rgba(255, 0, 0, 1); border-left-style: solid; border-left-width: 3px; border-right-color: rgba(255, 0, 0, 1); border-right-style: solid; border-right-width: 3px; border-top-color: rgba(255, 0, 0, 1); border-top-style: solid; border-top-width: 3px"), + new OverwriteCase("border-width:3px;border:1px solid red", "border-bottom-color: rgba(255, 0, 0, 1); border-bottom-style: solid; border-bottom-width: 1px; border-left-color: rgba(255, 0, 0, 1); border-left-style: solid; border-left-width: 1px; border-right-color: rgba(255, 0, 0, 1); border-right-style: solid; border-right-width: 1px; border-top-color: rgba(255, 0, 0, 1); border-top-style: solid; border-top-width: 1px"), + new OverwriteCase("background:red;background:blue", "background-attachment: initial; background-clip: initial; background-color: rgba(0, 0, 255, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), + new OverwriteCase("background:red;background-color:blue", "background-attachment: initial; background-clip: initial; background-color: rgba(0, 0, 255, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), + new OverwriteCase("background-color:blue;background:red", "background-attachment: initial; background-clip: initial; background-color: rgba(255, 0, 0, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), + new OverwriteCase("background:red;background:", "background-attachment: initial; background-clip: initial; background-color: rgba(255, 0, 0, 1); background-image: initial; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), + new OverwriteCase("background:linear-gradient(red,blue);background:none", "background-attachment: initial; background-clip: initial; background-color: initial; background-image: none; background-origin: initial; background-position-x: initial; background-position-y: initial; background-repeat-x: initial; background-repeat-y: initial; background-size: initial"), }; [Test] @@ -58,8 +71,10 @@ public void RedeclaringAPropertyProducesTheExpectedBlock() { var failures = new List(); - foreach (var (input, expected) in Cases) + foreach (var testCase in Cases) { + var input = testCase.Input; + var expected = testCase.Expected; var actual = Describe(ParseDeclarations(input)); if (!String.Equals(actual, expected, StringComparison.Ordinal)) diff --git a/src/AngleSharp.Css.Tests/Extensions/MatchMedia.cs b/src/AngleSharp.Css.Tests/Extensions/MatchMedia.cs index f500b7dc..b76dc3aa 100644 --- a/src/AngleSharp.Css.Tests/Extensions/MatchMedia.cs +++ b/src/AngleSharp.Css.Tests/Extensions/MatchMedia.cs @@ -26,10 +26,23 @@ public void SupportsAnswersWithoutThrowing(System.String condition, System.Boole Assert.AreEqual(expected, window.Supports(condition)); } - private static (IWindow Window, IElement Element) CreateStyled(System.String style) + private readonly struct StyledElement + { + public StyledElement(IWindow window, IElement element) + { + Window = window; + Element = element; + } + + public IWindow Window { get; } + + public IElement Element { get; } + } + + private static StyledElement CreateStyled(System.String style) { var document = new HtmlParser(new HtmlParserOptions(), BrowsingContext.New(Configuration.Default.WithCss())).ParseDocument($"
"); - return (document.DefaultView, document.GetElementById("d")); + return new StyledElement(document.DefaultView, document.GetElementById("d")); } [TestCase("position", "static")] @@ -41,14 +54,18 @@ private static (IWindow Window, IElement Element) CreateStyled(System.String sty [TestCase("flex-direction", "row")] public void ScriptSeesInitialValuesOfWhatWasNotDeclared(System.String property, System.String expected) { - var (window, element) = CreateStyled(""); + var styled = CreateStyled(""); + var window = styled.Window; + var element = styled.Element; Assert.AreEqual(expected, window.GetComputedStyleOfScript(element).GetPropertyValue(property)); } [Test] public void ScriptSeesWhatWasDeclared() { - var (window, element) = CreateStyled("position: absolute; overflow: hidden"); + var styled = CreateStyled("position: absolute; overflow: hidden"); + var window = styled.Window; + var element = styled.Element; var style = window.GetComputedStyleOfScript(element); Assert.AreEqual("absolute", style.GetPropertyValue("position")); @@ -59,7 +76,9 @@ public void ScriptSeesWhatWasDeclared() [Test] public void TheComputedStyleForDotNetStillTellsWhatWasNotDeclared() { - var (window, element) = CreateStyled(""); + var styled = CreateStyled(""); + var window = styled.Window; + var element = styled.Element; window.GetComputedStyleOfScript(element); Assert.AreEqual(System.String.Empty, window.GetComputedStyle(element).GetPropertyValue("position")); diff --git a/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs b/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs index 21235472..1fc57420 100644 --- a/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/InheritanceChainTests.cs @@ -108,6 +108,22 @@ public void BlockifiedElementsKeepTheirInheritedDeclarations() Assert.AreEqual(1, floating.Count(m => m.Name == "display")); } + private readonly struct BorderExpectation + { + public BorderExpectation(string id, string width, string color) + { + Id = id; + Width = width; + Color = color; + } + + public string Id { get; } + + public string Width { get; } + + public string Color { get; } + } + [Test] public void ShorthandsWithVariablesAreSubstitutedPerElement() { @@ -117,8 +133,11 @@ public void ShorthandsWithVariablesAreSubstitutedPerElement() "

z

"); var tree = document.DefaultView.Render(); - foreach (var (id, width, color) in new[] { ("first", "1px", "rgba(255, 0, 0, 1)"), ("second", "2px", "rgba(0, 0, 255, 1)"), ("third", "1px", "rgba(255, 0, 0, 1)") }) + foreach (var expectation in new[] { new BorderExpectation("first", "1px", "rgba(255, 0, 0, 1)"), new BorderExpectation("second", "2px", "rgba(0, 0, 255, 1)"), new BorderExpectation("third", "1px", "rgba(255, 0, 0, 1)") }) { + var id = expectation.Id; + var width = expectation.Width; + var color = expectation.Color; var computed = Find(tree, id).ComputedStyle; foreach (var side in new[] { "top", "right", "bottom", "left" }) diff --git a/src/AngleSharp.Css.Tests/Styling/PartialRenderTreeTests.cs b/src/AngleSharp.Css.Tests/Styling/PartialRenderTreeTests.cs index 7a455264..8e8e287b 100644 --- a/src/AngleSharp.Css.Tests/Styling/PartialRenderTreeTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/PartialRenderTreeTests.cs @@ -85,21 +85,34 @@ public void APartialTreeOfTheDocumentWithItsStylesIsTheRenderedTree() AssertSame(expected, partial); } + private readonly struct BuiltChildren + { + public BuiltChildren(ElementRenderNode node, System.Collections.Generic.IList children) + { + Node = node; + Children = children; + } + + public ElementRenderNode Node { get; } + + public System.Collections.Generic.IList Children { get; } + } + [Test] public void APartialTreeOfTheDocumentTellsAboutTheChildrenItBuilds() { var document = Parse(); var styles = document.DefaultView.GetStyleCollection(new DefaultRenderDevice { ViewPortWidth = 1000, ViewPortHeight = 800 }); - var built = new System.Collections.Generic.List<(ElementRenderNode, System.Collections.Generic.IList)>(); - var partial = document.DefaultView.RenderPartial(styles, (node, children) => built.Add((node, children.ToList()))); + var built = new System.Collections.Generic.List(); + var partial = document.DefaultView.RenderPartial(styles, (node, children) => built.Add(new BuiltChildren(node, children.ToList()))); var body = partial.Children.OfType().Single(m => m.Ref.LocalName == "body"); var bodyChildren = body.Children.ToList(); _ = partial.Children.ToList(); // the ones read, once; not the ones of the elements in the body - CollectionAssert.AreEqual(new[] { partial, body }, built.Select(m => m.Item1)); - CollectionAssert.AreEqual(partial.Children, built[0].Item2); - CollectionAssert.AreEqual(bodyChildren, built[1].Item2); + CollectionAssert.AreEqual(new[] { partial, body }, built.Select(m => m.Node)); + CollectionAssert.AreEqual(partial.Children, built[0].Children); + CollectionAssert.AreEqual(bodyChildren, built[1].Children); } [Test] From 13fc57f2b30f811bca1f7cd446c79f4eb3bffef0 Mon Sep 17 00:00:00 2001 From: FlorianRappl <1766191+FlorianRappl@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:45:38 +0000 Subject: [PATCH 07/12] Initial plan From e6125bb54c07e5dc331d49230db72850c55029b8 Mon Sep 17 00:00:00 2001 From: FlorianRappl <1766191+FlorianRappl@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:48:30 +0000 Subject: [PATCH 08/12] Avoid value tuples in rounded paths Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../Painting/RecordingContextTests.cs | 16 ++++++++++++++++ src/AngleSharp.Css/Painting/PathGeometry.cs | 16 ++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs b/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs index d8f35df7..0361a92b 100644 --- a/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs +++ b/src/AngleSharp.Css.Tests/Painting/RecordingContextTests.cs @@ -245,6 +245,22 @@ public void PointInRoundedRectangle() Assert.IsFalse(ctx.IsPointInPath(39, 39)); } + [Test] + public void PointInRoundedRectangleWithNegativeDimensions() + { + var ctx = Create(); + ctx.RoundRect(40, 0, -40, 40, 0, 20, 0, 0); + + Assert.IsFalse(ctx.IsPointInPath(1, 1)); + Assert.IsTrue(ctx.IsPointInPath(19, 1)); + + ctx.Reset(); + ctx.RoundRect(0, 40, 40, -40, 0, 0, 0, 20); + + Assert.IsFalse(ctx.IsPointInPath(1, 1)); + Assert.IsTrue(ctx.IsPointInPath(19, 1)); + } + [Test] public void PointInRoundedCornerOfArcTo() { diff --git a/src/AngleSharp.Css/Painting/PathGeometry.cs b/src/AngleSharp.Css/Painting/PathGeometry.cs index 3c0e7b0a..a1389435 100644 --- a/src/AngleSharp.Css/Painting/PathGeometry.cs +++ b/src/AngleSharp.Css/Painting/PathGeometry.cs @@ -210,16 +210,24 @@ public void RoundRect(Double x, Double y, Double w, Double h, Double[] radii, Pa { x += w; w = -w; - (tl, tr) = (tr, tl); - (bl, br) = (br, bl); + var radius = tl; + tl = tr; + tr = radius; + radius = bl; + bl = br; + br = radius; } if (h < 0) { y += h; h = -h; - (tl, bl) = (bl, tl); - (tr, br) = (br, tr); + var radius = tl; + tl = bl; + bl = radius; + radius = tr; + tr = br; + br = radius; } // overlapping corners are scaled down From 708efbb2887bb6b6f3ba82f2e8f44470e939745c Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 17 Nov 2026 13:03:27 +0100 Subject: [PATCH 09/12] Fixes and enhancements --- CHANGELOG.md | 2 + .../Extensions/AnalysisWindow.cs | 4 +- .../ComputedStyleCollectionReuseTests.cs | 75 +++++++++++++++++++ .../Styling/Configuration.cs | 4 +- .../Styling/FontWeightComputedStyleTests.cs | 14 ++++ .../Converters/FontWeightValueConverter.cs | 2 +- .../CssDefaultStyleSheetProvider.cs | 6 +- .../Dom/Internal/StyleCollection.cs | 46 ++++++++++++ .../Extensions/WindowExtensions.cs | 40 +++++++++- .../Primitives/CssRelativeFontWeightValue.cs | 8 +- 10 files changed, 192 insertions(+), 9 deletions(-) create mode 100644 src/AngleSharp.Css.Tests/Styling/ComputedStyleCollectionReuseTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d394f439..b4180c98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Released on Wednesday, November 18 2026. - Improved CSS render tree construction performance - gains up to 50% +- Improved `getComputedStyle` called many times in a row to be much faster +- Fixed headings and table headers in a lighter parent (e.g. `body { font-weight: 300 }`) not being bold - Added the CSS Painting API with the `paint()` image function (#277) - Added support for registered custom properties via `@property` (#274) - Added `CSS.registerProperty()` diff --git a/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs b/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs index db71f93b..1d3d1f6a 100644 --- a/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs +++ b/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs @@ -66,7 +66,7 @@ public void GetComputedStyleImportantHigherNoInheritance() var computedStyle = window.GetComputedStyle(element); Assert.AreEqual("rgba(255, 0, 0, 1)", computedStyle.GetColor()); - Assert.AreEqual("bold", computedStyle.GetFontWeight()); + Assert.AreEqual("700", computedStyle.GetFontWeight()); Assert.AreEqual(3, computedStyle.Length); } @@ -177,7 +177,7 @@ public void GetComputedStyleComplexScenario() Assert.AreEqual("0px", style.GetMargin()); Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetColor()); - Assert.AreEqual("bold", style.GetFontWeight()); + Assert.AreEqual("700", style.GetFontWeight()); Assert.AreEqual("italic", style.GetFontStyle()); Assert.AreEqual("20px", style.GetFontSize()); } diff --git a/src/AngleSharp.Css.Tests/Styling/ComputedStyleCollectionReuseTests.cs b/src/AngleSharp.Css.Tests/Styling/ComputedStyleCollectionReuseTests.cs new file mode 100644 index 00000000..e05f8e1f --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/ComputedStyleCollectionReuseTests.cs @@ -0,0 +1,75 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using NUnit.Framework; + using System.Linq; + using System.Threading.Tasks; + + /// + /// Computed styles asked for one after another reuse the indexed rules of the document, as + /// long as the rules stay the same; any change of them is seen by the next computed style. + /// + [TestFixture] + public class ComputedStyleCollectionReuseTests + { + private static Task LoadAsync(string body) => + BrowsingContext.New(Configuration.Default.WithCss()).OpenAsync(m => m.Content("" + body)); + + private static string ColorOf(IDocument document) => + document.DefaultView.GetComputedStyle(document.GetElementById("t")).GetColor(); + + [Test] + public async Task AddedStyleSheetIsSeen() + { + var document = await LoadAsync("

A

"); + Assert.AreEqual("rgba(255, 0, 0, 1)", ColorOf(document)); + + var style = document.CreateElement("style"); + style.TextContent = "p { color: green }"; + document.Head.AppendChild(style); + + Assert.AreEqual("rgba(0, 128, 0, 1)", ColorOf(document)); + } + + [Test] + public async Task InsertedAndDeletedRulesAreSeen() + { + var document = await LoadAsync("

A

"); + var sheet = document.StyleSheets.OfType().First(); + Assert.AreEqual("rgba(255, 0, 0, 1)", ColorOf(document)); + + sheet.Insert("#t { color: green }", 1); + Assert.AreEqual("rgba(0, 128, 0, 1)", ColorOf(document)); + + // the same number of rules, but another one + sheet.RemoveAt(1); + sheet.Insert("#t { color: blue }", 1); + Assert.AreEqual("rgba(0, 0, 255, 1)", ColorOf(document)); + } + + [Test] + public async Task ChangedSelectorIsSeen() + { + var document = await LoadAsync("

A

"); + var rule = document.StyleSheets.OfType().First().Rules.OfType().Last(); + Assert.AreEqual("rgba(255, 0, 0, 1)", ColorOf(document)); + + rule.SelectorText = "p"; + + Assert.AreEqual("rgba(0, 128, 0, 1)", ColorOf(document)); + } + + [Test] + public async Task DisabledStyleSheetIsSeen() + { + var document = await LoadAsync("

A

"); + Assert.AreEqual("rgba(0, 128, 0, 1)", ColorOf(document)); + + document.StyleSheets.Last().IsDisabled = true; + + Assert.AreEqual("rgba(255, 0, 0, 1)", ColorOf(document)); + } + } +} diff --git a/src/AngleSharp.Css.Tests/Styling/Configuration.cs b/src/AngleSharp.Css.Tests/Styling/Configuration.cs index a973cd49..3e216a72 100644 --- a/src/AngleSharp.Css.Tests/Styling/Configuration.cs +++ b/src/AngleSharp.Css.Tests/Styling/Configuration.cs @@ -52,7 +52,9 @@ public void ObtainDefaultSheet() // 81, not 80: the UA stylesheet now also gives `iframe` its default border. // 85, not 81: the UA stylesheet now also carries the popover rules (hidden unless // shown, centered in the viewport, and the `::backdrop` of a shown popover). - Assert.AreEqual(85, sheet.Rules.Length); + // 86, not 85: headings and `th` are `bold` (as in the HTML standard), `b` and + // `strong` stay `bolder`, which takes a rule of its own. + Assert.AreEqual(86, sheet.Rules.Length); } } } diff --git a/src/AngleSharp.Css.Tests/Styling/FontWeightComputedStyleTests.cs b/src/AngleSharp.Css.Tests/Styling/FontWeightComputedStyleTests.cs index 8ff1f1d5..e1a1e1b1 100644 --- a/src/AngleSharp.Css.Tests/Styling/FontWeightComputedStyleTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/FontWeightComputedStyleTests.cs @@ -77,5 +77,19 @@ public void HeadingUaBolderResolvesToBold() { Assert.AreEqual("700", ComputedFontWeight("

Title

", "target")); } + + [Test] + public void HeadingIsBoldInALightParent() + { + // the UA rule of headings and table headers is `bold`, not `bolder` (which gives 400 after 300) + Assert.AreEqual("700", ComputedFontWeight("

Title

", "target")); + Assert.AreEqual("700", ComputedFontWeight("
Title
", "target")); + } + + [Test] + public void StrongIsBolderInALightParent() + { + Assert.AreEqual("400", ComputedFontWeight("
x
", "target")); + } } } diff --git a/src/AngleSharp.Css/Converters/FontWeightValueConverter.cs b/src/AngleSharp.Css/Converters/FontWeightValueConverter.cs index 1b0bf78c..65fc2d12 100644 --- a/src/AngleSharp.Css/Converters/FontWeightValueConverter.cs +++ b/src/AngleSharp.Css/Converters/FontWeightValueConverter.cs @@ -13,7 +13,7 @@ sealed class FontWeightValueConverter : IValueConverter { var value = _keywords.Convert(source); - if (value is CssConstantValue keyword && (keyword.Value == FontWeight.Bolder || keyword.Value == FontWeight.Lighter)) + if (value is CssConstantValue keyword && (keyword.Value == FontWeight.Bolder || keyword.Value == FontWeight.Lighter || keyword.Value == FontWeight.Bold)) { return new CssRelativeFontWeightValue(keyword); } diff --git a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs index fab842c7..cf7cb41d 100644 --- a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs +++ b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs @@ -96,7 +96,7 @@ private static ICssStyleSheet Parse(String source) colgroup { display: table-column-group } td, th { display: table-cell; padding: 1px } caption { display: table-caption } -th { font-weight: bolder; text-align: center } +th { font-weight: bold; text-align: center } caption { text-align: center } body { margin: 8px } h1 { font-size: 2em; margin: .67em 0 } @@ -112,8 +112,8 @@ private static ICssStyleSheet Parse(String source) h5 { font-size: .83em; margin: 1.5em 0 } h6 { font-size: .75em; margin: 1.67em 0 } h1, h2, h3, h4, -h5, h6, b, -strong { font-weight: bolder } +h5, h6 { font-weight: bold } +b, strong { font-weight: bolder } blockquote, figure { margin-left: 40px; margin-right: 40px } fieldset { margin-left: 2px; margin-right: 2px; border: 2px groove rgb(192, 192, 192); padding: 0.35em 0.75em 0.625em } diff --git a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs index 5f951a26..c44bdccc 100644 --- a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs +++ b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs @@ -22,6 +22,10 @@ sealed class StyleCollection : IStyleCollection private List? _matches; private Int32 _defaultRuleCount; private CssPropertyRegistry? _registry; + private List? _signature; + + // separates the rules of the default sheets from the author's in the signature + private static readonly Object AuthorSheets = new(); #endregion @@ -130,18 +134,53 @@ internal CssPropertyRegistry GetRegistrations() #region Helpers + /// + /// Gets if the other collection is made of the same rules as this one (the same + /// objects, with the same selectors, in the same order, valid for the same device and + /// registrations), so this one's index serves it as well. + /// + internal Boolean HasSameRules(StyleCollection other) + { + if (!ReferenceEquals(_device, other._device) || !ReferenceEquals(Scope, other.Scope)) + { + return false; + } + + GetRules(); + other.GetRules(); + var (mine, theirs) = (_signature!, other._signature!); + + if (mine.Count != theirs.Count) + { + return false; + } + + for (var i = 0; i < mine.Count; i++) + { + if (!ReferenceEquals(mine[i], theirs[i])) + { + return false; + } + } + + return true; + } + private List CollectRules() { var rules = new List(); var layers = new List(); _registry = new CssPropertyRegistry(); + _signature = new List(); AddRules(rules, layers, _defaultSheets); _defaultRuleCount = rules.Count; + _signature.Add(AuthorSheets); AddRules(rules, layers, WithoutEarlierDuplicates(_sheets)); var scripted = _document is not null ? CssScriptPropertyRegistrations.Get(_document) : null; if (scripted is not null) { + _signature.Add(scripted); _registry.RegisterAll(scripted); } _layerRanks = layers.ConvertAll(m => m.Rank); @@ -157,6 +196,7 @@ private void AddRules(List rules, List layers, IEnumerable { if (!sheet.IsDisabled && sheet.Media.Validate(_device)) { + _signature!.Add(sheet); AddRules(rules, layers, sheet.Rules, root); } } @@ -224,9 +264,13 @@ private void AddRules(List rules, List layers, ICssRuleLis { foreach (var rule in list) { + _signature!.Add(rule); + switch (rule) { case ICssStyleRule style: + // a rule given another selector text gets another selector + _signature.Add(style.Selector); rules.Add(style); layers.Add(layer); break; @@ -240,9 +284,11 @@ private void AddRules(List rules, List layers, ICssRuleLis break; case ICssMediaRule media when media.IsValid(_device): + _signature.Add(media.Rules); AddRules(rules, layers, media.Rules, layer); break; case ICssSupportsRule supports when supports.IsValid(_device): + _signature.Add(supports.Rules); AddRules(rules, layers, supports.Rules, layer); break; case ICssLayerRule { IsStatement: true } statement: diff --git a/src/AngleSharp.Css/Extensions/WindowExtensions.cs b/src/AngleSharp.Css/Extensions/WindowExtensions.cs index 56c7fe25..48758cb5 100644 --- a/src/AngleSharp.Css/Extensions/WindowExtensions.cs +++ b/src/AngleSharp.Css/Extensions/WindowExtensions.cs @@ -8,6 +8,7 @@ namespace AngleSharp.Dom using System; using System.Collections.Generic; using System.Linq; + using System.Runtime.CompilerServices; /// /// A set of useful extension methods for the Window class. @@ -115,10 +116,47 @@ public static Double DevicePixelRatio(this IWindow window) public static ICssStyleDeclaration GetComputedStyle(this IWindow window, IElement element, String? pseudo = null) { var device = window.GetRenderDevice(); - var styleCollection = window.GetStyleCollection(device); + var styleCollection = ComputedStyleCollections.Get(window.Document, window.GetStyleCollection(device)); return styleCollection.ComputeDeclarations(element, pseudo); } + /// + /// The style collection of the last computed style of each document: scripts ask for + /// computed styles many times in a row (e.g. Elementor reads the device mode from the + /// body's ::after for every widget), and a new collection indexes all rules again (about + /// 6 ms for 6000 rules). The last one is taken as long as it has the same rules. + /// + private static class ComputedStyleCollections + { + private static readonly ConditionalWeakTable Collections = new(); + + public static IStyleCollection Get(IDocument? document, IStyleCollection fresh) + { + if (document is null || fresh is not StyleCollection collection) + { + return fresh; + } + + var holder = Collections.GetValue(document, _ => new Holder()); + + lock (holder) + { + if (holder.Last is { } last && last.HasSameRules(collection)) + { + return last; + } + + holder.Last = collection; + return collection; + } + } + + private sealed class Holder + { + public StyleCollection? Last; + } + } + /// /// Gets the computed style as script sees it, where a property that was not declared has /// its initial value instead of being empty. diff --git a/src/AngleSharp.Css/Values/Primitives/CssRelativeFontWeightValue.cs b/src/AngleSharp.Css/Values/Primitives/CssRelativeFontWeightValue.cs index 8ebcc184..60e34c6b 100644 --- a/src/AngleSharp.Css/Values/Primitives/CssRelativeFontWeightValue.cs +++ b/src/AngleSharp.Css/Values/Primitives/CssRelativeFontWeightValue.cs @@ -7,7 +7,8 @@ namespace AngleSharp.Css.Values /// /// Represents a relative font weight (bolder or lighter), which computes to - /// a number resolved against the parent's computed weight. + /// a number resolved against the parent's computed weight, or bold, which + /// computes to 700. /// See https://www.w3.org/TR/css-fonts-4/#relative-weights. /// sealed class CssRelativeFontWeightValue : ICssPrimitiveValue, IEquatable @@ -47,6 +48,11 @@ public CssRelativeFontWeightValue(CssConstantValue keyword) ICssValue ICssValue.Compute(ICssComputeContext context) { + if (Value == FontWeight.Bold) + { + return new CssIntegerValue(700); + } + var parent = (context as IInheritingComputeContext)?.InheritedValue(PropertyNames.FontWeight); var weight = GetWeight(parent); var result = Value == FontWeight.Bolder ? Bolder(weight) : Lighter(weight); From ffdf326c9e403450ae19e04c60ae53b9e1d91195 Mon Sep 17 00:00:00 2001 From: FlorianRappl <1766191+FlorianRappl@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:38 +0000 Subject: [PATCH 10/12] Initial plan From 236946a2be585b7dd63dbb1f682b02ecb428c46f Mon Sep 17 00:00:00 2001 From: FlorianRappl <1766191+FlorianRappl@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:25:37 +0000 Subject: [PATCH 11/12] Fix net462 StyleCollection compilation Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/AngleSharp.Css/Dom/Internal/StyleCollection.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs index c44bdccc..1026a921 100644 --- a/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs +++ b/src/AngleSharp.Css/Dom/Internal/StyleCollection.cs @@ -148,7 +148,8 @@ internal Boolean HasSameRules(StyleCollection other) GetRules(); other.GetRules(); - var (mine, theirs) = (_signature!, other._signature!); + var mine = _signature!; + var theirs = other._signature!; if (mine.Count != theirs.Count) { From 46107dd2898e668028e3cf0b88753ee01a251845 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Wed, 18 Nov 2026 21:27:28 +0100 Subject: [PATCH 12/12] Fixed issues in CSS extensions and analysis window tests --- CHANGELOG.md | 2 ++ .../Extensions/AnalysisWindow.cs | 30 +++++++++++++++++++ .../Extensions/CssOmExtensions.cs | 18 +++++++---- .../Extensions/StyleCollectionExtensions.cs | 4 +-- 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4180c98..39fe46eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ Released on Wednesday, November 18 2026. - Improved CSS render tree construction performance - gains up to 50% - Improved `getComputedStyle` called many times in a row to be much faster - Fixed headings and table headers in a lighter parent (e.g. `body { font-weight: 300 }`) not being bold +- Fixed `getComputedStyle` giving `unset` instead of the inherited value of an inherited property or the initial one of another (e.g. `position: unset` was not `static`) +- Fixed `getComputedStyle` not blockifying the `display` of flex and grid items - Added the CSS Painting API with the `paint()` image function (#277) - Added support for registered custom properties via `@property` (#274) - Added `CSS.registerProperty()` diff --git a/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs b/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs index 1d3d1f6a..3c09e3d4 100644 --- a/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs +++ b/src/AngleSharp.Css.Tests/Extensions/AnalysisWindow.cs @@ -30,6 +30,36 @@ public void GetComputedStyleTrivialInitialScenario() Assert.AreEqual(2, style.Length); } + [Test] + public void GetComputedStyleResolvesUnsetToInitialOrInherited() + { + // skve.de's navigation is `position: unset` inside a relative header: static, so its + // absolutely positioned dropdowns refer to the header + var source = "
"; + var document = ParseDocument(source); + var window = document.DefaultView; + var nav = document.QuerySelector("nav"); + + var style = window.GetComputedStyle(nav); + + Assert.AreEqual("static", style.GetPosition()); + Assert.AreEqual("rgba(255, 0, 0, 1)", style.GetColor()); + } + + [Test] + public void GetComputedStyleBlockifiesFlexAndGridItems() + { + var source = "
LinkBoxNone
Item
"; + var document = ParseDocument(source); + var window = document.DefaultView; + + Assert.AreEqual("block", window.GetComputedStyle(document.QuerySelector(".flex > a")).GetDisplay()); + Assert.AreEqual("flex", window.GetComputedStyle(document.QuerySelector(".flex > span")).GetDisplay()); + Assert.AreEqual("none", window.GetComputedStyle(document.QuerySelector(".flex > b")).GetDisplay()); + Assert.AreEqual("block", window.GetComputedStyle(document.QuerySelector(".grid > i")).GetDisplay()); + Assert.AreEqual("inline-block", window.GetComputedStyle(document.QuerySelector("#plain")).GetDisplay()); + } + [Test] public void GetComputedStyleImportantHigherNoInheritance() { diff --git a/src/AngleSharp.Css/Extensions/CssOmExtensions.cs b/src/AngleSharp.Css/Extensions/CssOmExtensions.cs index cab72093..42120e24 100644 --- a/src/AngleSharp.Css/Extensions/CssOmExtensions.cs +++ b/src/AngleSharp.Css/Extensions/CssOmExtensions.cs @@ -126,7 +126,8 @@ void ComputeLocal(ICssProperty property) var substitutedKeyword = property.RawValue is not ICssSpecialValue && computed.RawValue is ICssSpecialValue; // the info is only needed for a value that may be a keyword var info = default(DeclarationInfo); - var initialValue = computed.RawValue is CssInitialValue || + // `unset` is `inherit` for an inherited property and `initial` otherwise + var initialValue = computed.RawValue is CssInitialValue or CssUnsetValue || (CssProperty.MaySerializeAsKeyword(computed.RawValue) && (info = factory.Create(property.Name)).Shorthands.Length > 0 && computed.Value.Isi(CssKeywords.Initial)); if ((computed.RawValue is null || substitutedKeyword || initialValue) && property.RawValue is not null && property is CssProperty cssProperty) @@ -240,15 +241,16 @@ private static void AddRegisteredProperties(CssStyleDeclaration declarations, IC } /// - /// Blockifies the computed display of a floated box, an absolutely positioned box - /// and the root element, see CSS Display 3 §2.7 and CSS 2.1 §9.7. + /// Blockifies the computed display of a floated box, an absolutely positioned box, + /// a flex or grid item and the root element, see CSS Display 3 §2.7 and CSS 2.1 §9.7. /// /// The computed style of the element. /// The element the style was computed for. + /// The computed style of the element's parent, if any. /// The computed style, adjusted if needed. - internal static ICssStyleDeclaration Blockify(this ICssStyleDeclaration style, IElement element) + internal static ICssStyleDeclaration Blockify(this ICssStyleDeclaration style, IElement element, ICssStyleDeclaration parent = null) { - if (style is CssStyleDeclaration declarations && IsBlockified(declarations, element)) + if (style is CssStyleDeclaration declarations && (IsBlockified(declarations, element) || IsFlexOrGridItem(parent))) { // display has neither shorthands nor is it inherited, i.e., there is nothing to // derive: a missing declaration is the same as one without a value. @@ -282,6 +284,12 @@ private static Boolean IsBlockified(CssStyleDeclaration style, IElement element) position.Isi(CssKeywords.Absolute) || position.Isi(CssKeywords.Fixed); } + // the children of a flex or grid container are its items (CSS Flexbox §4, CSS Grid §6) + private static Boolean IsFlexOrGridItem(ICssStyleDeclaration parent) => + parent is CssStyleDeclaration declarations && + declarations.GetDeclaration(PropertyNames.Display)?.RawValue is CssConstantValue mode && + mode.Value is DisplayMode.Flex or DisplayMode.InlineFlex or DisplayMode.Grid or DisplayMode.InlineGrid; + private static ICssValue Blockify(ICssValue display) { // A missing display property computes to its initial value, i.e., inline. diff --git a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs index e3fac74d..29de0f84 100644 --- a/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs +++ b/src/AngleSharp.Css/Extensions/StyleCollectionExtensions.cs @@ -120,7 +120,7 @@ private static ICssStyleDeclaration GetComputedDeclarations(IStyleCollection sty var node = nodes.Pop(); var explicitStyle = styles.ComputeExplicitStyle(node); var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parent, (styles as StyleCollection)?.GetRegistrations()); - parent = explicitStyle.PrepareComputedDeclarations(parent!, context).Compute(context).Blockify(node); + parent = explicitStyle.PrepareComputedDeclarations(parent!, context).Compute(context).Blockify(node, parent); } return parent!; @@ -197,7 +197,7 @@ public static ICssStyleDeclaration ComputeDeclarationsWithParent(this IStyleColl var ctx = element.Owner?.Context; var explicitStyle = styles.ComputeExplicitStyle(element); var context = new CssComputeContext(styles.Device, ctx, explicitStyle, parentComputedStyle, (styles as StyleCollection)?.GetRegistrations()); - return explicitStyle.PrepareComputedDeclarations(parentComputedStyle, context).Compute(context).Blockify(element); + return explicitStyle.PrepareComputedDeclarations(parentComputedStyle, context).Compute(context).Blockify(element, parentComputedStyle); } ///