CssMedium
Represents a medium rule. More information available at:
http://www.w3.org/TR/css3-mediaqueries/
using AngleSharp.Css;
using AngleSharp.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
namespace AngleSharp.Dom.Css
{
internal sealed class CssMedium : IEnumerable<MediaFeature>, IEnumerable
{
private static readonly string[] Types = new string[4] {
Keywords.Screen,
Keywords.Speech,
Keywords.Print,
Keywords.All
};
private readonly List<MediaFeature> _features;
public string Type { get; set; }
public bool IsExclusive { get; set; }
public bool IsInverse { get; set; }
public string Constraints {
get {
string[] array = new string[_features.Count];
for (int i = 0; i < _features.Count; i++) {
array[i] = _features[i].CssText;
}
return string.Join(" and ", array);
}
}
public string CssText {
get {
string constraints = Constraints;
string str = IsExclusive ? "only " : (IsInverse ? "not " : string.Empty);
if (string.IsNullOrEmpty(constraints))
return str + (Type ?? string.Empty);
if (string.IsNullOrEmpty(Type))
return str + constraints;
return str + Type + " and " + constraints;
}
}
internal CssMedium()
{
_features = new List<MediaFeature>();
}
public bool Validate(RenderDevice device)
{
if (!string.IsNullOrEmpty(Type) && Types.Contains(Type, StringComparison.Ordinal) == IsInverse)
return false;
if (IsInvalid(device, Keywords.Screen, RenderDevice.Kind.Screen) || IsInvalid(device, Keywords.Speech, RenderDevice.Kind.Speech) || IsInvalid(device, Keywords.Print, RenderDevice.Kind.Printer))
return false;
foreach (MediaFeature feature in _features) {
if (feature.Validate(device) == IsInverse)
return false;
}
return true;
}
public IEnumerator<MediaFeature> GetEnumerator()
{
return _features.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal bool AddConstraint(string name, ICssValue value = null)
{
MediaFeature mediaFeature = Factory.MediaFeatures.Create(name);
if (mediaFeature == null || !mediaFeature.TrySetValue(value))
return false;
_features.Add(mediaFeature);
return true;
}
private bool IsInvalid(RenderDevice device, string keyword, RenderDevice.Kind kind)
{
if (Type == keyword)
return device.DeviceType == kind == IsInverse;
return false;
}
}
}