hover method

Color hover(
  1. Color color
)

Generates a hovered variant of the given color by darkening light colors and lighting dark colors based on their HSL lightness.

Colors at the extremes (very light or very dark) will be adjusted more aggressively than colors in the middle.

The lightening and darkening are controlled by hoverLighten and hoverDarken.

Implementation

Color hover(Color color) {
  // This results in a slight precision loss when using Display P3 colors, but it's negligible for hover effects.
  final hsl = HSLColor.fromColor(color);
  final l = hsl.lightness;

  // More aggressive color change when lightness is close to extremes & less when in the middle.
  final (space, factor, sign) = l > 0.5 ? (1.0 - l, hoverDarken, -1) : (l, hoverLighten, 1);
  final aggressiveness = 1 + ((0.5 - space) / 0.5);
  final adjustment = factor * aggressiveness * sign;
  final lightness = clampDouble(l + adjustment, 0, 1);

  // This isn't accurate since Display P3 colors will be interpreted in sRGB space. We keep this since converting to
  // Display P3 causes a noticeable color shift. A proper fix will require oklch.
  final hovered = hsl.withLightness(lightness).toColor();
  if (hovered.colorSpace != color.colorSpace) {
    return hovered.withValues(colorSpace: color.colorSpace);
  }

  return hovered;
}