parseColor function

LatexColor? parseColor(
  1. String text
)

Parses a colour written as a name, #rgb, #rrggbb, #rrggbbaa, or bare rrggbb hex (KaTeX accepts this). Returns null if text is not a colour.

Implementation

LatexColor? parseColor(String text) {
  final t = text.trim();
  final named = namedColors[t.toLowerCase()];
  if (named != null) return LatexColor(0xFF000000 | named);
  final hex = t.startsWith('#') ? t.substring(1) : t;
  if (!RegExp(r'^[0-9a-fA-F]+$').hasMatch(hex)) return null;
  switch (hex.length) {
    case 3:
      final r = int.parse(hex[0] * 2, radix: 16);
      final g = int.parse(hex[1] * 2, radix: 16);
      final b = int.parse(hex[2] * 2, radix: 16);
      return LatexColor.fromARGB(0xFF, r, g, b);
    case 6:
      return LatexColor(0xFF000000 | int.parse(hex, radix: 16));
    case 8:
      final v = int.parse(hex, radix: 16);
      return LatexColor(((v & 0xFF) << 24) | (v >> 8));
  }
  return null;
}