Skip to content
0.2.0-dev Download ZIP
309 lines ·13.0 KB Raw
1using System.Globalization;
2using AngleSharp.Dom;
3
4namespace EvilEngine.Html;
5
6public static class Defaults
7{
8 public const double MonospaceRatio = 12.0 / 16.0;
9 public static readonly Rgba ThreeDFace = new(233, 233, 237);
10
11 private static readonly HashSet<string> Hidden =
12 [
13 "head", "script", "style", "template", "title", "meta", "link", "base", "noscript", "area", "datalist",
14 "param", "rp", "source", "track", "col", "colgroup", "dialog", "option", "optgroup", "embed", "object",
15 "iframe", "video", "audio", "canvas", "svg", "math", "map"
16 ];
17
18 private static readonly HashSet<string> Blocks =
19 [
20 "html", "body", "address", "blockquote", "center", "div", "figure", "figcaption", "footer", "form", "header",
21 "hr", "legend", "listing", "main", "p", "plaintext", "pre", "search", "xmp", "article", "aside", "h1", "h2",
22 "h3", "h4", "h5", "h6", "hgroup", "nav", "section", "dir", "dd", "dl", "dt", "menu", "ol", "ul", "fieldset",
23 "details", "summary"
24 ];
25
26 private static readonly HashSet<string> Lists = ["dir", "menu", "ol", "ul"];
27 private static readonly HashSet<string> NestedListMargins = ["dir", "dl", "menu", "ol", "ul"];
28
29 private static readonly HashSet<string> Monospace =
30 ["code", "kbd", "samp", "tt", "pre", "listing", "plaintext", "xmp"];
31
32 private static readonly HashSet<string> Italic = ["address", "cite", "dfn", "em", "i", "var"];
33 private static readonly HashSet<string> Bold = ["b", "strong", "th"];
34
35 private static readonly HashSet<string> OneEmBlocks =
36 ["p", "dl", "dir", "menu", "ol", "ul", "pre", "listing", "plaintext", "xmp", "blockquote", "figure"];
37
38 public static ComputedStyle For(IElement element, ComputedStyle parent)
39 {
40 var name = element.LocalName;
41 var style = parent.Inherit();
42
43 if (Hidden.Contains(name) || element.HasAttribute("hidden"))
44 return style with { Display = Display.None };
45 if (name == "input" &&
46 string.Equals(element.GetAttribute("type"), "hidden", StringComparison.OrdinalIgnoreCase))
47 return style with { Display = Display.None };
48
49 if (Blocks.Contains(name))
50 style = style with { Display = Display.Block };
51 style = name switch
52 {
53 "li" => style with { Display = Display.ListItem },
54 "table" => style with { Display = Display.Table },
55 "caption" => style with { Display = Display.TableCaption },
56 "thead" => style with { Display = Display.TableHeaderGroup, VerticalAlign = VerticalAlign.Middle },
57 "tbody" => style with { Display = Display.TableRowGroup, VerticalAlign = VerticalAlign.Middle },
58 "tfoot" => style with { Display = Display.TableFooterGroup, VerticalAlign = VerticalAlign.Middle },
59 "tr" => style with
60 {
61 Display = Display.TableRow,
62 VerticalAlign = element.ParentElement?.LocalName == "table"
63 ? VerticalAlign.Middle
64 : parent.VerticalAlign
65 },
66 "td" or "th" => style with { Display = Display.TableCell, VerticalAlign = parent.VerticalAlign },
67 _ => style
68 };
69
70 style = Font(name, style, parent);
71 var em = style.FontSize;
72
73 if (OneEmBlocks.Contains(name))
74 style = style with { Margin = Edges.Vertical(em) };
75
76 style = name switch
77 {
78 "body" => style with { Margin = Edges.All(8) },
79 "h1" => style with { Margin = Edges.Vertical(0.67 * em) },
80 "h2" => style with { Margin = Edges.Vertical(0.83 * em) },
81 "h3" => style with { Margin = Edges.Vertical(1.0 * em) },
82 "h4" => style with { Margin = Edges.Vertical(1.33 * em) },
83 "h5" => style with { Margin = Edges.Vertical(1.67 * em) },
84 "h6" => style with { Margin = Edges.Vertical(2.33 * em) },
85 "blockquote" or "figure" => style with { Margin = new Edges(em, 40, em, 40) },
86 "dd" => style with { Margin = new Edges(0, 0, 0, 40) },
87 "fieldset" => style with
88 {
89 Margin = new Edges(0, 2, 0, 2),
90 Padding = new Edges(0.35 * em, 0.75 * em, 0.625 * em, 0.75 * em),
91 Border = Edges.All(2),
92 BorderStyle = BorderStyle.Groove,
93 BorderColor = ThreeDFace
94 },
95 "legend" => style with { Padding = new Edges(0, 2, 0, 2) },
96 "hr" => style with
97 {
98 Margin = Edges.Vertical(0.5 * em),
99 Border = Edges.All(1),
100 BorderStyle = BorderStyle.Inset,
101 BorderColor = Rgba.Gray
102 },
103 "center" or "caption" => style with { TextAlign = TextAlign.Center },
104 "th" when parent.TextAlign == TextAlign.Start => style with { TextAlign = TextAlign.Center },
105 "pre" or "listing" or "plaintext" or "xmp" => style with { WhiteSpace = WhiteSpace.Pre },
106 "nobr" => style with { WhiteSpace = WhiteSpace.NoWrap },
107 "u" or "ins" => style with { Decoration = style.Decoration | Decoration.Underline },
108 "s" or "strike" or "del" => style with { Decoration = style.Decoration | Decoration.LineThrough },
109 "mark" => style with { Background = Rgba.Yellow, Color = Rgba.Black },
110 "sub" => style with { VerticalAlign = VerticalAlign.Sub },
111 "sup" => style with { VerticalAlign = VerticalAlign.Super },
112 _ => style
113 };
114
115 if (name == "summary" && element.ParentElement is { LocalName: "details" } details
116 && details.Children.FirstOrDefault(child => child.LocalName == "summary") == element)
117 style = style with
118 {
119 ListStyle = details.HasAttribute("open") ? ListStyle.DisclosureOpen : ListStyle.DisclosureClosed
120 };
121
122 if (name is "a" or "area" && element.HasAttribute("href"))
123 style = style with { Color = Rgba.Link, Decoration = style.Decoration | Decoration.Underline };
124
125 if (Lists.Contains(name))
126 style = style with
127 {
128 Padding = new Edges(0, 0, 0, 40),
129 ListStyle = name == "ol" ? ListStyle.Decimal : ListDepthStyle(element)
130 };
131 if (NestedListMargins.Contains(name) && HasListAncestor(element))
132 style = style with { Margin = style.Margin with { Top = 0, Bottom = 0 } };
133 if (name is "ol" or "ul" or "li" && ListType(element.GetAttribute("type")) is { } type)
134 style = style with { ListStyle = type };
135
136 if (name is "p" or "div" or "h1" or "h2" or "h3" or "h4" or "h5" or "h6" or "caption"
137 && Align(element.GetAttribute("align")) is { } align)
138 style = style with { TextAlign = align };
139 if (name is "td" or "th" && element.HasAttribute("nowrap"))
140 style = style with { WhiteSpace = WhiteSpace.NoWrap };
141
142 return name switch
143 {
144 "table" => Table(element, style),
145 "td" or "th" => Cell(element, style),
146 "tr" or "thead" or "tbody" or "tfoot" => Aligned(element, style),
147 _ => style
148 };
149 }
150
151 private static ComputedStyle Table(IElement table, ComputedStyle style)
152 {
153 style = style with
154 {
155 BorderSpacing = ParseInteger(table.GetAttribute("cellspacing")) ?? 2,
156 Width = ParseDimension(table.GetAttribute("width")),
157 CenteredByMargins = string.Equals(table.GetAttribute("align")?.Trim(), "center",
158 StringComparison.OrdinalIgnoreCase)
159 };
160 if (table.GetAttribute("border") is { } border)
161 style = style with { Border = Edges.All(ParseInteger(border) ?? 1), BorderStyle = BorderStyle.Outset };
162 return style;
163 }
164
165 private static ComputedStyle Cell(IElement cell, ComputedStyle style)
166 {
167 var table = cell.Closest("table");
168 style = Aligned(cell, style with
169 {
170 Padding = Edges.All(ParseInteger(table?.GetAttribute("cellpadding")) ?? 1),
171 Width = ParseDimension(cell.GetAttribute("width")),
172 Height = ParseDimension(cell.GetAttribute("height"))
173 });
174 if (table?.GetAttribute("border") is { } border && ParseInteger(border) != 0)
175 style = style with { Border = Edges.All(1), BorderStyle = BorderStyle.Inset };
176 return style;
177 }
178
179 private static ComputedStyle Aligned(IElement element, ComputedStyle style)
180 {
181 if (Align(element.GetAttribute("align")) is { } align)
182 style = style with { TextAlign = align };
183 return element.GetAttribute("valign")?.Trim().ToLowerInvariant() switch
184 {
185 "top" => style with { VerticalAlign = VerticalAlign.Top },
186 "middle" or "center" => style with { VerticalAlign = VerticalAlign.Middle },
187 "bottom" => style with { VerticalAlign = VerticalAlign.Bottom },
188 "baseline" => style with { VerticalAlign = VerticalAlign.Baseline },
189 _ => style
190 };
191 }
192
193 public static int? ParseInteger(string? value)
194 {
195 if (value == null)
196 return null;
197 var i = 0;
198 while (i < value.Length && value[i] is ' ' or '\t' or '\n' or '\f' or '\r')
199 i++;
200 if (i < value.Length && value[i] == '+')
201 i++;
202 var start = i;
203 long number = 0;
204 for (; i < value.Length && char.IsAsciiDigit(value[i]); i++)
205 number = Math.Min(number * 10 + (value[i] - '0'), int.MaxValue);
206 return i == start ? null : (int)number;
207 }
208
209 public static Length? ParseDimension(string? value)
210 {
211 if (value == null)
212 return null;
213 var i = 0;
214 while (i < value.Length && value[i] is ' ' or '\t' or '\n' or '\f' or '\r')
215 i++;
216 var start = i;
217 while (i < value.Length && char.IsAsciiDigit(value[i]))
218 i++;
219 if (i == start)
220 return null;
221 var end = i;
222 if (i < value.Length && value[i] == '.')
223 {
224 i++;
225 while (i < value.Length && char.IsAsciiDigit(value[i]))
226 i++;
227 if (i > end + 1)
228 end = i;
229 }
230
231 var number = double.Parse(value[start..end], CultureInfo.InvariantCulture);
232 if (number == 0)
233 return null;
234 return new Length(number, end < value.Length && value[end..].TrimStart('.').StartsWith('%'));
235 }
236
237 private static ComputedStyle Font(string name, ComputedStyle style, ComputedStyle parent)
238 {
239 var size = parent.FontSize;
240 style = name switch
241 {
242 "h1" => style with { FontSize = size * 2, Bold = true },
243 "h2" => style with { FontSize = size * 1.5, Bold = true },
244 "h3" => style with { FontSize = size * 1.17, Bold = true },
245 "h4" => style with { FontSize = size, Bold = true },
246 "h5" => style with { FontSize = size * 0.83, Bold = true },
247 "h6" => style with { FontSize = size * 0.67, Bold = true },
248 "big" => style with { FontSize = size * 1.2 },
249 "small" or "sub" or "sup" => style with { FontSize = size / 1.2 },
250 _ => style
251 };
252 if (Bold.Contains(name))
253 style = style with { Bold = true };
254 if (Italic.Contains(name))
255 style = style with { Italic = true };
256 if (Monospace.Contains(name) && style.Family != GenericFamily.Monospace)
257 style = style with { Family = GenericFamily.Monospace, FontSize = style.FontSize * MonospaceRatio };
258 return style;
259 }
260
261 private static bool HasListAncestor(IElement element)
262 {
263 for (var parent = element.ParentElement; parent != null; parent = parent.ParentElement)
264 if (Lists.Contains(parent.LocalName))
265 return true;
266 return false;
267 }
268
269 private static ListStyle ListDepthStyle(IElement element)
270 {
271 var depth = 0;
272 for (var parent = element.ParentElement; parent != null; parent = parent.ParentElement)
273 if (Lists.Contains(parent.LocalName))
274 depth++;
275 return depth switch { 0 => ListStyle.Disc, 1 => ListStyle.Circle, _ => ListStyle.Square };
276 }
277
278 private static ListStyle? ListType(string? type)
279 {
280 return type switch
281 {
282 null => null,
283 "1" => ListStyle.Decimal,
284 "a" => ListStyle.LowerAlpha,
285 "A" => ListStyle.UpperAlpha,
286 "i" => ListStyle.LowerRoman,
287 "I" => ListStyle.UpperRoman,
288 _ => type.ToLowerInvariant() switch
289 {
290 "disc" => ListStyle.Disc,
291 "circle" => ListStyle.Circle,
292 "square" => ListStyle.Square,
293 "none" => ListStyle.None,
294 _ => null
295 }
296 };
297 }
298
299 private static TextAlign? Align(string? align)
300 {
301 return align?.ToLowerInvariant() switch
302 {
303 "left" or "justify" => TextAlign.Start,
304 "center" or "middle" => TextAlign.Center,
305 "right" => TextAlign.Right,
306 _ => null
307 };
308 }
309}