Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ jobs:
10.0.x

- name: Build
run: ./build.sh -AngleSharpVersion 1.5.0
run: ./build.sh -AngleSharpVersion 1.9.0

windows:
runs-on: windows-latest
Expand All @@ -74,9 +74,9 @@ jobs:
- name: Build
run: |
if ($env:GITHUB_REF -eq "refs/heads/main") {
.\build.ps1 -Target Publish -AngleSharpVersion 1.5.0
.\build.ps1 -Target Publish -AngleSharpVersion 1.9.0
} elseif ($env:GITHUB_REF -eq "refs/heads/devel") {
.\build.ps1 -Target PrePublish -AngleSharpVersion 1.5.0
.\build.ps1 -Target PrePublish -AngleSharpVersion 1.9.0
} else {
.\build.ps1 -AngleSharpVersion 1.5.0
.\build.ps1 -AngleSharpVersion 1.9.0
}
5 changes: 4 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,16 @@ dotnet run --project src/AngleSharp.Performance.Css/AngleSharp.Performance.Css.c

Notes:

- CI invokes `./build.sh -AngleSharpVersion 1.5.0` on Linux and `./build.ps1` on Windows.
- CI invokes `./build.sh -AngleSharpVersion 1.9.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

- 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.9.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`
- Fallout entrypoint: `build/Build.cs`
Expand Down Expand Up @@ -137,6 +139,7 @@ dotnet test src/AngleSharp.Css.Tests/AngleSharp.Css.Tests.csproj
- Avoid broad refactors when making focused feature fixes.
- Keep public API changes intentional; many files under `Dom` are effectively surface area.
- Existing code mixes nullable contexts (`#nullable enable` and `#nullable disable`); do not normalize unrelated files.
- Stay trim- and AOT-clean. The library sets `IsAotCompatible` on its .NETCoreApp targets, so the trim and AOT analyzers run on every build and a warning breaks it. Reflection over a runtime type (`GetType().GetProperties()`, `Assembly.GetTypes()`) is what they reject: read members off an annotated generic parameter instead (`Css<T, TProperties>` via AngleSharp's `ToDictionary<T>`), or use a fixed table. The analyzers only see the library itself; publishing a small `PublishAot` console app against it is the end-to-end check.
- In `src/AngleSharp.Css/ValueConverters.cs`, avoid static field initializers that reference converters declared later in the same file. Forward references can capture `null` during type initialization and only fail at runtime.

## 8) Documentation and onboarding references
Expand Down
40 changes: 40 additions & 0 deletions src/AngleSharp.Css.Tests/Extensions/ApiExtension.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
namespace AngleSharp.Css.Tests.Extensions
{
using AngleSharp.Css.Dom;
using AngleSharp.Dom;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using static CssConstructionFunctions;

Expand All @@ -23,5 +26,42 @@ public void ExtensionCssWithEmptyListOnly()
var elements = document.QuerySelectorAll("li").Css("color", "red");
Assert.AreEqual(0, elements.Count());
}

[Test]
public void ExtensionCssWithAnonymousObjectSetsDeclarations()
{
var document = ParseDocument("<ul><li>a</li><li>b</li></ul>");
var elements = document.QuerySelectorAll("li").Css(new { color = "red", display = "none" });
Assert.AreEqual(2, elements.Count());

foreach (var element in elements)
{
Assert.AreEqual("rgba(255, 0, 0, 1)", element.GetStyle().GetPropertyValue("color"));
Assert.AreEqual("none", element.GetStyle().GetPropertyValue("display"));
}
}

[Test]
public void ExtensionCssWithDictionaryCopiesItsEntries()
{
// A dictionary binds to the generic overload ahead of the key value pair one, so it
// must be copied there rather than have the properties of Dictionary read.
var document = ParseDocument("<ul><li>a</li></ul>");
var properties = new Dictionary<String, String> { ["color"] = "red", ["margin-left"] = "2px" };
var element = document.QuerySelectorAll("li").Css(properties).Single();
Assert.AreEqual("rgba(255, 0, 0, 1)", element.GetStyle().GetPropertyValue("color"));
Assert.AreEqual("2px", element.GetStyle().GetPropertyValue("margin-left"));
}

[Test]
public void ExtensionCssWithValueDeclaredAsObjectStillWorks()
{
var document = ParseDocument("<ul><li>a</li></ul>");
Object properties = new { color = "red" };
#pragma warning disable CS0618 // The obsolete Object overload is the one under test.
var element = document.QuerySelectorAll("li").Css(properties).Single();
#pragma warning restore CS0618
Assert.AreEqual("rgba(255, 0, 0, 1)", element.GetStyle().GetPropertyValue("color"));
}
}
}
21 changes: 20 additions & 1 deletion src/AngleSharp.Css/AngleSharp.Css.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<!-- Marks the package trimmable and AOT-compatible, and runs the trim, AOT and single-file
analyzers on every build. Only the .NETCoreApp targets support it; the SDK warns on the
others. Keyed on TargetFramework because TargetFrameworkIdentifier is not set yet when the
project's own properties are evaluated. -->
<PropertyGroup Condition=" '$(TargetFramework)' != 'netstandard2.0' And !$(TargetFramework.StartsWith('net4')) ">
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>

<!-- IsAotCompatible makes the SDK reference Microsoft.NET.ILLink.Tasks implicitly, at the version
its KnownILLinkPack table lists per target (8.0.x for net8.0, 10.0.x for net10.0). Two versions
of one package in one project make Visual Studio's NuGet Consolidate tab report it, so every
target uses the trimmer of the SDK doing the build instead. Following the SDK's bundled version
keeps it current without pinning, and covers the next pair of targets too (net10.0 next to net11.0).
KnownILLinkPack is SDK-internal and undocumented: if an SDK renames or reshapes it, this goes
inert or fails the restore - drop it then, or once only one .NETCoreApp target is left. -->
<ItemGroup>
<KnownILLinkPack Update="Microsoft.NET.ILLink.Tasks" ILLinkPackVersion="$(BundledNETCoreAppPackageVersion)" />
</ItemGroup>

<PropertyGroup Label="Packaging">
<PackageProjectUrl>https://anglesharp.github.io</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand All @@ -21,7 +40,7 @@
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<AngleSharpVersion Condition=" '$(AngleSharpVersion)' == '' ">1.5.0</AngleSharpVersion>
<AngleSharpVersion Condition=" '$(AngleSharpVersion)' == '' ">1.9.0</AngleSharpVersion>
</PropertyGroup>

<ItemGroup>
Expand Down
43 changes: 43 additions & 0 deletions src/AngleSharp.Css/Common/DynamicallyAccessedMembersAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#if !NET5_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
// The trimmer matches these by name, so this internal copy lets the generic parameters of the
// reflection-based extensions carry their annotation on the targets whose BCL predates it.

[AttributeUsage(
AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,
Inherited = false)]
internal sealed class DynamicallyAccessedMembersAttribute : Attribute
{
public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
{
MemberTypes = memberTypes;
}

public DynamicallyAccessedMemberTypes MemberTypes { get; }
}

[Flags]
internal enum DynamicallyAccessedMemberTypes
{
None = 0,
PublicParameterlessConstructor = 0x0001,
PublicConstructors = 0x0002 | PublicParameterlessConstructor,
NonPublicConstructors = 0x0004,
PublicMethods = 0x0008,
NonPublicMethods = 0x0010,
PublicFields = 0x0020,
NonPublicFields = 0x0040,
PublicNestedTypes = 0x0080,
NonPublicNestedTypes = 0x0100,
PublicProperties = 0x0200,
NonPublicProperties = 0x0400,
PublicEvents = 0x0800,
NonPublicEvents = 0x1000,
Interfaces = 0x2000,
All = ~None,
}
}
#endif
20 changes: 20 additions & 0 deletions src/AngleSharp.Css/Common/RequiresUnreferencedCodeAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#if !NET5_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
// The trimmer matches this by name, so this internal copy lets the obsolete Object overloads
// carry their warning on the targets whose BCL predates it.

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]
internal sealed class RequiresUnreferencedCodeAttribute : Attribute
{
public RequiresUnreferencedCodeAttribute(String message)
{
Message = message;
}

public String Message { get; }

public String? Url { get; set; }
}
}
#endif
32 changes: 31 additions & 1 deletion src/AngleSharp.Css/Extensions/CssApiExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace AngleSharp.Dom
using AngleSharp.Html.Dom;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

/// <summary>
Expand Down Expand Up @@ -96,17 +97,46 @@ public static T Css<T>(this T elements, IEnumerable<KeyValuePair<String, String>
/// declarations.
/// </summary>
/// <typeparam name="T">The type of element collection.</typeparam>
/// <typeparam name="TProperties">The declared type whose properties are the declarations.</typeparam>
/// <param name="elements">The collection.</param>
/// <param name="properties">
/// An enumeration of properties in form of an anonymous object, that
/// carries key-value pairs.
/// </param>
/// <returns>The collection itself.</returns>
public static T Css<T, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] TProperties>(this T elements, TProperties properties)
where T : class, IEnumerable<IElement>
{
// Typed as the interface so this binds to the key value pair overload, not back to itself.
IEnumerable<KeyValuePair<String, String>> realProperties = properties.ToDictionary();
return elements.Css(realProperties);
}

/// <summary>
/// Extends the CSS of the given elements with the specified
/// declarations.
/// </summary>
/// <typeparam name="T">The type of element collection.</typeparam>
/// <param name="elements">The collection.</param>
/// <param name="properties">
/// An enumeration of properties in form of an anonymous object, that
/// carries key-value pairs.
/// </param>
/// <returns>The collection itself.</returns>
[Obsolete(RuntimePropertiesObsolete)]
[RequiresUnreferencedCode(RuntimePropertiesTrimming)]
public static T Css<T>(this T elements, Object properties)
where T : class, IEnumerable<IElement>
{
var realProperties = properties.ToDictionary();
// Kept so code compiled against it keeps working; a recompile binds everything but a
// value declared as Object to the generic overload. Being obsolete itself, it may call
// the obsolete Object overload of ToDictionary without a warning.
IEnumerable<KeyValuePair<String, String>> realProperties = properties.ToDictionary();
return elements.Css(realProperties);
}

private const String RuntimePropertiesObsolete = "Reads the properties of the value's runtime type, which trimming can remove. Pass the value with its own type, such as an anonymous object, or as a dictionary, to use the generic overload.";

private const String RuntimePropertiesTrimming = "Reads the public properties of the value's runtime type, which trimming can remove.";
}
}
Loading