CSSStyleDeclaration
Represents a single CSS declaration block.
using AngleSharp.Css;
using AngleSharp.DOM.Css;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace AngleSharp.DOM.Collections
{
[DOM("CSSStyleDeclaration")]
public sealed class CSSStyleDeclaration : IEnumerable<CSSProperty>, IEnumerable
{
private List<CSSProperty> _rules;
private CSSRule _parent;
private Func<string> _getter;
private Action<string> _setter;
private bool _blocking;
[DOM("cssText")]
public string CssText {
get {
return _getter();
}
set {
Update(value);
_setter(value);
}
}
[DOM("length")]
public int Length {
get {
return _rules.Count;
}
}
[DOM("parentRule")]
public CSSRule ParentRule {
get {
return _parent;
}
internal set {
_parent = value;
}
}
[DOM("item")]
public string this[int index] {
get {
if (index < 0 || index >= Length)
return null;
return _rules[index].Name;
}
}
internal List<CSSProperty> List => _rules;
internal CSSStyleDeclaration()
{
string text = string.Empty;
_getter = (() => text);
_setter = delegate(string value) {
text = value;
};
_rules = new List<CSSProperty>();
}
internal CSSStyleDeclaration(Element host)
{
Func<string> func = _getter = (() => host.GetAttribute("style"));
_setter = delegate(string value) {
host.SetAttribute("style", value);
};
_rules = new List<CSSProperty>();
}
[DOM("removeProperty")]
public string RemoveProperty(string propertyName)
{
for (int i = 0; i < _rules.Count; i++) {
if (_rules[i].Name.Equals(propertyName)) {
CSSValue value = _rules[i].Value;
_rules.RemoveAt(i);
Propagate();
return value.CssText;
}
}
return null;
}
[DOM("getPropertyPriority")]
public string GetPropertyPriority(string propertyName)
{
for (int i = 0; i < _rules.Count; i++) {
if (_rules[i].Name.Equals(propertyName)) {
if (!_rules[i].Important)
return null;
return "important";
}
}
return null;
}
[DOM("getPropertyValue")]
public string GetPropertyValue(string propertyName)
{
for (int i = 0; i < _rules.Count; i++) {
if (_rules[i].Name.Equals(propertyName))
return _rules[i].Value.CssText;
}
return null;
}
[DOM("setProperty")]
public CSSStyleDeclaration SetProperty(string propertyName, string propertyValue)
{
Propagate();
return this;
}
internal void Update(string value)
{
if (!_blocking) {
List<CSSProperty> rules = CssParser.ParseDeclarations(value ?? string.Empty, false)._rules;
_rules.Clear();
_rules.AddRange(rules);
}
}
private void Propagate()
{
_blocking = true;
_setter(ToCss());
_blocking = false;
}
public string ToCss()
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < _rules.Count; i++) {
stringBuilder.Append(_rules[i].ToCss()).Append(';');
}
return stringBuilder.ToString();
}
public IEnumerator<CSSProperty> GetEnumerator()
{
return _rules.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_rules).GetEnumerator();
}
}
}