Git Product home page Git Product logo

anglesharp.css's Introduction

logo

AngleSharp

CI GitHub Tag NuGet Count Issues Open Gitter Chat StackOverflow Questions CLA Assistant

AngleSharp is a .NET library that gives you the ability to parse angle bracket based hyper-texts like HTML, SVG, and MathML. XML without validation is also supported by the library. An important aspect of AngleSharp is that CSS can also be parsed. The included parser is built upon the official W3C specification. This produces a perfectly portable HTML5 DOM representation of the given source code and ensures compatibility with results in evergreen browsers. Also standard DOM features such as querySelector or querySelectorAll work for tree traversal.

⚡⚡ Migrating from AngleSharp 0.9 to AngleSharp 0.10 or later (incl. 1.0)? Look at our migration documentation. ⚡⚡

Key Features

  • Portable (using .NET Standard 2.0)
  • Standards conform (works exactly as evergreen browsers)
  • Great performance (outperforms similar parsers in most scenarios)
  • Extensible (extend with your own services)
  • Useful abstractions (type helpers, jQuery like construction)
  • Fully functional DOM (all the lists, iterators, and events you know)
  • Form submission (easily log in everywhere)
  • Navigation (a BrowsingContext is like a browser tab - control it from .NET!).
  • LINQ enhanced (use LINQ with DOM elements, naturally without wrappers)

The advantage over similar libraries like HtmlAgilityPack is that the exposed DOM is using the official W3C specified API, i.e., that even things like querySelectorAll are available in AngleSharp. Also the parser uses the HTML 5.1 specification, which defines error handling and element correction. The AngleSharp library focuses on standards compliance, interactivity, and extensibility. It is therefore giving web developers working with C# all possibilities as they know from using the DOM in any modern browser.

The performance of AngleSharp is quite close to the performance of browsers. Even very large pages can be processed within milliseconds. AngleSharp tries to minimize memory allocations and reuses elements internally to avoid unnecessary object creation.

Simple Demo

The simple example will use the website of Wikipedia for data retrieval.

var config = Configuration.Default.WithDefaultLoader();
var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(address);
var cellSelector = "tr.vevent td:nth-child(3)";
var cells = document.QuerySelectorAll(cellSelector);
var titles = cells.Select(m => m.TextContent);

Or the same with explicit types:

IConfiguration config = Configuration.Default.WithDefaultLoader();
string address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
IBrowsingContext context = BrowsingContext.New(config);
IDocument document = await context.OpenAsync(address);
string cellSelector = "tr.vevent td:nth-child(3)";
IHtmlCollection<IElement> cells = document.QuerySelectorAll(cellSelector);
IEnumerable<string> titles = cells.Select(m => m.TextContent);

In the example we see:

  • How to setup the configuration for supporting document loading
  • Asynchronously get the document in a new context using the configuration
  • Performing a query to get all cells with the content of interest
  • The whole DOM supports LINQ queries

Every collection in AngleSharp supports LINQ statements. AngleSharp also provides many useful extension methods for element collections that cannot be found in the official DOM.

Supported Platforms

AngleSharp has been created as a .NET Standard 2.0 compatible library. This includes, but is not limited to:

  • .NET Core (2.0 and later)
  • .NET Framework (4.6.2 and later)
  • Xamarin.Android (7.0 and 8.0)
  • Xamarin.iOS (10.0 and 10.14)
  • Xamarin.Mac (3.0 and 3.8)
  • Mono (4.6 and 5.4)
  • UWP (10.0 and 10.0.16299)
  • Unity (2018.1)

Documentation

The documentation of AngleSharp is located in the docs folder. More examples, best-practices, and general information can be found there. The documentation also contains a list of frequently asked questions.

More information is also available by following some of the hyper references mentioned in the Wiki. In-depth articles will be published on the CodeProject, with links being placed in the Wiki at GitHub.

Use-Cases

  • Parsing HTML (incl. fragments)
  • Parsing CSS (incl. selectors, declarations, ...)
  • Constructing HTML (e.g., view-engine)
  • Minifying CSS, HTML, ...
  • Querying document elements
  • Crawling information
  • Gathering statistics
  • Web automation
  • Tools with HTML / CSS / ... support
  • Connection to page analytics
  • HTML / DOM unit tests
  • Automated JavaScript interaction
  • Testing other concepts, e.g., script engines
  • ...

Vision

The project aims to bring a solid implementation of the W3C DOM for HTML, SVG, MathML, and CSS to the CLR - all written in C#. The idea is that you can basically do everything with the DOM in C# that you can do in JavaScript (plus, of course, more).

Most parts of the DOM are included, even though some may still miss their (fully specified / correct) implementation. The goal for v1.0 is to have all practically relevant parts implemented according to the official W3C specification (with useful extensions by the WHATWG).

The API is close to the DOM4 specification, however, the naming has been adjusted to apply with .NET conventions. Nevertheless, to make AngleSharp really useful for, e.g., a JavaScript engine, attributes have been placed on the corresponding interfaces (and methods, properties, ...) to indicate the status of the field in the official specification. This allows automatic generation of DOM objects with the official API.

This is a long-term project which will eventually result in a state of the art parser for the most important angle bracket based hyper-texts.

Our hope is to build a community around web parsing and libraries from this project. So far we had great contributions, but that goal was not fully achieved. Want to help? Get in touch with us!

Participating in the Project

If you know some feature that AngleSharp is currently missing, and you are willing to implement the feature, then your contribution is more than welcome! Also if you have a really cool idea - do not be shy, we'd like to hear it.

If you have an idea how to improve the API (or what is missing) then posts / messages are also welcome. For instance there have been ongoing discussions about some styles that have been used by AngleSharp (e.g., HTMLDocument or HtmlDocument) in the past. In the end AngleSharp stopped using HTMLDocument (at least visible outside of the library). Now AngleSharp uses names like IDocument, IHtmlElement and so on. This change would not have been possible without such fruitful discussions.

The project is always searching for additional contributors. Even if you do not have any code to contribute, but rather an idea for improvement, a bug report or a mistake in the documentation. These are the contributions that keep this project active.

Live discussions can take place in our Gitter chat, which supports using GitHub accounts.

More information is found in the contribution guidelines. All contributors can be found in the CONTRIBUTORS file.

This project has also adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community.

For more information see the .NET Foundation Code of Conduct.

Funding / Support

If you use AngleSharp frequently, but you do not have the time to support the project by active participation you may still be interested to ensure that the AngleSharp projects keeps the lights on.

Therefore we created a backing model via Bountysource. Any donation is welcome and much appreciated. We will mostly spend the money on dedicated development time to improve AngleSharp where it needs to be improved, plus invest in the web utility eco-system in .NET (e.g., in JavaScript engines, other parsers, or a renderer for AngleSharp to mention some outstanding projects).

Visit Bountysource for more details.

Development

AngleSharp is written in the most recent version of C# and thus requires Roslyn as a compiler. Using an IDE like Visual Studio 2019+ is recommended on Windows. Alternatively, VSCode (with OmniSharp or another suitable Language Server Protocol implementation) should be the tool of choice on other platforms.

The code tries to be as clean as possible. Notably the following rules are used:

  • Use braces for any conditional / loop body
  • Use the -Async suffixed methods when available
  • Use VIP ("Var If Possible") style (in C++ called AAA: Almost Always Auto) to place types on the right

More important, however, is the proper usage of tests. Any new feature should come with a set of tests to cover the functionality and prevent regression.

Changelog

A very detailed changelog exists. If you are just interested in major releases then have a look at the GitHub releases.

.NET Foundation

This project is supported by the .NET Foundation.

License

AngleSharp is released using the MIT license. For more information see the license file.

anglesharp.css's People

Contributors

campersau avatar ericmutta avatar florianrappl avatar iamcarbon avatar jogibear9988 avatar macewindu avatar martinwelsch avatar meziantou avatar mganss avatar sheshnathverma avatar the-nutty avatar zeaposs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

anglesharp.css's Issues

Make StyleCollectionExtentions.ComputeDeclarations take a IEnumerable<ICssStyleRule>to allow for caching of the StyleCollection.

Bug Report

Iterating through IWindow.GetStyleCollection is slow if doing on multiple elements, this could be because _sheets is deferred or just because GetEnumerator is doing lots of work.

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

This relates to #51 where i was hoping to be able to cache the StyleCollection returned by IWindow.GetStyleCollection to significantly speed up the process of calling StyleCollection.ComputeDeclarations on every element in a document. However it is still just as slow.

Possible Solution

  1. Make ComputeDeclarations take a IEnumerable that could be pre calculated.
  2. Optionally 1 but return a IEnumerable from IWindow.GetStyleCollection.

Im happy to implement the change if that would help as if possible i would appreciate it if we could get this out in a patch version, but wanted to run potential solutions by you before creating a PR.

Removing properties causes empty value when serializing

Example:

var p = new HtmlParser(new HtmlParserOptions(), BrowsingContext.New(new Configuration().WithCss()));
var dom = p.ParseDocument(@"<html><body><div style=""background: 0;"">Test</div></body></html>");
var div = dom.QuerySelector("div");
var style = div.GetStyle();
style.RemoveProperty("background-position-x");
style.RemoveProperty("background-position-y");
var css = style.CssText; // -> "background: "

FWIW, both Chrome and Firefox output "background-color: rgba(0, 0, 0, 0); background-repeat: repeat; background-attachment: scroll; background-image: none; background-size: auto auto; background-origin: padding-box; background-clip: border-box;" in this case.

Numerical font-weight not parsed correctly in font shorthand

Description

A font shorthand declaration is not parsed correctly if it contains a numerical font-weight.

Steps to Reproduce

var p = new HtmlParser(new HtmlParserOptions(), BrowsingContext.New(new Configuration().WithCss(new CssParserOptions())));
var dom = p.ParseDocument(@"<html><body><div style=""font: 400 12px serif"">Test</div></body></html>");
var div = dom.QuerySelector("div");
var style = div.GetStyle(); // -> style.Length == 0
var css = style.CssText; // -> ""

It works if font-weight is specified using a constant, e.g. font: bold 12px serif.

Possible Solution

It seems the numerical case is not considered here:

if (weight == null)
{
weight = source.ParseConstant(Map.FontWeights);
source.SkipSpacesAndComments();
}

Question: how to extract value from StringValue?

I need to access actual value of CSS string literal (StringValue class). Right now I can only access CssText property, which is string literal itself with quotes and required escaping.

Basically I would like to access StringValue.Value property, but it is not public right now. Maybe you can add ICssStringValue interface with additional Value property?

StyleCollectionExtensions.SortBySpecificity does not account for null selector.

Bug Report

I have observed instances where ICssStyleRule.Selector is null. This causes StyleCollectionExtensions.SortBySpecificity to throw a null reference exception.

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Possible Solution

I unfortunately dont have the raw HTML that caused this issue but i have confirmed the following change does fix the issue.

            rules.Where(m => m.Selector?.Match(element) ?? false).OrderBy(m => m.Selector.Specificity);

Would you accept a PR for this solution?

Example on how to format CSS?

I'm sorry if it's a dumb question, but I've been trying to format CSS (prettify) the same way I do for HTML and for some reason things fail for me. I know the code is in PowerShell (which is loading your NET library) but I don't have a way to build this in C#.

This is the output I'm getting. Is it like I'm missing small detail or a bug (unlikely)?

image

function Format-CSS {
    [CmdletBinding()]
    param(
        [string] $File,
        [string] $OutputFile
    )
    if ($File -and (Test-Path -LiteralPath $File)) {
        $FileContent = [IO.File]::ReadAllText($file)

        $CssParser = New-Object -TypeName AngleSharp.Css.Parser.CssParser
        $ParsedDocument = $CssParser.ParseStyleSheet($FileContent)
        $StringWriter = [System.IO.StringWriter]::new()
        $PrettyMarkupFormatter = New-Object -TypeName AngleSharp.Css.PrettyStyleFormatter
        $ParsedDocument.ToCss($StringWriter, $PrettyMarkupFormatter)

        $FormattedCSS = $StringWriter.ToString()

        if ($FormattedCSS) {
            [IO.File]::WriteAllText($OutputFile, $FormattedCSS)
        }
    }
}

HTML is 99% the same, and it works just fine.

function Format-HTML {
    [CmdletBinding()]
    param(
        [string] $File,
        [string] $OutputFile
    )
    if ($File -and (Test-Path -LiteralPath $File)) {
        $FileContent = [IO.File]::ReadAllText($file)

        $HTMLParser = New-Object -TypeName AngleSharp.Html.Parser.HtmlParser
        $ParsedDocument = $HTMLParser.ParseDocument($FileContent)
        $StringWriter = [System.IO.StringWriter]::new()
        $PrettyMarkupFormatter = New-Object -TypeName AngleSharp.Html.PrettyMarkupFormatter
        $ParsedDocument.ToHtml($StringWriter, $PrettyMarkupFormatter)
        #$ParsedDocument.StyleSheets

        $FormattedHTML = $StringWriter.ToString()

        if ($FormattedHTML) {
            [IO.File]::WriteAllText($OutputFile, $FormattedHTML)
        }
    }
}

What am I missing? Would you be able to provide simple C# based example how you would format CSS natively?

ElementExtensions.GetInnerText removes whitespace before span

Bug Report

Description

The GetInnerText() extension method in v0.12.1 of AngleSharp.Css removes whitespace before a <span> element; that isn't desired behavior.

Steps to Reproduce

using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;

static class Program
{
	static void Main()
	{
		var ctx = BrowsingContext.New(Configuration.Default.WithCss());
		var parser = ctx.GetService<IHtmlParser>();
		var nodeList = parser.ParseFragment("<div><div>Div with <span>a span</span> in it.</div></div>", null);
		var element = (IElement)nodeList[0];
		Console.WriteLine(element.GetInnerText());
		Console.ReadKey();
	}
}

Expected behavior: Outputs "Div with a span in it.".

In all of Firefox, Chrome, Edge, and IE, pasting var wrapper = document.createElement("div"); wrapper.innerHTML = "<div>Div with <span>a span</span> in it.</div>"; wrapper.innerText into the developer console produces this output.

Actual behavior: Outputs "Div witha span in it."

Environment details: .NET Framework v4.6.2

Possible Solution

The problem appears to lie at the end of ProcessText. I'm not sure I fully understand the intent there, it appears to remove a single space after the last non-whitespace character of a text node with trailing white-space. I think that might not be correct when the subsequent node is an inline element, the text node is at the end of an inline element, or if the style for the text node had white-space pre or pre-wrap.

CSS shorthand property **text-decoration** is not properly expanded

Bug Report

Prerequisites

  • [ Yes ] Can you reproduce the problem in a [MWE]
  • [ Yes 0.12.1 ] Are you running the latest version of AngleSharp?
  • [ Yes ] Did you check the FAQs to see if that helps you?
  • [ Yes ] Are you reporting to the correct repository? (if its an issue with the core library, please report to AngleSharp directly)
  • [ Yes ] Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

CSS shorthand property text-decoration is not properly expanded.

Steps to Reproduce

  1. Configure AngleSharp WithCss.
  2. Using a new BrowsingContext, parse this HTML:
<!DOCTYPE html>
<html>
<head><title></title></head>
<body style="text-decoration: underline dotted;"></body>
</html>
  1. Get the style for the Body element.
    var styleDeclaration = document.Body.ComputeCurrentStyle();

Expected behavior:
As per CSS text-decoration

<'text-decoration-line'> || <'text-decoration-style'> || <'text-decoration-color'>.

"text-decoration-style: dotted"
"text-decoration-line: underline"

Actual behavior:

"text-decoration-style: underline"
"text-decoration-line: dotted"

Environment details:
Windows 10, .Net 4.7

Possible Solution

Swap so text-decoration-style is expanded into text-decoration-line and vice-versa.

PS: When you are changing CSS properties behavior, could you please override the ToString() method to return the CssText. This will make working in the debugger much easier.

Counters used in content css property are broken after calling ToCss

Bug Report

Description

After parsing a CSS stylesheet with counter() call inside content: property, ToCss() returns invalid CSS.

Steps to Reproduce

var parser = new CssParser();
var sheet = parser.ParseStyleSheet(@"
h1::before {
  counter-increment: h1;
  content: counter(h1) "".\00A0"";
}
");
var css = sheet.ToCss();

Expected behavior:
h1::before { counter-increment: h1 1; content: counter(h1) ". " }
Actual behavior:
h1::before { counter-increment: h1 1; content: h1 decimal ". " }

Environment details: [OS, .NET Runtime, ...] .NET 4.8/Windows 10 AngleSharp.Css 0.14.1

Question: why SrcDeclaration uses AnyValueConverter?

I'm trying to find url function calls and because @font-face{ src } uses AnyValue, I cannot detect urls there.
I can only detect src property, but it is not very usefull, as @font-face src value is a comma-separated list of url/format/local function combinations.

CSS value normalizing?

I realize the devel branch is basically alpha, so this is a "is this the behavior going forward?" type of question.

Basically, I'm curious if it's intentional that values such as background: 0 or color: black become background: left and color: rgba(0, 0, 0, 1), respectively. The end result is functionally equivalent, but given that, is there a reason to convert the source value?

I can understand splitting the AngleSharp project into separate projects, but my expectation was that the output would be the same in AngleSharp.Css as it is currently in the combined project.

For reference, this question originates from this issue in HtmlSanitzer: mganss/HtmlSanitizer#117.

NullReference exception when invoking GetStyle() in configuration without CSS

Example:

// no .WithCss() here!
var p = new HtmlParser(new HtmlParserOptions(), BrowsingContext.New(new Configuration()));
var dom = p.ParseDocument(@"<html><body><div style=""color: black"">Test</div></body></html>");
var div = dom.QuerySelector("div");
var style = div.GetStyle(); // NullReferenceException

I believe this occurs here:

var decl = parser.ParseDeclaration(value);

GetInnerText does not work

var doc = new HtmlParser().ParseDocument("<HTML><BODY><div>1<br/>2</div></BODY></HTML>"); Console.WriteLine(doc.DocumentElement.GetInnerText());

I want to know what's wrong

CSS rule with only `grid-template-areas` throws exception when requesting `CssText`

Bug Report

Description

CSS rule with only grid-template-areas throws exception when requesting CssText

Steps to Reproduce

[Test]
public void CssRuleWithOnlyGridTemplateAreasLegal()
{
	var snippet = @"div#A { grid-template-areas: ""a b b"" ""a c d"" }";
	var rule = ParseRule(snippet);
	var text  = rule.CssText;
	Assert.AreEqual(snippet, text);
}

Expected behavior:
Test should pass

Actual behavior:
Crash with exception:

System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
   at AngleSharp.Css.Values.GridTemplate.get_CssText() in c:\work\AngleSharp.Css\src\AngleSharp.Css\Values\GridTemplate.cs:line 67
   at AngleSharp.Css.Dom.CssProperty.get_Value() in c:\work\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\CssProperty.cs:line 49
   at AngleSharp.Css.Dom.CssProperty.ToCss(TextWriter writer, IStyleFormatter formatter) in c:\work\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\CssProperty.cs:line 124
   at AngleSharp.Css.CssStyleFormatter.AngleSharp.IStyleFormatter.BlockDeclarations(IEnumerable`1 declarations)
   at AngleSharp.Css.Dom.CssStyleDeclaration.ToCssBlock(IStyleFormatter formatter) in c:\work\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\CssStyleDeclaration.cs:line 192
   at AngleSharp.Css.Dom.CssStyleRule.ToCss(TextWriter writer, IStyleFormatter formatter) in c:\work\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\Rules\CssStyleRule.cs:line 64
   at AngleSharp.FormatExtensions.ToCss(IStyleFormattable style, IStyleFormatter formatter)
   at AngleSharp.Css.Dom.CssRule.get_CssText() in c:\work\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\CssRule.cs:line 36

CSS **boder-style** not properly expanded when 3 values are given.

Bug Report

Prerequisites

  • [ Yes ] Can you reproduce the problem in a [MWE]
  • [ Yes 0.12.1 ] Are you running the latest version of AngleSharp?
  • [ Yes ] Did you check the FAQs to see if that helps you?
  • [ Yes ] Are you reporting to the correct repository? (if its an issue with the core library, please report to AngleSharp directly)
  • [ Yes ] Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

CSS boder-style not properly expanded when 3 values are given.

Steps to Reproduce

  1. Configure AngleSharp WithCss.
  2. Using a new BrowsingContext, parse this HTML:
<!DOCTYPE html>
<html>
<head><title></title></head>
<body style="border-style: hidden double dashed;"></body>
</html>
  1. Get the style for the Body element.
    var styleDeclaration = document.Body.ComputeCurrentStyle();

Expected behavior:
As per CSS border-style

When three values are specified, the first style applies to the top, the second to the left and right, the third to the bottom.

"border-top-style: hidden"
"border-left-style: double"
"border-right-style: double"
"border-bottom-style: dashed"

Actual behavior:

"border-top-style: double"
"border-left-style: double"
"border-right-style: hidden"
"border-bottom-style: dashed"

Environment details:
Windows 10, .Net 4.7

Possible Solution

Fix the order into which the property is expanded.

Parsing or setting style attributes with [out of range values] should not throw exceptions

Thanks for creating this excellent project. I really like it.

When using CssEngine, some of the websites I try to load throw OverflowException: Value was either too large or too small for an (Int32, ...).

The parser throws this error and ignores the rest of the style sheet.

Here is a shortened call stack where the error happens: (sorry, the call stack is to large to paste it here)
AngleSharp.Parser.Css.CssNumberToken.get_IntegerValue()
...
...
AngleSharp.Parser.Css.CssParser.ParseStylesheetAsync()

Practically, web browsers treat this errors in more relaxed mode and they don't throw any exceptions; they check the supplied value and set either the maximum or the minimum for the given data type. The same also applies for setting style values directly using CSSStyleDeclaration class

for example, the following script tries to set zIndex with too large value.

var elm=document.getElementById('ID');
elm.style.zIndex='99999999999999999999999999999999999999999';
elm.style.zIndex;

If you run this script in debugger console of any web browser you will get the maximum value of Int32 "2147483647"

While setting too small value like the following example:

elm.style.zIndex='-99999999999999999999999999999999999999999';
will return the minimum value of Int32 "-2147483648"

So, does AngleSharp has any option to control whether to automatically convert out of range values or to throw exceptions (maybe something like strict mode). I'm talking about configuration option because I didn't read the specifications of parsing CSS style sheets and I don't want you to break any specs. But if the specs allow automatic conversion then there is no need for any option and the conversion should be applied automatically.

Thanks and good luck,
Atef

CSS property value API

See AngleSharp #240 for full discussion.

The efforts to create an easy-to-use, yet efficient, and extensible API for values are already started. Nevertheless, this is (due to the nature of the problem) a very complex problem. Independent of the complexity it needs to be solved, as the content of the values (i.e., the object behind the string) is / can be very important for the user.

Expose StyleCollectionExtensions publicly

New Feature Proposal

Currently if you are calling CssApiExtensions.ComputeCurrentStyle for a large number of elements in a single document it can be very slow, by allowing the caller to cache the StyleCollection returned from window.GetStyleCollection in WindowExtensions.GetComputedStyle this operation can be speed up significantly. I believe this was mentioned in another issue but im unable to find it at current.

Description

Is there a reason StyleCollectionExtensions cant be public, that would fix this issue as the caller could provide there own version of the WindowExtensions.GetComputedStyle with caching.

Would you be open to a PR that did this, if i have some spare time i may try to profile this code path further and see if there are any other easy wins.

Background

If you need to walk the dom calculating the style of all/multiple elements.

Specification

N/A

Rendering?

See AngleSharp #26 for the full discussion.

The IRenderDevice will be part of that story, even though the CSS library won't build up a render tree. Nevertheless, the CSS library will contain everything to make style computations and empower a rendering library in the task to derive the render tree.

"Initial" when parsing value without unit

Thanks for creating this great project.
I'm trying to use it to parse css styles inside SVG files. It works greate, but I have a problem with units.
In CSS inside SVG units are not required. For example: stroke-width: 2; is correct. When I try to parse something without unit I get CssProperty with "initial" value insted of 2 (for example).
Is there any way to get a valid value instead of "initial"?

Below is sample code:

string svgStyle = "rect { fill: red; stroke: blue; stroke-width: 3 }";
CssParser cssParser = new CssParser(new CssParserOptions()
            {
                IsIncludingUnknownDeclarations = true,
                IsIncludingUnknownRules = true,
                IsToleratingInvalidSelectors = true,
            });
ICssStyleSheet sheet = cssParser.ParseStyleSheet(svgStyle);

Expansion of shorthand properties to longhand

Hi,

I am trying to use AngleSharp.Css 0.10. Most things work fine, however, I've stumbled upon one issue.

Normally, shorthand properties expand correctly, for example:
border-color: red =>

  • border-left-color: red;
  • border-top-color: red;
  • border-right-color: red;
  • border-bottom-color: red;

border: 1px solid red =>

  • border-width: 1px;
  • border-style: solid;
  • border-color: red;

This is all OK. But what does not work is recursive expansion into longhand properties. I would expect setting border to result in border-width border-style and border-color (as it does), as well as border-X-width border-X-style and border-X-color

Is there a quick way to fix this? And is there some reflection API figure out that border-width expands into border-X-width?

Thanks,
-Todor

linear-gradients are not written to css with angles

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

Parsing a style rule with a linear-gradient, and then writing the same rule back to css causes the angle to get removed.

Steps to Reproduce

class Program
    {
        static void Main(string[] args)
        {
            var parser = new CssParser();
            var styleSheet = parser.ParseStyleSheet(".bg { background-image: linear-gradient(to right, #FF866E 0, #F15A24 0); }");
            var css = styleSheet.ToCss();
            Console.WriteLine(css);
            // Outputs
            // .bg { background-image: linear-gradient(rgba(255, 134, 110, 1) 0, rgba(241, 90, 36, 1) 0) }
        }
    }

Using a @media rule without explicitly registering an IRenderDevice causes a NullReferenceException

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (if its an issue with the core library, please report to AngleSharp directly)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

Attempting to call ComputeCurrentStyle() when any @media rules are defined causes a NullReferenceException to be thrown at:

   at AngleSharp.Css.Dom.MediaListExtensions.IsInvalid(ICssMedium medium, IRenderDevice device, String keyword, DeviceCategory category) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\MediaListExtensions.cs:line 60
   at AngleSharp.Css.Dom.MediaListExtensions.IsInvalid(ICssMedium medium, IRenderDevice device) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\MediaListExtensions.cs:line 53
   at AngleSharp.Css.Dom.MediaListExtensions.Validate(ICssMedium medium, IRenderDevice device) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\MediaListExtensions.cs:line 48
   at AngleSharp.Css.Dom.MediaListExtensions.<>c__DisplayClass4_0.<Validate>b__0(ICssMedium m) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\MediaListExtensions.cs:line 38
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
   at AngleSharp.Css.Dom.MediaListExtensions.Validate(IMediaList list, IRenderDevice device) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\MediaListExtensions.cs:line 38
   at AngleSharp.Css.Dom.ValidationExtensions.IsValid(ICssMediaRule rule, IRenderDevice device) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\ValidationExtensions.cs:line 30
   at AngleSharp.Css.Dom.StyleCollection.<GetRules>d__6.MoveNext() in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\StyleCollection.cs:line 68
   at AngleSharp.Css.Dom.StyleCollection.<GetEnumerator>d__5.MoveNext() in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Dom\Internal\StyleCollection.cs:line 48
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__1.MoveNext()
   at AngleSharp.Css.Extensions.StyleCollectionExtensions.ComputeCascadedStyle(StyleCollection styleCollection, IElement element) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Dom\StyleCollectionExtensions.cs:line 77
   at AngleSharp.Css.Extensions.StyleCollectionExtensions.ComputeDeclarations(StyleCollection rules, IElement element, String pseudoSelector) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Dom\StyleCollectionExtensions.cs:line 54
   at AngleSharp.Dom.WindowExtensions.GetComputedStyle(IWindow window, IElement element, String pseudo) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\WindowExtensions.cs:line 55
   at AngleSharp.Dom.CssApiExtensions.ComputeCurrentStyle(IElement element) in D:\projects\AngleSharp.Css\src\AngleSharp.Css\Extensions\CssApiExtensions.cs:line 27
   at AngleSharpTest.Program.MediaQueryCss() in D:\projects\Test2\AngleSharpTest\Program.cs:line 109

Steps to Reproduce

Compile and run a program calling MediaRuleCss:

    private static void MediaRuleCss()
    {
      var browsingContext = BrowsingContext.New(Configuration.Default.WithCss());
      var htmlParser = browsingContext.GetService<IHtmlParser>();
      var document = htmlParser.ParseDocument("<html><head><style>@media screen { }</style></head><body></body></html>");
      document.Body.ComputeCurrentStyle();
    }

Expected behavior:
Not getting a NullReferenceException. By default it should probably be assumed that the device is a screen.

Actual behavior:
Got NullReferenceException

Environment details:
.NET 4.7.2, Windows 10.0.18334.1]

Possible Solution

The only implementation of IRenderDevice included in AngleSharp.Css currently is MockRenderDevice which is only used for tests. I think a DefaultRenderDevice should be registered with some sane default values (i.e. there should just be hardcoded defaults independent on where the code is running if the goal isn't to render anything anyways).

ParseStyleSheetAsync throws NPE on empty string

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

Calling CssParser.ParseStyleSheetAsync("") throws a System.NullReferenceException.

Steps to Reproduce

Code:

class Program
    {
        static async Task Main(string[] args)
        {
            var parser = new CssParser();
            var s = await parser.ParseStyleSheetAsync("");

            Console.WriteLine(s);
        }
    }

Stacktrace:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at AngleSharp.Text.TextSource.DetectByteOrderMarkAsync(CancellationToken cancellationToken)
at AngleSharp.Text.TextSource.PrefetchAllAsync(CancellationToken cancellationToken)
at AngleSharp.Css.Parser.CssParser.ParseStyleSheetAsync(String content, CancellationToken cancelToken)

Expected behavior: [What you expected to happen]
To behave like the non-async version which correctly parses the empty string and returns an empty stylesheet.

Environment details: [OS, .NET Runtime, ...]
Windows 10
.NET Core 3.0.100

Exception regarding "iso-2022-cn" encoding

I'm currently migrating from Alba.Css to AngleSharp.Css.

Having this code:

var parser = new CssParser();
parser.ParseStyleSheet(".dummy { font-family: 'Poiret One' }");

I'm running it on a German Windows 10, 64-bit inside a .NET 4.7.2 WinForms application.

I'm getting this error:

System.ArgumentException: '"iso-2022-cn" ist kein unterstützter Codierungsname. Informationen zum Definieren einer benutzerdefinierten Codierung entnehmen Sie der Dokumentation zur Encoding.RegisterProvider-Methode.
Parametername: name'

The stack trace contains one item only:

at System.Globalization.EncodingTable.internalGetCodePageFromName(String name)

The error occurs in the last line (ParseStyleSheet) of my code snippet.

I honestly do not unserstand where the strange encoding is pulled from.

What I assume is that maybe I have to register some "global" settings to AngleSharp.Css, but I found nothing in detail that I should call.

My question

What am I doing wrong here, and how can I solve this?

Two unbalanced parentheses cause OutOfMemoryException in ParseStylesheet

Our security team required us to fuzz our use of AngleSharp. During fuzzing we found that, if there are two unbalanced parentheses in a stylesheet, then CssParser.ParseStylesheet will blow up and throw an OutOfMemoryException. For example, trying to parse this CSS file will result in an OOM

@media (-ms-high-contrast:white-on-black { } @media (-ms-high-contrast:white-on-black { }

The parser behaves as expected if only one parenthesis is missing (no massive increase in memory usage).

0701dbcc-mod-twoRuleRepro.txt
0701dbcc-mod-oneRuleRepro.txt

FormatException in ColorParse

Issue Templates

Please use one of the following templates to create your issue:

Getting the following exception information on parsing some html. No chance to recover exists because exception breaks parsing. Stack trace is:

System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(ReadOnlySpan`1 str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(ReadOnlySpan`1 s, NumberStyles style, NumberFormatInfo info)
   at AngleSharp.Css.Parser.ColorParser.ParseRgbComponent(StringSource source)
   at AngleSharp.Css.Parser.ColorParser.ParseRgba(StringSource source)
   at AngleSharp.Css.Parser.ColorParser.Start(StringSource source)
   at AngleSharp.Css.Parser.ColorParser.ParseColor(StringSource source)
   at AngleSharp.Css.Converters.StructValueConverter`1.Convert(StringSource source)
   at AngleSharp.Css.Converters.OrValueConverter.Convert(StringSource source)
   at AngleSharp.Css.Converters.ValueConverterExtensions.Convert(IValueConverter converter, String value)
   at AngleSharp.Css.Dom.CssProperty.set_Value(String value)
   at AngleSharp.Css.Dom.CssStyleDeclaration.SetProperty(String propertyName, String propertyValue, String priority)
   at AngleSharp.Css.Parser.CssBuilder.CreateDeclarationWith(ICssProperties properties, CssToken& token)
   at AngleSharp.Css.Parser.CssBuilder.FillDeclarations(CssStyleDeclaration style, CssToken token)
   at AngleSharp.Css.Parser.CssParser.Parse[T](String source, Func`3 create)
   at AngleSharp.Css.Dom.CssStyleDeclaration.Update(String value)
   at AngleSharp.Css.Dom.ElementCssInlineStyleExtensions.CreateStyle(IElement element, String source)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.GetValueLocked(TKey key, CreateValueCallback createValueCallback)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.GetValue(TKey key, CreateValueCallback createValueCallback)
   at AngleSharp.Css.StyleAttributeObserver.AngleSharp.Dom.IAttributeObserver.NotifyChange(IElement host, String name, String value)
   at AngleSharp.Dom.Element.SetupElement()
   at AngleSharp.Html.Parser.HtmlDomBuilder.CloseCurrentNode()
   at AngleSharp.Html.Parser.HtmlDomBuilder.InBodyEndTagAnythingElse(HtmlTagToken tag)
   at AngleSharp.Html.Parser.HtmlDomBuilder.InBodyEndTag(HtmlTagToken tag)
   at AngleSharp.Html.Parser.HtmlDomBuilder.Parse(HtmlParserOptions options)
   at AngleSharp.Html.Parser.HtmlParser.Parse(HtmlDocument document)
   at CI. <snipped>

Appears to be because of the numeric.Parse functions. At the very least the exceptions should be caught and null returned.

Thanks.

Documentation

For the version v1 of this project (or partially when AngleSharp.Core reaches v1) some documentation is required.

The outline for the CSS project is (roughly):

  • Introduction
  • Additions / CSSOM
  • Parsers
  • (Sample) use-cases w. (simple) examples
  • Core interfaces
  • Services and extensibility

Make ICssFunctionValue public

New Feature Proposal

Description

I'm trying to migrate to latest version and finally try to implement urls extraction from css without changes to AngleSharp itself (see #10). Looks like only missing part is unavailability of ICssFunctionValue interface, implemented by UrlReference

Background

I need to find all url's in css file, specified using 'url()' function.

The default style sheet in CssStylingService.Default is ignored

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (if its an issue with the core library, please report to AngleSharp directly)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

CssStylingService defines a Default style sheet (which by default is the one specified by W3C), and allows changing this with SetDefault. However this value is never read anywhere and nothing supplies default css rules.

Steps to Reproduce

Compile and run a program calling DefaultStyleSheetTest:

    private static void DefaultStyleSheetTest()
    {
      var browsingContext = BrowsingContext.New(Configuration.Default.WithCss());
      var htmlParser = browsingContext.GetService<IHtmlParser>();
      var document = htmlParser.ParseDocument("<html><body><b>Hello, World!</b></body></html>");
      var boldStyle = document.Body.FirstElementChild.ComputeCurrentStyle();
      Console.WriteLine(boldStyle.GetFontWeight());
    }

Expected behavior: "bolder" should be printed to the console

Actual behavior: an empty string is printed to the console

Environment details: .NET 4.7.2, Windows 10.0.18334.1

Possible Solution

Expose CssStylingService.Default through the IStylingService interface. Make StyleExtensions.GetStyleSheets yield the DefaultStyle as the first style sheet (given that the IStylingService can be accessed and has Default and it is not disabled.

Some indexers are missing a `DomAccessorAttribute`

The ICssRuleList for instance does not specify the DomAccessorAttribute Getter attribute for the index operation.

There may be other places - essentially we should look up all uses of this to properly specify the property.

GetInnerText() performace

Bug Report

I am writing, what I would think is a fairly simple usage of AngleSharp[.Css], I am extracting a html table of covid-19 cases etc.. by country. The headers [or other cells] can contain html <br>. INode.Text() [an extension] and INode.TextContent() remove the <br> returning values like “TotalCases”. My implementation parses the 3000ish cells in 4.6 seconds. Using AngleSharp.Css’s ElementExtensions’s string GetInnerText(this IElement element); takes over 8 minutes makeing it unusable.

I assume you must implement Css’s display:none and visibility:hidden. I do not require that functionality, as I  do not require an implementation of Javascript. If GetInnerText()  can not be sped up a reasonable solution would be to use something like my code with your implementation of html entities such as © etc..

The attached project’s interesting code is in AngleSharpCssSpeedFault.cs.
AngleSharpCssSpeedFault.zip

The last method InnerText(IElement) has a #if to switch between the two implementations of InnerText().

Prerequisites

Run the attached solution.

Description

see above

Steps to Reproduce

  1. Run the solution
  2. Change the #if in the last method InnerText()
  3. Run the solutino again.

Possible Solution

Use my InnerText() but add the expanding of all html & entities as that is missing.

Loading background-image from CSS

See AngleSharp #188 for full discussion.

Such as recursive downloads (or similar CSSOM oriented downloads), the resources requested in values should also be handed over to the corresponding requesters - if there are any, and only if resource loading is activate!

System.FormatException thown parsing CSS

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (if its an issue with the core library, please report to AngleSharp directly)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

[Description of the bug]
When parsing CSS with some very odd table styles a System.FormatException is thrown.
I think this is caused by the letter-spacing:-.px in the following CSS block (see steps to reproduce)
Note this is from an email hence the unusual styles and seemingly useless table.

<table border="0" cellpadding="0" cellspacing="0" style="background-color: #0098;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="45%">
    <tbody>
    <tr>
        <td align="center" style="color:#FFFFFF; font-family:Helvetica, Arial, sans-serif; font-size:16px; font-weight:bold; letter-spacing:-.px; line-height:100%; padding-top:7px; padding-right:8px; padding-bottom:7px; padding-left:8px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" valign="middle">
            <a href="test.com" style="color: #FFFFFF;text-decoration: none;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;font-weight: normal;" target="_blank">Click Here</a>
        </td>
    </tr>
    </tbody>
</table>

Steps to Reproduce

Create a C# project with AngleShart and AngleSharp.Css installed and run the following code

            var context = BrowsingContext.New(Configuration.Default.WithCss());
            var htmlParser = context.GetService<IHtmlParser>();
            var doc = htmlParser.ParseDocument("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color: #0098;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;\" width=\"45%\">\r\n\r\n    <tbody>\r\n\r\n    <tr>\r\n\r\n        <td align=\"center\" style=\"color:#FFFFFF; font-family:Helvetica, Arial, sans-serif; font-size:16px; font-weight:bold; letter-spacing:-.px; line-height:100%; padding-top:7px; padding-right:8px; padding-bottom:7px; padding-left:8px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;\" valign=\"middle\">\r\n\r\n            <a href=\"test.com\" style=\"color: #FFFFFF;text-decoration: none;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;font-weight: normal;\" target=\"_blank\">Click Here</a>\r\n\r\n        </td>\r\n\r\n    </tr>\r\n\r\n    </tbody>\r\n\r\n</table>\r\n");

Expected behavior: [What you expected to happen]
Should parse the HTML without throwing.
Actual behavior: [What actually happened]
Throws with the following stack trace.

System.FormatException
  HResult=0x80131537
  Message=Input string was not in a correct format.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
   at AngleSharp.Css.Parser.UnitParser.GetLength(Unit test)
   at AngleSharp.Css.Parser.UnitParser.ParseLength(StringSource source)
   at AngleSharp.Css.Converters.StructValueConverter`1.Convert(StringSource source)
   at AngleSharp.Css.Converters.OrValueConverter.Convert(StringSource source)
   at AngleSharp.Css.Converters.OrValueConverter.Convert(StringSource source)
   at AngleSharp.Css.Converters.OrValueConverter.Convert(StringSource source)
   at AngleSharp.Css.Converters.ValueConverterExtensions.Convert(IValueConverter converter, String value)
   at AngleSharp.Css.Dom.CssProperty.set_Value(String value)
   at AngleSharp.Css.Dom.CssStyleDeclaration.SetProperty(String propertyName, String propertyValue, String priority)
   at AngleSharp.Css.Parser.CssBuilder.CreateDeclarationWith(ICssProperties properties, CssToken& token)
   at AngleSharp.Css.Parser.CssBuilder.FillDeclarations(CssStyleDeclaration style, CssToken token)
   at AngleSharp.Css.Parser.CssParser.Parse[T](String source, Func`3 create)
   at AngleSharp.Css.Dom.CssStyleDeclaration.Update(String value)
   at AngleSharp.Css.Dom.ElementCssInlineStyleExtensions.CreateStyle(IElement element, String source)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.GetValueLocked(TKey key, CreateValueCallback createValueCallback)
   at System.Runtime.CompilerServices.ConditionalWeakTable`2.GetValue(TKey key, CreateValueCallback createValueCallback)
   at AngleSharp.Css.StyleAttributeObserver.AngleSharp.Dom.IAttributeObserver.NotifyChange(IElement host, String name, String value)
   at AngleSharp.Dom.Element.SetupElement()
   at AngleSharp.Html.Parser.HtmlDomBuilder.CloseCurrentNode()
   at AngleSharp.Html.Parser.HtmlDomBuilder.InCellEndTagCell(HtmlToken token)
   at AngleSharp.Html.Parser.HtmlDomBuilder.InCell(HtmlToken token)
   at AngleSharp.Html.Parser.HtmlDomBuilder.Parse(HtmlParserOptions options)
   at AngleSharp.Html.Parser.HtmlParser.Parse(HtmlDocument document)
   at Testing.Program.<Main>d__6.MoveNext() in D:\other code\C#\Testing\Testing\Program.cs:line 137
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Testing.Program.<Main>(String[] args)

Environment details: [OS, .NET Runtime, ...]
.NET core 2

Error in HTML after upgrade to 0.10

I use following Code:

                    element = CreateElement("button", htmlDocument);
                    ((IHtmlElement) element).GetStyle().SetPointerEvents("auto");
                    ((IHtmlElement) element).GetStyle().SetBorderWidth("1px");
                    ((IHtmlElement) element).GetStyle().SetBorderStyle("solid");
                    ((IHtmlElement) element).GetStyle().SetBorderColor("black");

wich creates following HTML:

     <button style="pointer-events: auto;border-width: 1px;border-top: solid rgba(0, 0, 0, 1);border-right: solid rgba(0, 0, 0, 1);border-bottom: solid rgba(0, 0, 0, 1);border-left: solid rgba(0, 0, 0, 1);"</button>

wich is wrong in Chrome, cause then bordersize is 3px and not 1px

Question: Replace font

Is there an easy way in the latest version of AngleSharp to replace a font in a style with another font?

CSSOM From Houdini Spec

Houdini is getting more in shape giving us some of the spec details that are particularly interesting, e.g.,

These two specs define not only how values are represented in IDL, but also how to extend / define properties. Those things are already somehow in AngleSharp.Css but should be made conforming to those specs to be on the same track early.

Expose CSS tokens

It would be nice if you can make CSS tokens public.
In my case I need to extract urls from css, but required functionality (access to tokens) is currently marked as internal.
Right now I use ExCss project (https://github.com/TylerBrinks/ExCSS) for that task, but it wasn't updated in ages and contain critical bugs.

How Parse css style fill rule?

I have this CSS:

var css = @"
	.st0{fill:#AFAA96;stroke:#AFAA96;stroke-miterlimit:10;}
	.st1{fill:none;stroke:#738282;stroke-width:32;stroke-miterlimit:10;}
	.st2{display:none;fill:none;stroke:#738282;stroke-width:32;stroke-miterlimit:10;}
	.st3{display:none;fill:none;stroke:#FAFAFA;stroke-width:32;stroke-miterlimit:10;}"

I try to parse with:

CssParser cssParser = new CssParser();
                    var style = cssParser.ParseStyleSheet(css);
 foreach (ICssStyleRule rule in style.Rules)
 {
    Console.WriteLine(rule.CssText);
 }

The output is:

//.st0 { stroke: rgba(175, 170, 150, 1); stroke-miterlimit: 10 }
//.st1 { stroke: rgba(115, 130, 130, 1); stroke-width: 32; stroke-miterlimit: 10 }
//.st2 { display: none; stroke: rgba(115, 130, 130, 1); stroke-width: 32; stroke-miterlimit: 10 }
//.st3 { display: none; stroke: rgba(250, 250, 250, 1); stroke-width: 32; stroke-miterlimit: 10 }

What happened to fill rule?

CssText property cuts off last semi-colon

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp? Version 0.14.1
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
  • Did you perform a search in the issues?

Description

When using ComputeCurrentStyle() of an element and then calling the CssText property from it, the ending semi-colon is missing.

Steps to Reproduce

  1. Using default configuration
IConfiguration config = Configuration.Default.WithDefaultLoader().WithCss();
var _context = BrowsingContext.New(config);
  1. Using the following element as an example: <textarea id="txtTestArea" style="height:1in; width:6.5in;"></textarea>
  2. Use following code:
var style = element.ComputeCurrentStyle();
var styleText = style.CssText;

Expected behavior:
I expect the variable styleText to have the value "display: inline-block; height: 1in; width: 6.5in;"

Actual behavior: [What actually happened]
However the ending semi-colon is missing (from the width property) and results in "display: inline-block; height: 1in; width: 6.5in"

Environment details: [OS, .NET Runtime, ...]
Operating System: Windows 10 Pro
.Net Runtime: Core 3.1

Possible Solution

The only thing I was able to do is to manually add the semi-colon on to the end of the CssText property.

How to translate code to AngleSharp 0.11.0

Hi,

I'm upgrading code to make use of AngleSharp 0.11.0.

The only thing I can't seem to figure out is how to change this code

            return new HtmlParser(new Configuration().WithCss(e => e.Options = new CssParserOptions
            {
                IsIncludingUnknownDeclarations = true,
                IsIncludingUnknownRules = true,
                IsToleratingInvalidConstraints = true,
                IsToleratingInvalidValues = true
            }));

I already tried this but have no idea how to do it in 0.11

            var options = new HtmlParserOptions();
            var cssParserOptions = new CssParserOptions
            {
                IsIncludingUnknownDeclarations = true,
                IsIncludingUnknownRules = true,
                IsToleratingInvalidSelectors = true
            };

            return new HtmlParser(new Configuration().WithCss() )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.