diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e37164c1..ebceb353 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,45 +4,8 @@ on: [push, pull_request] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCS_PATH: ${{ secrets.DOCS_PATH }} - DOCS_BRANCH: ${{ secrets.DOCS_BRANCH }} jobs: - can_document: - runs-on: ubuntu-latest - outputs: - value: ${{ steps.check_job.outputs.value }} - steps: - - name: Checks whether documentation can be built - id: check_job - run: | - echo "value: ${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - echo "::set-output name=value::${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - - documentation: - needs: [can_document] - runs-on: ubuntu-latest - if: needs.can_document.outputs.value == 'true' - - steps: - - uses: actions/checkout@v5 - - - name: Use Node.js - uses: actions/setup-node@v5 - with: - node-version: "20.x" - registry-url: 'https://registry.npmjs.org' - - - name: Install Dependencies - run: | - cd $DOCS_PATH - npm install - - - name: Deploy Doclet - run: | - cd $DOCS_PATH - npx pilet publish --fresh --url https://feed.piral.cloud/api/v1/pilet/anglesharp --api-key ${{ secrets.PIRAL_FEED_KEY }} - linux: runs-on: ubuntu-latest @@ -56,7 +19,7 @@ jobs: 10.0.x - name: Build - run: ./build.sh -AngleSharpVersion 1.10.0 + run: ./build.sh -AngleSharpVersion 1.11.0 windows: runs-on: windows-latest @@ -87,9 +50,9 @@ jobs: NUGET_API_KEY: ${{ steps.nuget_login.outputs.NUGET_API_KEY }} run: | if ($env:GITHUB_REF -eq "refs/heads/main") { - .\build.ps1 -Target Publish -AngleSharpVersion 1.10.0 + .\build.ps1 -Target Publish -AngleSharpVersion 1.11.0 } elseif ($env:GITHUB_REF -eq "refs/heads/devel") { - .\build.ps1 -Target PrePublish -AngleSharpVersion 1.10.0 + .\build.ps1 -Target PrePublish -AngleSharpVersion 1.11.0 } else { - .\build.ps1 -AngleSharpVersion 1.10.0 + .\build.ps1 -AngleSharpVersion 1.11.0 } diff --git a/AGENTS.md b/AGENTS.md index 29170523..639459d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ dotnet run --project src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.c Notes: -- CI invokes `./build.sh -AngleSharpVersion 1.10.0` on Linux and `./build.ps1` on Windows. +- CI invokes `./build.sh -AngleSharpVersion 1.11.0` on Linux and `./build.ps1` on Windows. - Treat warnings as errors is enabled in `src/Directory.Build.props`. ## 3) Build and target framework facts @@ -43,7 +43,7 @@ Notes: - Library project: `src/AngleSharp.Css/AngleSharp.Css.csproj` - Targets: `netstandard2.0;net8.0;net10.0` - Additional Windows-only targets: `net462;net472` - - The AngleSharp dependency defaults to version `1.10.0` and allows versions below `2.0.0`. + - The AngleSharp dependency defaults to version `1.11.0` and allows versions below `2.0.0`. - The `net8.0` and `net10.0` targets set `IsAotCompatible`, so trim and AOT analyzer warnings fail the build. - Test project: `src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj` - Targets: `net8.0` diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fe46eb..74fe819a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,32 @@ +# 1.6.0 + +Released on Tuesday, November 24 2026. + +- Fixed a comment in a declaration's value with a quote in it (e.g. `/* shouldn't */`) starting a string, which swallowed the rest of the style sheet (Acid2) +- Fixed an escaped `}` or `;` in a declaration's value (e.g. `error: \}`) ending the rule +- Fixed a `;` after a rule (e.g. `a { color: red; };`) being skipped instead of making the selector of the next rule invalid, which then applied +- Fixed `! important` with whitespace after the `!` not making the declaration important +- Fixed the `color` media feature, e.g. `(color)` and `(min-color: 0)` not matching, and `monochrome` without a value +- Fixed `not` making a media query with an unknown feature (e.g. `not all and (bogus)`) match +- Fixed `minmax()` with a math function (e.g. `repeat(auto-fill, minmax(min(100%, 17rem), 1fr))`) making `grid-template-columns` invalid in an auto repeat +- Fixed `@scope` rules never applying; a scope root and limit (`@scope (.a) to (.b)`) are respected +- Fixed color hints (e.g. `linear-gradient(black, 20%, white)`) and color interpolation methods (e.g. `in oklch`, `in hsl longer hue`) making a gradient invalid +- Fixed `conic-gradient` with both `from` and `at` being serialized with a comma between them +- Fixed `getComputedStyle` of a shadow host leaving out the `:host` rules of its shadow tree +- Fixed `getComputedStyle` of an element in a shadow tree ignoring the styles of its shadow root and not inheriting from the host +- Fixed `::marker`, `::first-line` and `::first-letter` rules never matching (e.g. for `getComputedStyle(li, '::marker')`) +- Fixed `AppendDefault` of the default style sheet provider dropping what was appended before +- Fixed a closed `details` showing more than its `summary` +- Fixed `transition-property` not accepting custom properties +- Fixed angles being computed in `rad` instead of the canonical `deg` +- Updated minimum version of AngleSharp to 1.11.0 +- Added `::part()` styling the parts of shadow trees +- Added the `:modal` pseudo-class and the user agent styles of `dialog` +- Added the `:fullscreen` pseudo-class, which a host forces (`SetPseudoClass`) on the element it shows fullscreen, and its user agent styles +- Added `IAnimatedValueProvider` as the animation origin of the cascade +- Added `GetImageSource()` for `img` elements and `ImageSource` of render nodes +- Added `CssDom.Register`, the DOM of this library declared for a scripting engine + # 1.5.0 Released on Wednesday, November 18 2026. diff --git a/docs/general/05-Extensibility.md b/docs/general/05-Extensibility.md index bd0d64b5..d834f281 100644 --- a/docs/general/05-Extensibility.md +++ b/docs/general/05-Extensibility.md @@ -89,6 +89,18 @@ The dictionary is keyed by the media feature name and holds the keyword the feat The value is compared to the queried keyword case insensitively, so a keyword that is newer than this library works as well. Used without a value, e.g., `@media (prefers-reduced-motion)`, the feature evaluates in a boolean context, where `no-preference` (and `none` for `forced-colors`, `hover`, `any-hover`, `pointer` and `any-pointer`) is `false`. Without a preference `hover` and `pointer` keep answering as they did before, i.e., as a device with no input mechanism. +## Expose The CSSOM To Scripts Without Reflection + +A scripting engine such as AngleSharp.Js finds the CSSOM by reflecting over its DOM attributes by default. A trimmed or natively compiled (AoT) application can instead hand the engine the registration that is generated for this library at build time, `AngleSharp.Css.CssDom.Register` (a `DomRegistration` of AngleSharp). It declares the CSSOM types, the `CSS` namespace and the members the library adds to the DOM, such as `element.style` or `getComputedStyle`: + +```cs +var config = Configuration.Default + .WithCss() + .WithJs(CssDom.Register); +``` + +The registration describes the version of AngleSharp.Css in use, so it never has to be kept in sync by hand. Several libraries are combined with `DomRegistrations.Combine`. + ## Composition Pattern Start from the default registrations and replace only what you need: diff --git a/src/AngleSharp.Css.Docs/docs.config.json b/src/AngleSharp.Css.Docs/docs.config.json deleted file mode 100644 index f3174b55..00000000 --- a/src/AngleSharp.Css.Docs/docs.config.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "AngleSharp.Css", - "author": "Florian Rappl", - "branch": "devel", - "repositoryUrl": "https://github.com/AngleSharp/AngleSharp.Css", - "rootDir": "../../", - "outputDir": "./dist", - "sitemap": { - "general": { - "sections": [ - { - "generator": "markdown", - "segment": "css", - "dir": "general" - } - ] - }, - "docs": { - "sections": [ - { - "generator": "markdown", - "segment": "css", - "dir": "tutorials" - } - ] - } - } -} \ No newline at end of file diff --git a/src/AngleSharp.Css.Docs/package.json b/src/AngleSharp.Css.Docs/package.json deleted file mode 100644 index fb31480e..00000000 --- a/src/AngleSharp.Css.Docs/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@anglesharp/css", - "version": "1.5.0", - "preview": true, - "description": "The doclet for the AngleSharp.Css documentation.", - "keywords": [ - "pilet" - ], - "dependencies": {}, - "devDependencies": { - "@anglesharp/website": "1.0.0", - "@types/react": "^17.0.5", - "@types/react-dom": "^17.0.5", - "@types/react-router": "latest", - "@types/react-router-dom": "^5.1.7", - "@types/node": "^15.3.0", - "typescript": "^4.2.4", - "@dbeining/react-atom": "4.1.19", - "@libre/atom": "1.3.3", - "history": "4.10.1", - "react": "17.0.2", - "react-dom": "17.0.2", - "react-router": "5.2.0", - "react-router-dom": "5.2.0", - "tslib": "2.2.0", - "path-to-regexp": "1.8.0", - "piral-cli": "^0.13.3-pre.2480", - "piral-cli-parcel": "^0.13.3-pre.2480" - }, - "peerDependencies": { - "@dbeining/react-atom": "*", - "@libre/atom": "*", - "history": "*", - "react": "*", - "react-dom": "*", - "react-router": "*", - "react-router-dom": "*", - "tslib": "*", - "path-to-regexp": "*", - "@anglesharp/website": "*" - }, - "scripts": { - "start": "pilet debug", - "build": "pilet build", - "upgrade": "pilet upgrade" - }, - "main": "dist/index.js", - "files": [ - "dist" - ], - "piral": { - "comment": "Keep this section to use the Piral CLI.", - "name": "@anglesharp/website" - }, - "peerModules": [ - "piral-docs-tools/components" - ] -} diff --git a/src/AngleSharp.Css.Docs/src/index.tsx b/src/AngleSharp.Css.Docs/src/index.tsx deleted file mode 100644 index dc50b37f..00000000 --- a/src/AngleSharp.Css.Docs/src/index.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { PiletApi } from 'piral-docs-tools'; - -const createDoclet = require('piral-docs-tools/doclet'); - -export function setup(api: PiletApi) { - createDoclet(api); -} diff --git a/src/AngleSharp.Css.Docs/tsconfig.json b/src/AngleSharp.Css.Docs/tsconfig.json deleted file mode 100644 index 610060fb..00000000 --- a/src/AngleSharp.Css.Docs/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "declaration": true, - "noImplicitAny": false, - "removeComments": false, - "noLib": false, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es6", - "sourceMap": true, - "outDir": "./dist", - "skipLibCheck": true, - "lib": ["dom", "es2018"], - "moduleResolution": "node", - "module": "esnext", - "jsx": "react", - "importHelpers": true - }, - "include": [ - "./src" - ], - "exclude": [ - "node_modules" - ] -} diff --git a/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj b/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj index 4bf64b57..eee8460d 100644 --- a/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj +++ b/src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs b/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs index 65bf7f2d..2c52b9d2 100644 --- a/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs +++ b/src/AngleSharp.Css.Tests/Declarations/CssGridProperty.cs @@ -155,6 +155,33 @@ public void CssGridTemplateColumnsLengthAutoRepeatLengthLegal() Assert.AreEqual("200px repeat(auto-fill, 100px) 300px", property.Value); } + [Test] + public void CssGridTemplateColumnsAutoRepeatMinmaxOfMathFunctionLegal() + { + var snippet = "grid-template-columns: repeat(auto-fill, minmax(min(100%, 17rem), 1fr))"; + var property = ParseDeclaration(snippet); + Assert.AreEqual("grid-template-columns", property.Name); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("repeat(auto-fill, minmax(min(100%, 17rem), 1fr))", property.Value); + } + + [Test] + public void CssGridTemplateColumnsAutoRepeatMinmaxOfCalcLegal() + { + var snippet = "grid-template-columns: repeat(auto-fit, minmax(calc(10rem + 2px), 1fr))"; + var property = ParseDeclaration(snippet); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("repeat(auto-fit, minmax(calc(10rem + 2px), 1fr))", property.Value); + } + + [Test] + public void CssGridTemplateColumnsAutoRepeatMinmaxWithoutFixedBreadthIllegal() + { + var snippet = "grid-template-columns: repeat(auto-fill, minmax(auto, 1fr))"; + var property = ParseDeclaration(snippet); + Assert.IsFalse(property.HasValue); + } + [Test] public void CssGridTemplateColumnsMultilineLinenamesAutoRepeatLegal() { diff --git a/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs b/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs index db5ac62c..97350806 100644 --- a/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs +++ b/src/AngleSharp.Css.Tests/Declarations/CssTransitionProperty.cs @@ -63,6 +63,22 @@ public void CssTransitionPropertyDashSpecificIllegal() Assert.IsFalse(property.HasValue); } + [Test] + public void CssTransitionPropertyCustomPropertyLegal() + { + var property = ParseDeclaration("transition-property : opacity, --My-Angle"); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("opacity, --My-Angle", property.Value); + } + + [Test] + public void CssTransitionWithCustomPropertyLegal() + { + var property = ParseDeclaration("transition : --angle 1s"); + Assert.IsTrue(property.HasValue); + Assert.AreEqual("--angle 1s", property.Value); + } + [Test] public void CssTransitionPropertySlidingVerticallyIllegal() { diff --git a/src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs b/src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs new file mode 100644 index 00000000..30dbca5b --- /dev/null +++ b/src/AngleSharp.Css.Tests/Extensions/Acid3Tests.cs @@ -0,0 +1,68 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Extensions +{ + using AngleSharp.Css.Dom; + using AngleSharp.Css.Parser; + using AngleSharp.Dom; + using AngleSharp.Html.Parser; + using NUnit.Framework; + + /// + /// Behavior the Acid3 test (acid3.acidtests.org) relies on. + /// + [TestFixture] + public class Acid3Tests + { + [TestCase("color: red ! important", "rgba(255, 0, 0, 1)")] + [TestCase("color: red !important", "rgba(255, 0, 0, 1)")] + [TestCase("color: red!IMPORTANT ", "rgba(255, 0, 0, 1)")] + [TestCase("border: 1px solid ! important", "1px solid")] + public void ImportantMayHaveWhitespaceAfterTheBang(System.String declaration, System.String expected) + { + var parser = new CssParser(); + var sheet = parser.ParseStyleSheet($"p {{ {declaration} }}"); + var style = ((ICssStyleRule)sheet.Rules[0]).Style; + var name = declaration.Substring(0, declaration.IndexOf(':')); + + Assert.AreEqual("important", style.GetPropertyPriority(name)); + Assert.AreEqual(expected, style.GetPropertyValue(name)); + } + + [Test] + public void ImportantNeedsTheBang() + { + var parser = new CssParser(); + var sheet = parser.ParseStyleSheet("p { color: red important }"); + var style = ((ICssStyleRule)sheet.Rules[0]).Style; + + Assert.AreEqual(System.String.Empty, style.GetPropertyPriority("color")); + } + + [TestCase("all and (min-color: 0)", true)] + [TestCase("(color)", true)] + [TestCase("(min-color: 1)", true)] + [TestCase("(max-color: 0)", false)] + [TestCase("(monochrome)", false)] + [TestCase("(max-monochrome: 0)", true)] + [TestCase("(min-monochrome: 1)", false)] + [TestCase("(max-color: 0) and (max-monochrome: 0)", false)] + [TestCase("(min-color: 1), (min-monochrome: 1)", true)] + [TestCase("not all and (min-color: 1), not all and (min-monochrome: 1)", true)] + [TestCase("not all and (bogus)", false)] + [TestCase("(bogus), all", true)] + public void MediaQueriesOfAColorScreen(System.String query, System.Boolean expected) + { + var window = CreateWindow(new DefaultRenderDevice { ColorBits = 32, MonochromeBits = 0, ViewPortWidth = 1000, ViewPortHeight = 800 }); + Assert.AreEqual(expected, window.MatchMedia(query).IsMatched, query); + } + + private static IWindow CreateWindow(IRenderDevice device) + { + var config = Configuration.Default.WithCss().WithRenderDevice(device); + var context = BrowsingContext.New(config); + var parser = context.GetService(); + var document = parser.ParseDocument("Example"); + return document.DefaultView; + } + } +} diff --git a/src/AngleSharp.Css.Tests/Extensions/ImageSources.cs b/src/AngleSharp.Css.Tests/Extensions/ImageSources.cs new file mode 100644 index 00000000..9e69a251 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Extensions/ImageSources.cs @@ -0,0 +1,169 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Extensions +{ + using AngleSharp.Css.RenderTree; + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using AngleSharp.Media; + using NUnit.Framework; + using System; + using System.Linq; + + [TestFixture] + public class ImageSourcesTests + { + private static readonly String BaseUrl = "http://localhost/"; + + private static IHtmlImageElement Construct(String html, IRenderDevice device = null, IConfiguration config = null) + { + config ??= Configuration.Default; + var context = BrowsingContext.New(config.WithCss().WithOnly(device ?? new DefaultRenderDevice { ViewPortWidth = 1280, ViewPortHeight = 800 })); + var document = context.OpenAsync(m => m.Content(html).Address(BaseUrl)).Result; + return document.QuerySelector("img"); + } + + private static String Source(String html, IRenderDevice device = null, IConfiguration config = null) => + Construct(html, device, config).GetImageSource()?.Url.Href; + + [Test] + public void ImageWithSrcOnlyShowsItsSrc() + { + Assert.AreEqual(BaseUrl + "cat.jpg", Source("cat")); + } + + [Test] + public void ImageWithoutSourceShowsNothing() + { + Assert.IsNull(Source("cat")); + } + + [Test] + public void DensityCandidateOfOneIsTakenOnAStandardDevice() + { + Assert.AreEqual(BaseUrl + "cat.jpg", Source("")); + } + + [Test] + public void DensityCandidateOfTheDevicePixelRatioIsTaken() + { + var device = new DefaultRenderDevice { ViewPortWidth = 1280, Resolution = 192 }; + Assert.AreEqual(BaseUrl + "cat-2x.jpg", Source("", device)); + } + + [Test] + public void SrcIsTheCandidateOfDensityOne() + { + Assert.AreEqual(BaseUrl + "cat.jpg", Source("")); + } + + [Test] + public void WidthCandidateFittingTheViewportIsTakenWithoutSizes() + { + var html = ""; + Assert.AreEqual(BaseUrl + "cat-1280.jpg", Source(html)); + Assert.AreEqual(BaseUrl + "cat-320.jpg", Source(html, new DefaultRenderDevice { ViewPortWidth = 300 })); + } + + [TestCase("300px", "cat-400.jpg")] + [TestCase("50vw", "cat-800.jpg")] + [TestCase("calc(20vw - 56px)", "cat-200.jpg")] + [TestCase("(max-width: 600px) 480px, 150px", "cat-200.jpg")] + [TestCase("(min-width: 600px) 380px, 150px", "cat-400.jpg")] + [TestCase("auto, 300px", "cat-400.jpg")] + public void WidthCandidateFittingTheSizesIsTaken(String sizes, String expected) + { + var html = $""; + Assert.AreEqual(BaseUrl + expected, Source(html)); + } + + [Test] + public void DensestCandidateIsTakenIfNoneIsDenseEnough() + { + var device = new DefaultRenderDevice { ViewPortWidth = 1280, Resolution = 192 }; + Assert.AreEqual(BaseUrl + "cat-400.jpg", Source("", device)); + } + + [Test] + public void UrlOfADataCandidateKeepsItsCommas() + { + Assert.AreEqual("data:image/png;base64,AAAA", Source("")); + } + + [Test] + public void PictureSourceWhoseMediaMatchesIsTaken() + { + var html = @" + + + +"; + Assert.AreEqual(BaseUrl + "cat-vertical.jpg", Source(html)); + Assert.AreEqual(BaseUrl + "cat-horizontal.jpg", Source(html, new DefaultRenderDevice { ViewPortWidth = 800 })); + Assert.AreEqual(BaseUrl + "cat.jpg", Source(html, new DefaultRenderDevice { ViewPortWidth = 500 })); + } + + [Test] + public void PictureSourceOfACombinedSrcsetIsTaken() + { + var html = @" + + + +"; + Assert.AreEqual(BaseUrl + "person@desktop.png", Source(html)); + Assert.AreEqual(BaseUrl + "person@mobile-2x.png", Source(html, new DefaultRenderDevice { ViewPortWidth = 500, Resolution = 192 })); + } + + [Test] + public void PictureSourceOfAnUnsupportedTypeIsSkipped() + { + var html = @" + + + +"; + Assert.AreEqual(BaseUrl + "logo.png", Source(html)); + + Assert.AreEqual(BaseUrl + "logo.webp", Source(html, config: Configuration.Default.With(new WebpImages()))); + } + + [TestCase("", 1.0)] + [TestCase("", 1.0)] + [TestCase("", 2.0)] + [TestCase("", 1.5)] + [TestCase("", 400.0 / 300.0)] + [TestCase("", 0.5)] + public void SourceKnowsTheDensityOfItsPixels(String html, Double expected) + { + Assert.AreEqual(expected, Construct(html).GetImageSource().Density, 0.0001); + } + + [Test] + public void RenderTreePicksTheImageForTheViewport() + { + var device = new DefaultRenderDevice { ViewPortWidth = 1280, ViewPortHeight = 800 }; + var img = Construct("", device); + var window = img.Owner.DefaultView; + + Assert.AreEqual(BaseUrl + "cat-400.jpg", FindNode(window.Render(), img).ImageSource?.Url.Href); + + // a tree built after the viewport was resized picks again + device.ViewPortWidth = 3000; + Assert.AreEqual(BaseUrl + "cat-800.jpg", FindNode(window.Render(), img).ImageSource?.Url.Href); + Assert.IsNull(FindNode(window.Render(), img.Owner.Body).ImageSource); + } + + private sealed class WebpImages : IResourceService + { + public Boolean SupportsType(String mimeType) => mimeType == "image/webp"; + + public System.Threading.Tasks.Task CreateAsync(AngleSharp.Io.IResponse response, System.Threading.CancellationToken cancel) => + System.Threading.Tasks.Task.FromResult(null); + } + + private static ElementRenderNode FindNode(IRenderNode node, IElement element) => + node is ElementRenderNode e && ReferenceEquals(e.Ref, element) + ? e + : node.Children.Select(child => FindNode(child, element)).FirstOrDefault(found => found is not null); + } +} diff --git a/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs b/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs index 20b88cfe..38e7c3f2 100644 --- a/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs +++ b/src/AngleSharp.Css.Tests/Extensions/PseudoElementRenderTests.cs @@ -255,5 +255,19 @@ public void ContentAddedThroughTheObjectModelGeneratesANode() Assert.IsTrue(FindElement((ElementRenderNode)window.Render(new PlainRenderDevice()), "target").Children.Any(m => m.Ref is IPseudoElement)); } -} + + [Test] + public void ClosedDetailsRendersItsSummaryOnly() + { + var root = Render("
SumText

Body

SumText

Body

"); + var closed = FindElement(root, "closed"); + var open = FindElement(root, "open"); + + Assert.AreEqual(1, closed.Children.Count()); + Assert.IsNotNull(FindElement(closed, "s1")); + Assert.IsNull(FindElement(closed, "p1")); + Assert.AreEqual(3, open.Children.Count()); + Assert.IsNotNull(FindElement(open, "p2")); + } + } } diff --git a/src/AngleSharp.Css.Tests/Styling/Configuration.cs b/src/AngleSharp.Css.Tests/Styling/Configuration.cs index 3e216a72..bf8bf9c4 100644 --- a/src/AngleSharp.Css.Tests/Styling/Configuration.cs +++ b/src/AngleSharp.Css.Tests/Styling/Configuration.cs @@ -54,7 +54,11 @@ public void ObtainDefaultSheet() // shown, centered in the viewport, and the `::backdrop` of a shown popover). // 86, not 85: headings and `th` are `bold` (as in the HTML standard), `b` and // `strong` stay `bolder`, which takes a rule of its own. - Assert.AreEqual(86, sheet.Rules.Length); + // 89, not 86: the UA stylesheet now also carries the dialog rules (hidden unless + // open, centered, and fixed in the viewport while it is a modal). + // 92, not 89: the UA stylesheet now also carries the fullscreen rules (covering the + // viewport, without the border of an iframe, and a black `::backdrop`). + Assert.AreEqual(92, sheet.Rules.Length); } } } diff --git a/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs b/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs index 381e2258..ceac415c 100644 --- a/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs +++ b/src/AngleSharp.Css.Tests/Styling/ContextLoading.cs @@ -77,7 +77,7 @@ public async Task GetDownloadsOfExampleDocumentWithCssAndJsShouldYieldAllResourc var document = await BrowsingContext.New(config).OpenAsync(res => res.Content(content).Address("http://localhost")); var downloads = document.GetDownloads().ToArray(); - Assert.AreEqual(6, downloads.Length); + Assert.AreEqual(5, downloads.Length); foreach (var download in downloads) { @@ -88,9 +88,8 @@ public async Task GetDownloadsOfExampleDocumentWithCssAndJsShouldYieldAllResourc Assert.AreEqual(document.QuerySelectorAll("link").Skip(0).First(), downloads[0].Source); Assert.AreEqual(document.QuerySelectorAll("link").Skip(1).First(), downloads[1].Source); Assert.AreEqual(document.QuerySelectorAll("link").Skip(2).First(), downloads[2].Source); - Assert.AreEqual(document.QuerySelector("img"), downloads[3].Source); - Assert.AreEqual(document.QuerySelector("iframe"), downloads[4].Source); - Assert.AreEqual(document.QuerySelectorAll("script").Skip(1).First(), downloads[5].Source); + Assert.AreEqual(document.QuerySelector("iframe"), downloads[3].Source); + Assert.AreEqual(document.QuerySelectorAll("script").Skip(1).First(), downloads[4].Source); } } } diff --git a/src/AngleSharp.Css.Tests/Styling/CssSheet.cs b/src/AngleSharp.Css.Tests/Styling/CssSheet.cs index eb3a6f6f..7295cecf 100644 --- a/src/AngleSharp.Css.Tests/Styling/CssSheet.cs +++ b/src/AngleSharp.Css.Tests/Styling/CssSheet.cs @@ -1349,5 +1349,39 @@ public void CssColorFunctionsMixAllShouldWork() Assert.IsNotNull(hwbAlpha); Assert.IsNotNull(hwbAngleAlpha); } + + [Test] + public void CssSheetCommentWithQuoteInValueStartsNoString() + { + // Acid2: an apostrophe in a comment used to swallow the rest of the style sheet + var sheet = ParseStyleSheet(@".chin { background: yellow /* shouldn't be visible */ no-repeat; } +.next { color: red; }"); + Assert.AreEqual(2, sheet.Rules.Length); + Assert.AreEqual("rgba(255, 255, 0, 1)", ((ICssStyleRule)sheet.Rules[0]).Style.GetPropertyValue("background-color")); + Assert.AreEqual(".next", ((ICssStyleRule)sheet.Rules[1]).SelectorText); + } + + [Test] + public void CssSheetEscapedCurlyBracketInValueDoesNotEndTheRule() + { + var sheet = ParseStyleSheet(@".parser { width: 2em; error: \}; background: yellow; } +.next { color: red; }"); + Assert.AreEqual(2, sheet.Rules.Length); + var parser = (ICssStyleRule)sheet.Rules[0]; + Assert.AreEqual("2em", parser.Style.GetPropertyValue("width")); + Assert.AreEqual("rgba(255, 255, 0, 1)", parser.Style.GetPropertyValue("background-color")); + } + + [Test] + public void CssSheetSemicolonAfterRuleInvalidatesTheNextSelector() + { + // a ';' is part of the prelude of the next rule, which then matches nothing + var sheet = ParseStyleSheet(@".parser { margin: 2em; }; +.parser { height: 3em; } +.after { color: red; }"); + Assert.AreEqual(3, sheet.Rules.Length); + Assert.IsNull(((CssStyleRule)sheet.Rules[1]).Selector); + Assert.AreEqual(".after", ((ICssStyleRule)sheet.Rules[2]).SelectorText); + } } } diff --git a/src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs b/src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs new file mode 100644 index 00000000..5657a8e3 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/FullscreenTests.cs @@ -0,0 +1,65 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Dom; + using AngleSharp.Dom; + using NUnit.Framework; + using static CssConstructionFunctions; + + /// + /// The CSS part of the Fullscreen API: the `:fullscreen` pseudo-class, which the host forces + /// on the element it shows fullscreen, and the user-agent styles making it cover the viewport. + /// + [TestFixture] + public class FullscreenTests + { + [Test] + public void FullscreenDoesNotMatchByItself() + { + var document = ParseDocument("
x
"); + var video = document.GetElementById("video"); + + Assert.IsFalse(video.Matches(":fullscreen")); + Assert.IsTrue(video.Matches(":not(:fullscreen)")); + } + + [Test] + public void FullscreenMatchesTheElementTheHostShowsFullscreen() + { + var document = ParseDocument("
x
"); + var video = document.GetElementById("video"); + + video.SetPseudoClass("fullscreen"); + Assert.IsTrue(video.Matches(":fullscreen")); + + video.RemovePseudoClass("fullscreen"); + Assert.IsFalse(video.Matches(":fullscreen")); + } + + [Test] + public void FullscreenElementCoversTheViewport() + { + var document = ParseDocument("
x
"); + var video = document.GetElementById("video"); + + video.SetPseudoClass("fullscreen"); + var style = document.DefaultView.GetComputedStyle(video); + + Assert.AreEqual("fixed", style.GetPosition()); + Assert.AreEqual("100%", style.GetWidth()); + Assert.AreEqual("0px", style.GetPropertyValue("margin-top")); + } + + [Test] + public void AppendedDefaultRulesAreKept() + { + var provider = new CssDefaultStyleSheetProvider(); + provider.AppendDefault("x-first { color: red }"); + provider.AppendDefault("x-second { color: blue }"); + var css = provider.Default.ToCss(); + + StringAssert.Contains("x-first", css); + StringAssert.Contains("x-second", css); + } + } +} diff --git a/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs b/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs index f6303922..5e5ae145 100644 --- a/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs +++ b/src/AngleSharp.Css.Tests/Styling/RegisteredCustomPropertyTests.cs @@ -239,5 +239,34 @@ public void DeclaredStyleKeepsTheSpecifiedValue() Assert.AreEqual("2em", element.GetStyle().GetPropertyValue("--len")); } - } + + [Test] + public void AngleIsComputedInDegrees() + { + var style = Compute("@property --a { syntax: \"\"; inherits: false; initial-value: 0deg; } #target { --a: 0.5turn }", "
"); + Assert.AreEqual("180deg", style.GetPropertyValue("--a")); + } + + private sealed class AnimatedValues : IAnimatedValueProvider + { + public System.Collections.Generic.IReadOnlyDictionary GetAnimatedValues(IElement element, ICssStyleDeclaration declared) => + element.Id == "target" ? new System.Collections.Generic.Dictionary { { "--len", "7px" }, { "--imp", "1px" } } : null; + } + + [Test] + public void AnimatedValueWinsOverTheDeclaredOneButNotOverAnImportantOne() + { + var document = ParseDocument("
"); + document.Context.SetAnimatedValueProvider(new AnimatedValues()); + var style = document.GetElementById("target").ComputeCurrentStyle(); + var child = document.GetElementById("child").ComputeCurrentStyle(); + document.Context.SetAnimatedValueProvider(null); + + Assert.AreEqual("7px", style.GetPropertyValue("--len")); + Assert.AreEqual("7px", style.GetPropertyValue("width")); + Assert.AreEqual("3px", style.GetPropertyValue("height")); + // inherited as any value of the element is + Assert.AreEqual("7px", child.GetPropertyValue("--len")); + } +} } diff --git a/src/AngleSharp.Css.Tests/Styling/RendererTestsPageTests.cs b/src/AngleSharp.Css.Tests/Styling/RendererTestsPageTests.cs new file mode 100644 index 00000000..aedd2b33 --- /dev/null +++ b/src/AngleSharp.Css.Tests/Styling/RendererTestsPageTests.cs @@ -0,0 +1,113 @@ +#nullable disable +namespace AngleSharp.Css.Tests.Styling +{ + using AngleSharp.Css.Converters; + using AngleSharp.Css.Dom; + using AngleSharp.Css.Values; + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using NUnit.Framework; + using System.Threading.Tasks; + using static AngleSharp.Css.ValueConverters; + + /// + /// Found on the renderer test pages (anglesharp-tests.anglevisions.com/renderer/): gradients of + /// CSS Images 4, @scope, the pseudo-elements a renderer styles, dialogs and shadow trees. + /// + [TestFixture] + public class RendererTestsPageTests + { + private const string Green = "rgba(0, 128, 0, 1)"; + + private static async Task OpenAsync(string html) + { + var context = BrowsingContext.New(Configuration.Default.WithCss()); + return await context.OpenAsync(req => req.Content("" + html)); + } + + [TestCase("linear-gradient(black, 20%, white)")] + [TestCase("linear-gradient(red 10%, 30%, blue 80%)")] + [TestCase("linear-gradient(in oklch, blue, red)")] + [TestCase("linear-gradient(90deg in hsl longer hue, red, red)")] + [TestCase("radial-gradient(circle in oklab, red, blue)")] + [TestCase("conic-gradient(in oklch from 10deg, red, blue)")] + public void GradientOfImages4IsValid(string source) + { + Assert.IsNotNull(GradientConverter.Convert(source)); + } + + [TestCase("linear-gradient(red, 10%)")] + [TestCase("linear-gradient(10%, red, blue)")] + [TestCase("linear-gradient(red, 10%, 20%, blue)")] + [TestCase("linear-gradient(in bogus, red, blue)")] + [TestCase("radial-gradient(closest-side in oklab at 10% 10%, red, blue)")] + public void GradientWithMisplacedHintOrInterpolationIsInvalid(string source) + { + Assert.IsNull(GradientConverter.Convert(source)); + } + + [Test] + public void ColorHintIsSerializedAsItsPosition() + { + var gradient = (CssLinearGradientValue)GradientConverter.Convert("linear-gradient(90deg in oklch, black, 20%, white)"); + Assert.AreEqual("linear-gradient(90deg in oklch, rgba(0, 0, 0, 1), 20%, rgba(255, 255, 255, 1))", gradient.CssText); + Assert.AreEqual("in oklch", gradient.Interpolation); + Assert.IsTrue(((CssGradientStopValue)gradient.Stops[1]).IsHint); + } + + [Test] + public void ConicGradientWithAngleAndCenterIsOneArgument() + { + var gradient = GradientConverter.Convert("conic-gradient(from 90deg at 30% 70%, black, white)"); + StringAssert.StartsWith("conic-gradient(from 90deg at 30% 70%, ", gradient.CssText); + } + + [Test] + public async Task ScopedRulesApplyBetweenRootAndLimit() + { + var document = await OpenAsync("" + + "
in
out
x"); + var window = document.DefaultView; + + Assert.AreEqual(Green, window.GetComputedStyle(document.GetElementById("in")).GetColor()); + Assert.AreEqual("rgba(255, 0, 0, 1)", window.GetComputedStyle(document.GetElementById("out")).GetColor()); + Assert.AreEqual("rgba(255, 0, 0, 1)", window.GetComputedStyle(document.GetElementById("outside")).GetColor()); + } + + [TestCase("::marker", "
  • A
")] + [TestCase("::first-line", "

A

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

A

")] + public async Task PseudoElementOfARendererIsStyled(string pseudo, string html) + { + var document = await OpenAsync(html); + Assert.AreEqual(Green, document.DefaultView.GetComputedStyle(document.GetElementById("t"), pseudo).GetColor()); + } + + [Test] + public async Task ModalDialogMatchesModalAndClosedOneIsHidden() + { + var document = await OpenAsync("A"); + var dialog = (IHtmlDialogElement)document.GetElementById("d"); + + Assert.AreEqual("none", document.DefaultView.GetComputedStyle(dialog).GetDisplay()); + dialog.ShowModal(); + Assert.IsTrue(dialog.Matches(":modal")); + Assert.AreEqual("fixed", document.DefaultView.GetComputedStyle(dialog).GetPosition()); + dialog.Close(); + Assert.IsFalse(dialog.Matches(":modal")); + } + + [Test] + public async Task ShadowTreeIsStyledByItsOwnSheetsAndInheritsFromTheHost() + { + var document = await OpenAsync("
"); + var host = document.GetElementById("host"); + var root = host.AttachShadow(); + root.InnerHtml = "A"; + var window = document.DefaultView; + + Assert.AreEqual(Green, window.GetComputedStyle(root.QuerySelector(".label")).GetColor()); + Assert.AreEqual("300", window.GetComputedStyle(root.QuerySelector("b")).GetFontWeight()); + } + } +} diff --git a/src/AngleSharp.Css/AngleSharp.Css.csproj b/src/AngleSharp.Css/AngleSharp.Css.csproj index 3a93345c..690d5564 100644 --- a/src/AngleSharp.Css/AngleSharp.Css.csproj +++ b/src/AngleSharp.Css/AngleSharp.Css.csproj @@ -40,7 +40,7 @@ true true snupkg - 1.10.0 + 1.11.0 @@ -62,6 +62,10 @@ <_Parameter1>false + + + <_Parameter1>AngleSharp.Css.CssDom + diff --git a/src/AngleSharp.Css/BrowsingContextExtensions.cs b/src/AngleSharp.Css/BrowsingContextExtensions.cs index 2e59013f..748c9cc9 100644 --- a/src/AngleSharp.Css/BrowsingContextExtensions.cs +++ b/src/AngleSharp.Css/BrowsingContextExtensions.cs @@ -17,6 +17,34 @@ public static class BrowsingContextExtensions { // the services of a context are fixed; resolving them walks all services private static readonly ConditionalWeakTable DeclarationFactories = new(); + private static readonly ConditionalWeakTable AnimatedValueProviders = new(); + + // most processes never have one, which spares every computed style the lookup + private static volatile Boolean _anyAnimatedValueProvider; + + /// + /// Sets what gives the animated values of the elements of the context's documents (see + /// ), or removes it with null. The styles computed from + /// then on include them; styles computed before stay as they are. + /// + /// The context to use. + /// The provider, or null. + public static void SetAnimatedValueProvider(this IBrowsingContext context, IAnimatedValueProvider provider) + { + if (context is null) + throw new ArgumentNullException(nameof(context)); + + AnimatedValueProviders.Remove(context); + + if (provider is not null) + { + _anyAnimatedValueProvider = true; + AnimatedValueProviders.Add(context, provider); + } + } + + internal static IAnimatedValueProvider GetAnimatedValueProvider(this IBrowsingContext context) => + _anyAnimatedValueProvider && context is not null && AnimatedValueProviders.TryGetValue(context, out var provider) ? provider : null; /// /// Loads a stylesheet resource via its URL. diff --git a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs index cf7cb41d..ae030283 100644 --- a/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs +++ b/src/AngleSharp.Css/CssDefaultStyleSheetProvider.cs @@ -10,6 +10,7 @@ sealed class CssDefaultStyleSheetProvider : ICssDefaultStyleSheetProvider #region Fields private ICssStyleSheet? _default; + private String _appended = String.Empty; #endregion @@ -21,11 +22,21 @@ sealed class CssDefaultStyleSheetProvider : ICssDefaultStyleSheetProvider #region Methods - public void SetDefault(ICssStyleSheet? sheet) => _default = sheet; + public void SetDefault(ICssStyleSheet? sheet) + { + _default = sheet; + _appended = String.Empty; + } public void SetDefault(String source) => SetDefault(Parse(source)); - public void AppendDefault(String source) => SetDefault(Parse($"{DefaultSource}\r\n{source}")); + // what was appended before stays (e.g. the rules of several extensions) + public void AppendDefault(String source) + { + var appended = $"{_appended}\r\n{source}"; + SetDefault(Parse($"{DefaultSource}{appended}")); + _appended = appended; + } #endregion @@ -85,8 +96,14 @@ private static ICssStyleSheet Parse(String source) [hidden] { display: none } [popover]:not(:popover-open):not(dialog[open]) { display: none } dialog:popover-open { display: block } +dialog:not([open]) { display: none } +dialog { display: block; position: absolute; left: 0; right: 0; width: fit-content; height: fit-content; margin: auto; border: solid; padding: 1em; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255) } +dialog:modal { position: fixed; overflow: auto; top: 0; bottom: 0; max-width: calc(100% - 6px - 2em); max-height: calc(100% - 6px - 2em) } [popover] { position: fixed; inset: 0; width: fit-content; height: fit-content; margin: auto; border: solid; padding: 0.25em; overflow: auto; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255) } :popover-open::backdrop { position: fixed; inset: 0; pointer-events: none !important; background-color: transparent } +:not(:root):fullscreen { position: fixed !important; inset: 0 !important; margin: 0 !important; box-sizing: border-box !important; min-width: 0 !important; max-width: none !important; min-height: 0 !important; max-height: none !important; width: 100% !important; height: 100% !important; transform: none !important; object-fit: contain } +iframe:fullscreen { border: none !important; padding: 0 !important } +:not(:root):fullscreen::backdrop { background: black } table { display: table } tr { display: table-row } thead { display: table-header-group } diff --git a/src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs b/src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs new file mode 100644 index 00000000..cbb23a40 --- /dev/null +++ b/src/AngleSharp.Css/Dom/Internal/FullscreenPseudoClassSelector.cs @@ -0,0 +1,21 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Dom; + using System; + + /// + /// The :fullscreen pseudo-class, which only the host knows to match: it forces it on the + /// element it shows fullscreen (see ElementExtensions.SetPseudoClass). + /// + sealed class FullscreenPseudoClassSelector : ISelector + { + public Priority Specificity => Priority.OneClass; + + public String Text => PseudoClassNames.Separator + CssPseudoClassSelectorFactory.Fullscreen; + + public void Accept(ISelectorVisitor visitor) => visitor.PseudoClass(CssPseudoClassSelectorFactory.Fullscreen); + + public Boolean Match(IElement element, IElement? scope) => false; + } +} diff --git a/src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs b/src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs new file mode 100644 index 00000000..3e184be0 --- /dev/null +++ b/src/AngleSharp.Css/Dom/Internal/ModalPseudoClassSelector.cs @@ -0,0 +1,22 @@ +#nullable enable +namespace AngleSharp.Css.Dom +{ + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using System; + + /// + /// Matches the `:modal` pseudo-class (Selectors 4 §13.4), i.e., a dialog shown as a modal. + /// + sealed class ModalPseudoClassSelector : ISelector + { + public Priority Specificity => Priority.OneClass; + + public String Text => PseudoClassNames.Separator + CssPseudoClassSelectorFactory.Modal; + + public void Accept(ISelectorVisitor visitor) => visitor.PseudoClass(CssPseudoClassSelectorFactory.Modal); + + public Boolean Match(IElement element, IElement? scope) => + element is IHtmlDialogElement dialog && dialog.Open && dialog.GetIsModal(); + } +} diff --git a/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs b/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs index c44bda3a..0460e9ef 100644 --- a/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs +++ b/src/AngleSharp.Css/Dom/Internal/Rules/CssScopeRule.cs @@ -1,6 +1,7 @@ #nullable disable namespace AngleSharp.Css.Dom { + using AngleSharp.Dom; using System; using System.Diagnostics; using System.IO; @@ -16,8 +17,121 @@ internal CssScopeRule(ICssStyleSheet owner) { } + private String _parsedText; + private ISelector _start; + private ISelector _end; + public String ScopeText { get; set; } + /// + /// Finds the scoping root of the element (CSS Cascade 6, 2.5): the closest inclusive + /// ancestor matching the scope's start (the parent of the style sheet's owner if there + /// is none), such that the element is not in a scoping limit below it. + /// + internal Boolean TryGetScopeRoot(IElement element, out IElement root) + { + root = null; + EnsureSelectors(); + + if (_start is null) + { + // @scope { ... } is scoped to the parent of the