Code Monkey home page Code Monkey logo

excss's Introduction

#Hi there, I'm Tyler 👋

👔 I'm a Solution Architect, Senior Software Developer, and love all things cloud, web, mobile, & big data

🌍 I'm based in Denver, Colorado

💬 I'm a solution architect and, full stack developer with 20 years professional experience. I specialise in teaching building enterprise applications using .NET, React, Azure and AWS.

🌐 Socials:

LinkedIn

💻 Tech Stack:

C# CSS3 GraphQL HTML5 JavaScript Markdown Rust TypeScript AWS Azure Firebase Google Cloud .Net Angular Bootstrap Electron.js Express.js Jasmine Less NPM NestJS Next JS NodeJS GitHub React Redux React Router RxJS Socket.io TailwindCSS Xamarin fNginx MicrosoftSQLServer MongoDB Postgres Redis Figma GIT Docker Kubernetes Postman Swagger Terraform

📊 GitHub Stats:


🔝 Top Contributed Repo


excss's People

Contributors

boricuaenlaluna avatar gdeswardt avatar h1gdev avatar inforithmics avatar jonlipsky avatar kurtgokhan avatar lee-m avatar lilithsilver avatar matherm-aboehm avatar meir017 avatar russkie avatar tylerbrinks 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

excss's Issues

Question

I was looking for a library that I could use to easily build a valid css style sheet in memory and then write it to disc. It looks to me like ExCSS has a good model and I was thinking of using it and possibly enhancing it to make that task more fluid. Any thoughts or objections?

@media with trailing semicolon not parsed correctly

inside an @media rule, a semicolon after a closing curly brace will make the parser ignore all subsequent style rule sets. With the example below, there will only be one rule after parsing It should be two; one style rule, and one media directive.

@media only screen and (min-width: 768px) { 
     .foo body {font-size: 100%; }; /* < ------- these */
     .bar div { font-size: 90%; }; /* < ------- these  */
} 
h1 { font-size: 3em; }

Declaration.ToString() adds quotes to function arguments

Given input CSS declaration: filter: Alpha(Opacity=0);
Declaration.ToString() gives: filter: Alpha('Opacity=0');

i.e. .something {filter: alpha(opacity=0); } -OR- .something {filter: chroma(color=white); }

I could not fix this, but I will share my workaround:

{
    var result = declaration.ToString();
    if (declaration.Expression.Terms.Count == 1)
    {
        Term term = declaration.Expression.Terms[0];
        if (term.Type == TermType.Function)
        {
            result = declaration.Name + ": " + term.Function.Name + "(" + term.Function.Expression.ToString() + ")";
        }
    }

    return result;
}

Really appreciate this project.

Errors out and parsing stops on some non-standard items.

Is there a mode that will allow this to handle some non-standard CSS used in CSS libraries that need to have support for older IE browsers? Or could this be something added to library by yourself or a contributor? Here is some CSS examples that have seemed to cause the parsing to stop.

Did not seem to like this.
audio:not([controls]) {
display: none;
}

Doesn't like the .2s
.uneditable-input {
-webkit-transition: border linear .2s, box-shadow linear .2s;
}

Media querys seem to end parsing.
@media (max-width: 767px) {
.footer ul > li {
display: block;
}
}

Does not like the \9, which is an IE thing.
img {
width: auto\9;
}

IE Star hack not handled properly

ExCSS doesn't handle properly the CSS Star hack

var x = new ExCSS.Parser().Parse("body { *display: inline; }");
// x.Errors.Count == 1 but I expected 0
// x.Rules[0].ToString() == "body{display:inline;}" => we have lost the *

Bad parse result when filtering with attribute and pseudo class

For this css:

input[type="reset"]::-moz-focus-inner
{
margin: 0;
}

I get a selector list of 3 simple selectors:
input
[type="reset"]
::moz-focus-inner

I think it should be a complex or other type of selector but it should be 1 selector in the parsed result.

This behavior has a side effect for this css:

input[type="reset"]::-moz-focus-inner,a,b,c
{
margin: 0;
}

All is the same like before, but:

  • The selector list has no sepeator
  • a,b,c also parsed as pseudo classes

ArgumentOutOfRangeException with TermList Indexer

Invalid markup is throwing an Exception in the TermList indexer, this should be handled as a parser error. In these two cases, (1) the value is empty, and (2) a semicolon is terminating before an !important.

A pull request will be coming shortly.

       [Test]
        public void Lexer_Handles_Empty_Value()
        {
            Assert.DoesNotThrow(() =>
            {
                var stylesheet = new Parser().Parse(".foo{clear:;}");
                Assert.AreEqual(1, stylesheet.Errors.Count);
                Assert.AreEqual(".foo{clear:;}", stylesheet.ToString());
            });
        }

        [Test]
        public void Lexer_Handles_Invalid_Important_Usage()
        {
            Assert.DoesNotThrow(() =>
            {
                var stylesheet = new Parser().Parse(@".accordion-a {background-color: #c6c6c6; !important;}");
                Assert.IsTrue(stylesheet.Errors.Count > 0);
            });
        }

calc(expr) incorrectly parsed

Example CSS

.step-header-brlje > ul.process-bar > li:not(:first-child):after {
  content: '';
  width: calc(100% - 16px);
  position: absolute;
  left: calc(-50% + 6px);
  top: 10px;
  border-top: 2px solid gray;
}

Result CSS:

.step-header-brlje > ul.process-bar > li:not(:first-child):after {
    content: '';
    width: calc(100% = 16px);
    position: absolute;
    left: calc(-50% = 6px);
    top: 10px;
    border-top: 2px solid gray;
}

Obviously the calc expressions are being parsed wrongly (notice the equal signs instead of math operators).

Can you assist ?

background gradients

Hi, I'm having trouble parsing a line like:

background: -moz-linear-gradient(left, rgba(0,119,152,1) 0%, rgba(1,160,155,1) 100%);

Error is at TermList.AddSeparator().
It throws the "Must call AddTerm AddSeparator in that order" error...

Any tips on how to solve this?

Edit Declaration Term

I am trying to change a valve of a declaration property (Color code) but no matter what I do I am unable to do it.

I am looping the rulesets like this:
For Each rule In sheet.StyleRules
For Each prop In rule.Declarations

           next

next

Please can someone help me out with my failing code or help me find some better way of completing this.

Any help is greatly appreciated.

010100110111010001100101

Calculate final styles by taking cascades into account

First of all a big thank you for creating this awesome read-write CSS parser! Actually I think it's the only one (besides its parent project) for .NET.

Would it be possible for the parser to calculate the final, actual styles after parsing the stylesheet? Like merge declarations by selectors? E.g. if there's a color: #fff declaration for body on ln 3, and a color: #000 on ln 50 the parser would calculate that the actual colour is #000.

Exception on parsing Unicode string

I've got an exception parsing a stylesheet with the following rule:

p.berschrift1, div.berschrift1
{mso-style-name:"\00DCberschrift 1";
mso-style-link:"\00DCberschrift 1 Zchn";
font-size:12.0pt;
font-family:"Times New Roman", "serif";}

Parser fails to convert a string "\00DCberschrift 1" because it tries to interpret 6 characters in ConsumeEscape method. I've changed this to 4 and now it works fine.
What do you think, is this fix correct?

@-ms-viewport not handled properly

When I try to parse the following CSS @-ms-viewport{width:device-width;} I get an unexpected error.

Then I try to convert the parsed rule to a string and I get @-ms-viewport{System.Collections.Generic.List1[ExCSS.RuleSet]}`

The issue is in DocumentRule.ToString and GenericRule.ToString, the List<RuleSet> is concatened instead of its content.

Version 2.0.3 has breaking changes from 2.0.2

When upgrading from package version 2.0.2 to 2.0.3, I noticed that StyleSheet.Rulesets property had disappeared and I had to rollback to 2.0.2 to be able to compile my project. The major version should be changed for a change in the public API.

Using ApiChange, I noticed that there were a lot more changes (including 4 types that were completely removed):

Compare from C:\packages\ExCSS.2.0.2\lib\net45 against C:\packages\ExCSS.2.0.3\lib\net45
ExCSS.dll has 151 changes
    Removed 4 public type/s
        - public enum ExCSS.RuleValueType
        - public class ExCSS.ParserNext
        - public class ExCSS.Function
        - public class ExCSS.Rectangle
    Added 6 public type/s
        + public interface ExCSS.IToString
        + public enum ExCSS.DocumentFunction
        + public class ExCSS.BaseSelector
        + public class ExCSS.DocumentRule
        + public class ExCSS.GenericFunction
        + public class ExCSS.InheritTerm
    public class ExCSS.Model.Extensions.StringExtensions
        + public static string TrimFirstLine(String value)
        + public static System.Text.StringBuilder TrimLastLine(StringBuilder builder)
        + public static System.Text.StringBuilder TrimFirstLine(StringBuilder builder)
    public class ExCSS.AggregateRule
        + interface: ExCSS.Model.ISupportsRuleSets
        - interface: ExCSS.IRuleContainer
        + public virtual List<RuleSet> get_RuleSets()
        + protected void .ctor()
        - public virtual List<RuleSet> get_Declarations()
        - protected void .ctor(StyleSheet context)
    public class ExCSS.ConditionalRule
        + protected void .ctor()
        - protected void .ctor(StyleSheet context)
    public enum ExCSS.Combinator
        + public const ExCSS.Combinator Namespace - Value: 4
    public struct ExCSS.HtmlColor
        Base type changed: System.ValueType -> ExCSS.Term
        + public byte A
        + public byte R
        + public byte G
        + public byte B
        + public static ExCSS.HtmlColor FromHsl(Single h,Single s,Single l)
        - public int get_Value()
        - public byte get_A()
        - public byte get_R()
        - public byte get_G()
        - public byte get_B()
        - public string ToCss()
        - public string ToHtml()
    public class ExCSS.FontFaceRule
        + interface: ExCSS.Model.ISupportsDeclarations
        + public virtual ExCSS.StyleDeclaration get_Declarations()
        - public ExCSS.StyleDeclaration get_Declarations()
    public class ExCSS.ImportRule
        + interface: ExCSS.Model.ISupportsMedia
        + public virtual ExCSS.MediaTypeList get_Media()
        - public ExCSS.MediaTypeList get_Media()
    public class ExCSS.KeyframeRule
        + interface: ExCSS.Model.ISupportsDeclarations
        + public virtual ExCSS.StyleDeclaration get_Declarations()
        - public ExCSS.StyleDeclaration get_Declarations()
    public class ExCSS.MediaRule
        + interface: ExCSS.Model.ISupportsMedia
        + public virtual ExCSS.MediaTypeList get_Media()
        - public ExCSS.MediaTypeList get_Media()
    public class ExCSS.PageRule
        + interface: ExCSS.Model.ISupportsSelector
        + interface: ExCSS.Model.ISupportsDeclarations
        + public virtual ExCSS.BaseSelector get_Selector()
        + public virtual void set_Selector(BaseSelector value)
        + public virtual ExCSS.StyleDeclaration get_Declarations()
        - public ExCSS.SimpleSelector get_Selector()
        - public void set_Selector(SimpleSelector value)
        - public string get_SelectorText()
        - public void set_SelectorText(String value)
        - public ExCSS.StyleDeclaration get_Declarations()
    public class ExCSS.StyleDeclaration
        + public ExCSS.RuleSet get_ParentRule()
        + public void set_ParentRule(RuleSet value)
    public class ExCSS.StyleRule
        + interface: ExCSS.Model.ISupportsSelector
        + interface: ExCSS.Model.ISupportsDeclarations
        + public virtual ExCSS.BaseSelector get_Selector()
        + public virtual void set_Selector(BaseSelector value)
        + public virtual ExCSS.StyleDeclaration get_Declarations()
        + public void .ctor(StyleDeclaration declarations)
        - public ExCSS.SimpleSelector get_Selector()
        - public void set_Selector(SimpleSelector value)
        - public ExCSS.StyleDeclaration get_Declarations()
    public class ExCSS.SupportsRule
        + public bool get_IsSupported()
        + public void set_IsSupported(Boolean value)
    public class ExCSS.GenericRule
        Base type changed: ExCSS.RuleSet -> ExCSS.AggregateRule
    public class ExCSS.SimpleSelector
        Base type changed: System.Object -> ExCSS.BaseSelector
        + public virtual string ToString(Boolean friendlyFormat,Int32 indentation)
        - public virtual string ToString()
        - public string ToString(Boolean friendlyFormat,Int32 indentation)
        - public void .ctor()
    public class ExCSS.ComplexSelector
        Base type changed: ExCSS.SimpleSelector -> ExCSS.BaseSelector
        + public ExCSS.ComplexSelector AppendSelector(BaseSelector selector,Combinator combinator)
        + public virtual string ToString(Boolean friendlyFormat,Int32 indentation)
        - public ExCSS.ComplexSelector AppendSelector(SimpleSelector selector,Combinator combinator)
        - public virtual string ToString()
        - public string ToString(Boolean friendlyFormat,Int32 indentation)
    public class ExCSS.SelectorList
        Base type changed: ExCSS.SimpleSelector -> ExCSS.BaseSelector
        + interface: System.Collections.Generic.IEnumerable`1<ExCSS.BaseSelector>
        - interface: System.Collections.Generic.IEnumerable`1<ExCSS.SimpleSelector>
        + protected List<BaseSelector> Selectors
        - protected List<SimpleSelector> Selectors
        + public ExCSS.BaseSelector get_Item(Int32 index)
        + public void set_Item(Int32 index,BaseSelector value)
        + public ExCSS.SelectorList AppendSelector(BaseSelector selector)
        + public virtual IEnumerator<BaseSelector> GetEnumerator()
        + public string ToString(Boolean friendlyFormat,Int32 indentation)
        - public ExCSS.SimpleSelector get_Item(Int32 index)
        - public void set_Item(Int32 index,SimpleSelector value)
        - public ExCSS.SelectorList AppendSelector(SimpleSelector selector)
        - public virtual IEnumerator<SimpleSelector> GetEnumerator()
    public class ExCSS.AggregateSelectorList
        + public readonly string Delimiter
        + public virtual string ToString(Boolean friendlyFormat,Int32 indentation)
        + public void .ctor(String delimiter)
        - public virtual string ToString()
        - public string ToString(Boolean friendlyFormat,Int32 indentation)
        - public void .ctor()
    public class ExCSS.MultipleSelectorList
        + interface: ExCSS.IToString
        + public virtual string ToString(Boolean friendlyFormat,Int32 indentation)
        - public virtual string ToString()
        - public string ToString(Boolean friendlyFormat,Int32 indentation)
    public class ExCSS.StylesheetParseError
        + public void .ctor(ParserError error,String errorMessage,Int32 line,Int32 column)
        - public void set_Message(String value)
        - public void .ctor(ParserError error,Int32 line,Int32 column,String message)
    public class ExCSS.Parser
        - public ExCSS.StyleSheet Parse(Stream stylesheetStream)
    public class ExCSS.Term
        + public static readonly ExCSS.InheritTerm Inherit
        - protected string Text
        + protected void .ctor()
        - public static ExCSS.Term get_Inherit()
        - public ExCSS.RuleValueType get_RuleValueType()
        - public virtual string ToString()
        - public void .ctor()
    public class ExCSS.PrimitiveTerm
        + public void set_Value(Object value)
        + public void set_PrimitiveType(UnitType value)
        + public Nullable<float> GetFloatValue(UnitType unit)
        + public virtual string ToString()
        - public void .ctor(HtmlColor value)
    public class ExCSS.TermList
        + public void AddTerm(Term term)
        + public void AddSeparator(TermSeparator termSeparator)
        + public void .ctor(Term[] terms)
    public class ExCSS.StyleSheet
        + public List<RuleSet> get_Rules()
        + public ExCSS.StyleSheet RemoveRule(Int32 index)
        + public ExCSS.StyleSheet InsertRule(String rule,Int32 index)
        + public IList<StyleRule> get_StyleRules()
        + public IList<CharacterSetRule> get_CharsetDirectives()
        + public IList<ImportRule> get_ImportDirectives()
        + public IList<FontFaceRule> get_FontFaceDirectives()
        + public IList<KeyframesRule> get_KeyframeDirectives()
        + public IList<MediaRule> get_MediaDirectives()
        + public IList<PageRule> get_PageDirectives()
        + public IList<SupportsRule> get_SupportsDirectives()
        + public IList<NamespaceRule> get_NamespaceDirectives()
        + public string ToString(Boolean friendlyFormat,Int32 indentation)
        + public void .ctor()
        - public List<CharacterSetRule> get_CharsetDirectives()
        - public List<FontFaceRule> get_FontFaceDirectives()
        - public List<ImportRule> get_ImportDirectives()
        - public List<KeyframesRule> get_KeyframeDirectives()
        - public List<MediaRule> get_MediaDirectives()
        - public List<NamespaceRule> get_NamespaceDirectives()
        - public List<PageRule> get_PageDirectives()
        - public List<SupportsRule> get_SupportsDirectives()
        - public List<StyleRule> get_Rulesets()
        - public void set_Rulesets(List<StyleRule> value)
        - public string ToString(Boolean friendlyFormat)
    public struct ExCSS.CombinatorSelector
        + public ExCSS.BaseSelector Selector
        - public ExCSS.SimpleSelector Selector
        + public char get_Character()
        + public void .ctor(BaseSelector selector,Combinator delimiter)
        - public char get_Char()
        - public void .ctor(SimpleSelector selector,Combinator delimiter)
From 1 assemblies were 4 types removed and 26 changed.

ExCSS errs when trying to parse bootstrap.css.

Trying to parse bootstrap.css, and ExCSS errors with this:

p.Errors
Count = 3
[0]: "-- line 9 col 165: ")" expected"
[1]: "-- line 9 col 175: "{" expected"
[2]: ""

The first two errors are for this part from line 29 of the original bootstrap.css: "audio:not([controls]) {" .

Blank declarations

Blank declarations are failing to parse. (two semicolons with nothing of significance in between)

td.whatever {
color: white; ;
}

Iteration support in TermList

Any particular reason why TermList does not implement IEnumerable<Term> to support iteration? It has Count and an indexer. It would avoid writing error-prone for looping code each time.

@Media enclosed css

Parser is unable to deal with css enclosed within @media element. Example here: http://www.google.com/about/default.css

Google use '@media screen,projection{' to encapsulate all remaining css. This causes EXCSS to throw NotSupportedExceptions from the methods 'AddSeparator' and 'AddTerm' in TermList.cs

Is it possible to make it handle this by telling it to close curley braces before the next element?

Signed Nuget package?

It seems that the source has all the ability to be signed, but the Nuget package has not been updated with that change. Any chance in getting a Nuget package update?

Thanks!

Space in font names lost

A CSS like this:

body
{
font: normal 100% Frutiger, "Frutiger Linotype" , Univers, Calibri, "Gill Sans" , "Gill Sans MT" , "Myriad Pro" , Myriad, "DejaVu Sans Condensed" , "Liberation Sans" , "Nimbus Sans L" , Geneva, "Helvetica Neue" , Helvetica, Arial, sans-serif;
}

after parsed will have font names without spaces, like FrutigerLinotype.
What can I do? Thanks in advance!

@Keyframes Parsing Regression with 2.0.3

It appears that @Keyframes parsing might have broken after this checkin : 928a09a It's somewhat inconsistent, as some cases seem to work. Below are a few examples.

Specifying a list of keyframes with a browser prefix doesn't ToString() the results correctly, and specifying a list of keyframes without a browser prefix throws a Null Reference Exception.

    [Test] //Fails
    public void KeyFrames_ToString_Test()
    {
        var parser = new Parser();
        Assert.That(parser.Parse(@"@-webkit-keyframes ixp-bounce { 0%, 20%, 50%, 80%, 100% { transform: translateY(0);}}"), Is.StringContaining("transform"));
    }

    [Test] //Fails
    public void KeyFrames_Exception_Test()
    {
        var paser = new Parser();
        Assert.DoesNotThrow(() => paser.Parse(@"@keyframes ixp-bounce { 0%, 20%, 50%, 80%, 100% { -webkit-transform: translateY(0); } }"));
    }

    [Test] //Succeeds
    public void KeyFrames_Works_Test()
    {
        var paser = new Parser();
        StyleSheet result = null;
        Assert.DoesNotThrow(() =>
        {
            result = paser.Parse(@"@keyframes ixp-bounce { 100% { -webkit-transform: translateY(0); } }");
        });
        Assert.That(result.ToString(), Is.StringContaining("transform"));
        Console.WriteLine(result.ToString());
    }

I'd be willing to send up a pull request, it seems like ParseKeyframeText in Parser.Block will need a little work? Do you have any suggestions @TylerBrinks ?

Parsing inline styles

If an inline style string color: red; font-size: 2em could be parsed to IList<Property> it would be very helpful.

How to get CSS output as a string?

Hi, I'm using ExCSS to parse and manipulate a CSS string.

Once I've done all manipulations, how can I get all the object model hierarchy as a whole string again?

Also, is there a documentation link with available options?

Thank you!

IndexOutOfRange exception in StringExtensions.TrimFirstLine

System.IndexOutOfRangeException occurred
  StackTrace:
       at System.Text.StringBuilder.get_Chars(Int32 index)
       at ExCSS.Model.Extensions.StringExtensions.TrimFirstLine(StringBuilder builder)
       at ExCSS.StyleSheet.ToString(Boolean friendlyFormat, Int32 indentation)
       at ExCSS.StyleSheet.ToString()

public static StringBuilder TrimFirstLine(this StringBuilder builder)
        {
            if (builder.Length > 0) // this check must be moved to "while"
            {
                while (builder[0] == '\r' || builder[0] == '\n' || builder[0] == '\t')
                {
                    builder.Remove(0, 1);
                }
            }

            return builder;
        }

Nuget Package Incompatible with .NET 4

Project refuses to build when set to 4.0, even though it is referencing packages\ExCSS.2.0.6\lib\net40

"Indirect Reference" issues include System.Runtime, System.Collections, etc.
Changing to 4.5 resolves this

Parsing FontFaceDirectives/Rules yields NullRef

When parsing the .Src property from FontFaceDirectives of a parsed document, I get a NullRef exception when the font-face directive's 'local' directive is split across a line ending

/* The Following Font Face can be parsed and .Src examined properly */
@font-face {
font-family: 'Roboto'; font-style: italic; font-weight: 400; src:
local('Roboto Italic'), local('Roboto-Italic'),
url('https://fonts.gstatic.com/s/roboto/v15/W4wDsBUluyw0tK3tykhXEfesZW2xOQ-xsNqO47m55DA.ttf')
format('truetype');
}

/* The following Font Face's SRC cannot be parsed because the local('LatoLight') is split across two lines. */
@font-face {
font-family: 'Lato'; font-style: normal; font-weight: 300; src: local('Lato
Light'), local('Lato-Light'),
url('https://fonts.gstatic.com/s/lato/v11/nj47mAZe0mYUIySgfn0wpQ.ttf')
format('truetype');
}

Exception:

System.NullReferenceException : Object reference not set to an instance of an object. at ExCSS.StyleDeclaration.GetPropertyValue(String propertyName) at Core.Html.HtmlWebFont.<>c.<FindWebFontsInHtml>b__8_0(FontFaceRule n) in C:\dev\litmus\Core\Core\Html\HtmlWebFont.cs:line 49

Example code:

var css = HtmlCascadingStyleSheet.RetrieveCssFromHtmlDocument(html);
            var parser = new Parser();
            var stylesheet = parser.Parse(css);

            //get standalone font face directives and font-face directives inside @media blocks     
            var webFonts = stylesheet.FontFaceDirectives.Where(n => !string.IsNullOrEmpty(n.Src)).ToList();

Fails parsing bootstrap.css

I wanted to use ExCSS to parse bootstrap and add/edit class selectors in order to isolate CSS that will be inserted into a JS client-side widget.

Unfortunately the attached bootstrap.css file failed after/at:

audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}

No further Rulesets were parsed.

Example code:

    static void Main()
    {
        var parser = new ExCSS.ExCSS();
        string css = File.ReadAllText(@"..\bootstrap.css.txt");
        Stylesheet ss = parser.Parse(css);
        foreach (RuleSet rs in ss.RuleSets) {
            foreach (Selector rss in rs.Selectors){
                Console.WriteLine(rss.ToString());
            }
        }
        Console.ReadKey();

}

bootstrap.css.txt

Comments issue

It seems there is some kind of problem with comments on 2.0.2 right now. The CSS:

#sidebar { }
/*********************************************************************************/
/* Footer                                                                        */
/*********************************************************************************/

#footer {}

/*********************************************************************************/
/* Copyright                                                                     */
/*********************************************************************************/

#copyright {}

W3C CSS validator says its OK.

This test is failing:

        [Test]
        public void TestComments()
        {
            string comments = "#sidebar { }\r\n" +
                "/*********************************************************************************/\r\n" +
                "/* Footer                                                                        */\r\n" +
                "/*********************************************************************************/\r\n" +
                "\r\n" +
                "#footer {}\r\n" +
                "\r\n" +
                "/*********************************************************************************/\r\n" +
                "/* Copyright                                                                     */\r\n" +
                "/*********************************************************************************/\r\n" +
                "\r\n" +
                "#copyright {}\r\n";

            var stylesheet = new Parser().Parse(comments);
            Assert.AreEqual(0, stylesheet.Errors.Count);
        }

The error is "Expected comment to close before end of file."

Keep comments?

Is there any way to keep comments (in some cases those contain licenses that should not be removed?)

Misc CSS parsing/generation errors

Example:
background:rgba(0,0,0,0.5);
font-family:Georgia,serif;
box-shadow:3px 0 1px -1px #ddd,-3px 0 1px -1px #ddd;

Generated
background:#000000;
font-family:Georgia serif;
box-shadow:3px 0 1px -1px #DDDDDD -3px 0 1px -1px #DDDDDD;

In order:
Missing alpha value, should not convert from rgba into hex.
Missing comma.
Missing commas at group separation.

Update for NuGet?

Looks like your last push for this project to NuGet was on July 20, 2012. Since then it looks like you've moved to Antlr and maybe made some fixes. Are these changes still being evaluated or has the project been abandoned?

Incompatible with .NET 4.5.2

When the ExCSS library version 2.0.6 is referenced by .NET 4.5.2 assembly, it cannot be compiled. The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Update: It happens only in VS 2013. VS 2015 RC is not affected.

@Media enclosed terms

Parser is unable to deal with css enclosed within @media element. Example here: http://www.google.com/about/default.css

Google use '@media screen,projection{' to encapsulate all remaining css. This causes EXCSS to throw NotSupportedExceptions from the methods 'AddSeparator' and 'AddTerm' in TermList.cs

Is it possible to make it handle this?

InvalidOperationException using Microsoft gradients

code as below throws an exception in the parser. Pull request coming soon.

System.InvalidOperationException : Sequence contains no elements
   at System.Linq.Enumerable.Last(IEnumerable`1 source)
   at ExCSS.Parser.ParseValueFunction(Block token) in Parser.Blocks.cs: line 439
   at ExCSS.Parser.ParseTokenBlock(Block token) in Parser.Blocks.cs: line 107
   at ExCSS.Parser.Parse(String css) in Parser.cs: line 41
   at ExCSS.Tests.SelectorFixture.Parser_Reads_Multi_Microsoft_Filter_Fns() in SelectorFixture.cs: line 548
        [Test]
        public void Parser_Reads_Multi_Microsoft_Filter_Fns()
        {
            var css = @".test {
background: rgb(30,87,153); /* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUwJSIgc3RvcC1jb2xvcj0iIzI5ODlkOCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjUxJSIgc3RvcC1jb2xvcj0iIzIwN2NjYSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiM3ZGI5ZTgiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(top,  rgba(30,87,153,1) 0%, rgba(41,137,216,1) 50%, rgba(32,124,202,1) 51%, rgba(125,185,232,1) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(30,87,153,1)), color-stop(50%,rgba(41,137,216,1)), color-stop(51%,rgba(32,124,202,1)), color-stop(100%,rgba(125,185,232,1))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* IE10+ */
background: linear-gradient(to bottom,  rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-8 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#1e5799',endColorstr='#7db9e8',GradientType=0); /* IE6-8 */
}";
            var results = new Parser().Parse(css);
            Assert.That(results.Errors.Count == 0);
        }

Parser fails on inherit value

take this scenerio:

            var parser = new Parser();
            var css = parser.Parse(
@"div 
{
    font:inherit
}");

Parser will fail in FinalizeProperty because it tries to index into the _terms list when it didn't get populated properly because the value was applied directly to the _property's Term.
I will attempt to make a pull request and fix the issue.

Separate multiple rules

Take for example:
.ui-icon,
.ui-widget-content .ui-icon {
background-image: url("images/ui-icons_222222_256x240.png");
}

This is parsed as a single RuleSet object ".ui-icon, .ui-widget-content .ui-icon".

Is there a way to have the parser separate those each into its own RuleSet?

ArgumentOutOfRangeException

Test

string test = "html{color:#000;}";
new ExCSS.Parser().Parse(test);

Exception

System.ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
  at System.Collections.Generic.List`1[ExCSS.Term].get_Item (Int32 index) [0x00000] in <filename unknown>:0 
  at ExCSS.Parser.FinalizeProperty () [0x00073] in -ExCSS/ExCSS/Parser.cs:160 
  at ExCSS.Parser.ParsePostValue (ExCSS.Model.TextBlocks.Block token) [0x00010] in -ExCSS/ExCSS/Parser.Blocks.cs:491 
  at ExCSS.Parser.ParseSingleValue (ExCSS.Model.TextBlocks.Block token) [0x00190] in -ExCSS/ExCSS/Parser.Blocks.cs:403 
  at ExCSS.Parser.ParseHexValue (ExCSS.Model.TextBlocks.Block token) [0x00077] in -ExCSS/ExCSS/Parser.Blocks.cs:484 
  at ExCSS.Parser.ParseTokenBlock (ExCSS.Model.TextBlocks.Block token) [0x00212] in -ExCSS/ExCSS/Parser.Blocks.cs:102 
  at ExCSS.Parser.Parse (System.String css) [0x0007c] in -ExCSS/ExCSS/Parser.cs:40 

Adding a WriteLine(token); inside the Parser.Parse(css) method loop generated the following output up till the exception

html
{
color
:
#
00
;

In this method _terms.Count == 0

    private void FinalizeProperty()
    {
        if (_property != null)
        {
            if (_terms.Count > 1)
            {
                var termList = new TermList();
                _property.Term = termList;

                _terms.ForEach(t => termList.AddTerm(_termDelimiter, t));
            }
            else
            {
                _property.Term = _terms[0]; <--------------------ArgumentOutOfRange
            }
        }

        _terms.Clear();
        _termDelimiter = GrammarSegment.Whitespace;
        _property = null;
    }

Release an dll

Hi,

im working on ubuntu and i cant compile the source in monodevelop and there is no nuget. So could you upload the latest dll?

Create a .NET 3.5 version

It would be real useful to have a .NET 3.5 version of the project and of course a NuGet package supporting .NET 3.5.

Strong-signing of the assembly would also be useful, as it can then be used in strongly-signed projects.

.NET 3.5 version requires no changes: the project compiles and runs fine on .NET 3.5

HtmlColor does not support hsl or hsla

Hsla colors are not recognized as an html color. They are recognized as a generic function.

The following should be valid HtmlColor:

/* HSL model, added to CSS3 /
p { color: hsl(0, 100%, 50%) } /
red /
p { color: hsl(120, 100%, 50%) } /
green /
p { color: hsl(120, 100%, 25%) } /
dark green /
p { color: hsl(120, 100%, 75%) } /
light green /
p { color: hsl(120, 50%, 50%) } /
pastel green */

/* HSL model with alpha channel /
p { color: hsla(120, 100%, 50%, 1) } /
green /
p { color: hsla(120, 100%, 50%, 0.5) } /
semi-transparent green /
p { color: hsla(120, 100%, 50%, 0.1) } /
very transparent green */

Links to alternatives

I've ported CSS parser from Mozilla Firefox to C#. I've put links in the ReadMe to your project, as my parser supports all CSS features, but lacks modification, serialization etc., so the choice between your library and mine depends on the features needed.

It would be nice if you link back from your readme file too, as it may be useful for some people. Even when I add the missing features, the libraries are likely to remain quite different.

P.S. Any estimates about when the rewrite to Antlr will be finished?

Basic example needs updating

The basic example appears to no longer be working.
StylesheetParser is probably replaced by new Parser().Parse("...")

Further StyleSheet.Ruleset among other are marked internal which makes them unaccessible.
There appear to be no other way to access the rulesets, upon testing I found 29 items in Ruleset but only one ImportDirective and one MediaDirective publicly accessible.

Extracting Urls with v2

Hi,

I am currently using v1.1.0 to extract urls from css using this code:

    var parser = new StylesheetParser();
    var styleSheet = parser.Parse(cssText);
    var cssUrlTerms = styleSheet.RuleSets
        .SelectMany(r => r.Declarations)
        .SelectMany(d => d.Expression.Terms)
        .Where(t => t.Type == TermType.Url)
        .Union(
            styleSheet.Directives.SelectMany(d => d.RuleSets)
            .SelectMany(r => r.Declarations)
            .SelectMany(d => d.Expression.Terms)
            .Where(t => t.Type == TermType.Url)
        )
        .Distinct()
        .ToList();

I don't see a way to do something similar with v2, am I missing something?

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.