Skip to content
0.2.0-dev Download ZIP
541 lines ·16.4 KB Raw
1using System.Text;
2
3namespace EvilEngine.Tailwind;
4
5public enum SelectorKind
6{
7 List,
8 Combinator,
9 Complex,
10 Compound,
11 Selector,
12 Function,
13 Value
14}
15
16public sealed class SelectorNode : ITreeNode<SelectorNode>
17{
18 public SelectorNode(SelectorKind kind, string value, List<SelectorNode>? nodes = null)
19 {
20 Kind = kind;
21 Value = value;
22 Nodes = nodes ?? [];
23 }
24
25 public SelectorKind Kind { get; set; }
26 public string Value { get; set; }
27 public List<SelectorNode> Nodes { get; set; }
28
29 public bool HasNodes =>
30 Kind is SelectorKind.List or SelectorKind.Complex or SelectorKind.Compound or SelectorKind.Function;
31
32 public List<SelectorNode>? Children => HasNodes ? Nodes : null;
33
34 public SelectorNode Clone()
35 {
36 return Kind switch
37 {
38 SelectorKind.Combinator or SelectorKind.Selector or SelectorKind.Value => new SelectorNode(Kind, Value),
39 SelectorKind.Complex or SelectorKind.Compound or SelectorKind.List => new SelectorNode(Kind, "",
40 Nodes.Select(n => n.Clone()).ToList()),
41 _ => new SelectorNode(Kind, Value, Nodes.Select(n => n.Clone()).ToList())
42 };
43 }
44
45 public override string ToString()
46 {
47 return SelectorParser.ToCss([this]);
48 }
49}
50
51public static class SelectorParser
52{
53 private const char Backslash = '\\';
54 private const char CloseBracket = ']';
55 private const char CloseParen = ')';
56 private const char Colon = ':';
57 private const char Comma = ',';
58 private const char DoubleQuote = '"';
59 private const char Dot = '.';
60 private const char GreaterThan = '>';
61 private const char Newline = '\n';
62 private const char Hash = '#';
63 private const char OpenBracket = '[';
64 private const char OpenParen = '(';
65 private const char Plus = '+';
66 private const char SingleQuote = '\'';
67 private const char Space = ' ';
68 private const char Tab = '\t';
69 private const char Tilde = '~';
70 private const char Ampersand = '&';
71 private const char Asterisk = '*';
72
73 public static SelectorNode Combinator(string value)
74 {
75 return new SelectorNode(SelectorKind.Combinator, value);
76 }
77
78 public static SelectorNode Complex(List<SelectorNode> nodes)
79 {
80 return new SelectorNode(SelectorKind.Complex, "", nodes);
81 }
82
83 public static SelectorNode Compound(List<SelectorNode> nodes)
84 {
85 return new SelectorNode(SelectorKind.Compound, "", nodes);
86 }
87
88 public static SelectorNode Fun(string value, List<SelectorNode> nodes)
89 {
90 return new SelectorNode(SelectorKind.Function, value, nodes);
91 }
92
93 public static SelectorNode List(List<SelectorNode> nodes)
94 {
95 return new SelectorNode(SelectorKind.List, "", nodes);
96 }
97
98 public static SelectorNode Selector(string value)
99 {
100 return new SelectorNode(SelectorKind.Selector, value);
101 }
102
103 public static SelectorNode ValueOf(string value)
104 {
105 return new SelectorNode(SelectorKind.Value, value);
106 }
107
108 private static int FirstChar(string value)
109 {
110 return value.Length > 0 ? value[0] : -1;
111 }
112
113 public static bool IsUniversalSelector(SelectorNode node)
114 {
115 return node.Kind == SelectorKind.Selector && FirstChar(node.Value) == Asterisk;
116 }
117
118 public static bool IsNestingSelector(SelectorNode node)
119 {
120 return node.Kind == SelectorKind.Selector && FirstChar(node.Value) == Ampersand;
121 }
122
123 public static bool IsClassSelector(SelectorNode node)
124 {
125 return node.Kind == SelectorKind.Selector && FirstChar(node.Value) == Dot;
126 }
127
128 public static bool IsIdSelector(SelectorNode node)
129 {
130 return node.Kind == SelectorKind.Selector && FirstChar(node.Value) == Hash;
131 }
132
133 public static bool IsPseudoSelector(SelectorNode node)
134 {
135 return node.Kind == SelectorKind.Selector && FirstChar(node.Value) == Colon;
136 }
137
138 public static bool IsAttributeSelector(SelectorNode node)
139 {
140 return node.Kind == SelectorKind.Selector && FirstChar(node.Value) == OpenBracket;
141 }
142
143 public static bool IsTypeSelector(SelectorNode node)
144 {
145 if (node.Kind != SelectorKind.Selector) return false;
146
147 switch (FirstChar(node.Value))
148 {
149 case Asterisk:
150 case Ampersand:
151 case Dot:
152 case Hash:
153 case Colon:
154 case OpenBracket:
155 return false;
156 default:
157 return true;
158 }
159 }
160
161 public static SelectorNode CloneAstNode(SelectorNode node)
162 {
163 return node.Clone();
164 }
165
166 public static string ToCss(List<SelectorNode> ast, bool minify = false)
167 {
168 var css = new StringBuilder();
169 foreach (var node in ast)
170 switch (node.Kind)
171 {
172 case SelectorKind.Selector:
173 case SelectorKind.Value:
174 css.Append(node.Value);
175 break;
176 case SelectorKind.Combinator:
177 if (minify || node.Value == " ")
178 css.Append(node.Value);
179 else
180 css.Append(' ').Append(node.Value).Append(' ');
181 break;
182 case SelectorKind.Function:
183 css.Append(node.Value).Append('(').Append(ToCss(node.Nodes, minify)).Append(')');
184 break;
185 case SelectorKind.Complex:
186 case SelectorKind.Compound:
187 css.Append(ToCss(node.Nodes, minify));
188 break;
189 case SelectorKind.List:
190 css.Append(string.Join(minify ? "," : ", ", node.Nodes.Select(n => ToCss([n], minify))));
191 break;
192 }
193
194 return css.ToString();
195 }
196
197 private static string Slice(string s, int start, int end)
198 {
199 if (start < 0) start = Math.Max(s.Length + start, 0);
200 if (end < 0) end = Math.Max(s.Length + end, 0);
201 start = Math.Min(start, s.Length);
202 end = Math.Min(end, s.Length);
203 return end > start ? s[start..end] : "";
204 }
205
206 private static string CharAt(string input, int i)
207 {
208 return i >= 0 && i < input.Length ? input[i].ToString() : "undefined";
209 }
210
211 public static List<SelectorNode> Parse(string input)
212 {
213 input = input.Replace("\r\n", "\n");
214
215 var ast = new List<SelectorNode>();
216 var target = ast;
217 var containsCombinator = false;
218 var contextStack = new Stack<(List<SelectorNode> Target, SelectorNode? CurrentList, bool ContainsCombinator)>();
219 SelectorNode? currentList = null;
220 var buffer = "";
221 int peekChar;
222
223 SelectorNode Current(List<SelectorNode>? nodes = null)
224 {
225 nodes ??= target;
226 return nodes.Count == 1 ? nodes[0] : containsCombinator ? Complex(nodes) : Compound(nodes);
227 }
228
229 void Append(SelectorNode node)
230 {
231 var existing = target.Count > 0 ? target[^1] : null;
232
233 if (existing?.Kind == SelectorKind.Compound)
234 existing.Nodes.Add(node);
235 else if (existing != null && existing.Kind != SelectorKind.List && existing.Kind != SelectorKind.Combinator)
236 target[^1] = Compound([existing, node]);
237 else
238 target.Add(node);
239 }
240
241 for (var i = 0; i < input.Length; i++)
242 {
243 var currentChar = input[i];
244
245 switch (currentChar)
246 {
247 case Comma:
248 {
249 if (buffer.Length > 0)
250 {
251 Append(Selector(buffer));
252 buffer = "";
253 }
254
255 for (; i + 1 < input.Length; i++)
256 {
257 peekChar = input[i + 1];
258 if (peekChar != Newline && peekChar != Space && peekChar != Tab)
259 break;
260 }
261
262 if (currentList != null)
263 {
264 currentList.Nodes.Add(Current());
265 target = [];
266 containsCombinator = false;
267 }
268 else
269 {
270 var nodes = target.ToList();
271 target.Clear();
272 var item = Current(nodes);
273 var node = List([item]);
274 target.Add(node);
275 currentList = node;
276 target = [];
277 containsCombinator = false;
278 }
279
280 break;
281 }
282
283 case GreaterThan:
284 case Newline:
285 case Space:
286 case Plus:
287 case Tab:
288 case Tilde:
289 {
290 if (buffer.Length > 0)
291 {
292 Append(Selector(buffer));
293 buffer = "";
294 }
295
296 var start = i;
297 var end = i + 1;
298 for (; end < input.Length; end++)
299 {
300 peekChar = input[end];
301 if (peekChar != GreaterThan && peekChar != Newline && peekChar != Space &&
302 peekChar != Plus && peekChar != Tab && peekChar != Tilde)
303 break;
304 }
305
306 i = end - 1;
307
308 var value = input[start..end].Trim();
309 if (value == "" && (target.Count == 0 || end >= input.Length || input[end] == Comma))
310 break;
311
312 target.Add(Combinator(value == "" ? " " : value));
313 containsCombinator = true;
314
315 break;
316 }
317
318 case OpenParen:
319 {
320 var node = Fun(buffer, []);
321 buffer = "";
322
323 if (node.Value != ":not" && node.Value != ":where" && node.Value != ":has" && node.Value != ":is")
324 {
325 var start = i + 1;
326 var nesting = 0;
327
328 for (var j = i + 1; j < input.Length; j++)
329 {
330 peekChar = input[j];
331 if (peekChar == OpenParen)
332 {
333 nesting++;
334 continue;
335 }
336
337 if (peekChar == CloseParen)
338 {
339 if (nesting == 0)
340 {
341 i = j;
342 break;
343 }
344
345 nesting--;
346 }
347 }
348
349 var end = i;
350
351 var contents = Slice(input, start, end);
352
353 if (node.Value == ":nth-child" || node.Value == ":nth-last-child")
354 {
355 var idx = contents.IndexOf("of ", StringComparison.Ordinal);
356 if (idx != -1)
357 {
358 node.Nodes.Add(ValueOf(contents[..(idx + 3)]));
359 node.Nodes.AddRange(Parse(contents[(idx + 3)..]));
360 buffer = "";
361 i = end;
362
363 Append(node);
364
365 break;
366 }
367 }
368
369 node.Nodes.Add(ValueOf(contents));
370 buffer = "";
371 i = end;
372
373 Append(node);
374
375 break;
376 }
377
378 Append(node);
379 contextStack.Push((target, currentList, containsCombinator));
380 target = node.Nodes;
381 containsCombinator = false;
382 currentList = null;
383
384 break;
385 }
386
387 case CloseParen:
388 {
389 if (buffer.Length > 0)
390 {
391 Append(Selector(buffer));
392 buffer = "";
393 }
394
395 if (currentList != null)
396 {
397 currentList.Nodes.Add(Current());
398 }
399 else if (containsCombinator)
400 {
401 var all = target.ToList();
402 target.Clear();
403 target.Add(Complex(all));
404 }
405
406 if (contextStack.TryPop(out var context))
407 {
408 target = context.Target;
409 currentList = context.CurrentList;
410 containsCombinator = context.ContainsCombinator;
411 }
412 else
413 {
414 target = ast;
415 currentList = null;
416 containsCombinator = false;
417 }
418
419 break;
420 }
421
422 case Dot:
423 case Colon:
424 case Hash:
425 {
426 if (currentChar == Colon && buffer == ":")
427 {
428 buffer += input[i];
429 break;
430 }
431
432 if (buffer.Length > 0)
433 Append(Selector(buffer));
434 buffer = input[i].ToString();
435 break;
436 }
437
438 case OpenBracket:
439 {
440 if (buffer.Length > 0)
441 {
442 Append(Selector(buffer));
443 buffer = "";
444 }
445
446 var start = i;
447 var nesting = 0;
448
449 for (var j = i + 1; j < input.Length; j++)
450 {
451 peekChar = input[j];
452 if (peekChar == OpenBracket)
453 {
454 nesting++;
455 continue;
456 }
457
458 if (peekChar == CloseBracket)
459 {
460 if (nesting == 0)
461 {
462 i = j;
463 break;
464 }
465
466 nesting--;
467 }
468 }
469
470 Append(Selector(Slice(input, start, i + 1)));
471 break;
472 }
473
474 case SingleQuote:
475 case DoubleQuote:
476 {
477 var start = i;
478
479 for (var j = i + 1; j < input.Length; j++)
480 {
481 peekChar = input[j];
482 if (peekChar == Backslash)
483 {
484 j += 1;
485 }
486 else if (peekChar == currentChar)
487 {
488 i = j;
489 break;
490 }
491 }
492
493 buffer += Slice(input, start, i + 1);
494 break;
495 }
496
497 case Ampersand:
498 case Asterisk:
499 {
500 if (buffer.Length > 0)
501 {
502 Append(Selector(buffer));
503 buffer = "";
504 }
505
506 Append(Selector(input[i].ToString()));
507 break;
508 }
509
510 case Backslash:
511 {
512 buffer += input[i] + CharAt(input, i + 1);
513 i += 1;
514 break;
515 }
516
517 default:
518 {
519 buffer += input[i];
520 break;
521 }
522 }
523 }
524
525 if (buffer.Length > 0)
526 Append(Selector(buffer));
527
528 if (currentList != null)
529 {
530 currentList.Nodes.Add(Current());
531 }
532 else if (containsCombinator)
533 {
534 var all = target.ToList();
535 target.Clear();
536 target.Add(Complex(all));
537 }
538
539 return ast;
540 }
541}