lisurc
Having the library parse color values such as "red" or "green" to convert them to CssColor objects would be nice. Version 1.0.0.3 does not seem to support this. I think the System.Drawing.Color methods could be used to achieve this.
#2 · closed · 4 comments
Having the library parse color values such as "red" or "green" to convert them to CssColor objects would be nice. Version 1.0.0.3 does not seem to support this. I think the System.Drawing.Color methods could be used to achieve this.
I want to preserve compatibility with results from Fixrefox's parser, so the `Color` property will remain as is. However, to simplify operations with named colors, I've added `CalculatedColor` property. You can also use new overloads of `CssColor` factory methods. ``` cs [TestMethod] public void ParseSheet_Simple_ColorName () { var loader = new CssLoader(); var css = loader.ParseSheet("h1 { color: red; }", SheetUri, BaseUri); var h1 = css.StyleRules.Single(); var h1color = h1.Declaration.Data.Single(); Assert.AreEqual(CssProperty.Color, h1color.Property); Assert.AreEqual(CssColor.RGB(0xFF, 0x00, 0x00), h1color.Value.CalculatedColor); Assert.AreEqual(CssColor.RGB(0xFF, 0x00, 0x00), CssColor.ColorNameToRGB(h1color.Value.String)); } ``` Note that `CssColor.EnumColor` values (`"inactivecaptiontext"`, `"-moz-dialog"` etc.) will not be converted. See https://github.com/Athari/CsCss/releases/tag/v1.0.1.0
Renamed `CssValue.CalculatedColor` to `ComputedColor` (to use usual CSS terminology).
Thanks for your updates. With your addition of <code>CssColor.ColorNameToRGB</code> I've actually added some extension methods to my code base on <code>CssDeclaration</code> to ease <code>CssColor</code> value retrieval and conversion for other color properties (BackgroundColor, BorderColor, etc.). ``` csharp public static Nullable<CssColor> GetComputedColor(this CssDeclaration decl, CssProperty property) { CssValue value = decl.GetValue(property); if (value != null) { if (value.Unit == CssUnit.Color) { return value.Color; } if (value.Unit == CssUnit.String) { return CssColor.ColorNameToRGB(value.String); } } return null; } public static int ToArgb(this CssColor color) { return (color.A << 24) | (color.R << 16) | (color.G << 8) | color.B; } ``` Not sure that fits the spirit of the code base but that came being quite handy for me.
The first method moves `CssValue` property one level lower. In the library, it would only be meaningful if applied to all properties, but that would cause too much noise. Besides, I don't see much difference between the first two lines: ``` cs decl.GetComputedColor(CssProperty.Color); decl.GetValue(CssProperty.Color).ComputedColor; // 6 characters more decl.Color.ComputedColor; // if property is known at compile time ``` The second method is application-specific, as byte order varies between graphics libraries (RGB and BGR are both common).