enforceMinimumContrast static method

Color enforceMinimumContrast(
  1. Color fg,
  2. Color bg, {
  3. required double minRatio,
  4. bool hasExplicitBackground = false,
})

Adjusts fg lightness in OKLab until contrast against bg meets minRatio (1.0..21.0), preserving hue as much as the sRGB gamut allows.

When hasExplicitBackground is true, intentional fg == bg spoiler cells are preserved unchanged. When false, ANSI foregrounds that collide with the default theme background are adjusted to meet minRatio.

Implementation

static Color enforceMinimumContrast(
  Color fg,
  Color bg, {
  required double minRatio,
  bool hasExplicitBackground = false,
}) {
  if (minRatio <= 1.0) return fg;
  if (hasExplicitBackground && fg.r == bg.r && fg.g == bg.g && fg.b == bg.b) {
    return fg;
  }
  if (contrastRatio(fg, bg) >= minRatio) return fg;

  final goLighter =
      contrastRatio(Colors.white, bg) >= contrastRatio(Colors.black, bg);
  final (initialPassL, fallback) = goLighter
      ? (1.0, Colors.white)
      : (0.0, Colors.black);
  final (startL, a, b) = _srgbToOklab(fg);
  var failL = startL;
  var passL = initialPassL;
  var best = fallback;

  for (var i = 0; i < 10; i++) {
    final mid = (failL + passL) * 0.5;
    final candidate = _oklabToSrgb(mid, a, b);
    if (contrastRatio(candidate, bg) >= minRatio) {
      best = candidate;
      passL = mid;
    } else {
      failL = mid;
    }
  }
  return best;
}