colorForHash function

ConsoleColor colorForHash(
  1. Object? object, {
  2. ColorSaturation? saturation,
  3. TerminalColorSupport? colorSupport,
})

Selects a readable color for object based on terminal capabilities.

This is the main entry point for hash-based color selection. It automatically chooses the best algorithm based on terminal color support:

  • No color support: Returns DefaultColor (terminal's default foreground)
  • ANSI 16 colors: Returns an IndexedColor from the basic 16-color palette
  • 256-color terminals: Returns an IndexedColor from curated readable colors
  • Truecolor terminals: Returns an RgbColor with HSL variance (~7300 variations)

Example

final colorSupport = detectTerminalColorSupport();

// For logger names (vibrant colors)
final color = hashColorForTerminal('MyLogger', ColorPalette.vibrant, colorSupport);

// For class names (subtle colors)
final color = hashColorForTerminal('MyClass', ColorPalette.subtle, colorSupport);

// For method names (muted colors)
final color = hashColorForTerminal('myMethod', ColorPalette.muted, colorSupport);

All returned colors are guaranteed to be readable on both light and dark terminal backgrounds.

See also:

  • hashColorAnsi256 for direct 256-color selection with custom palette
  • hashColorTruecolor for direct truecolor selection with custom palette
  • readableColors for the curated color palettes

Implementation

ConsoleColor colorForHash(
  Object? object, {
  ColorSaturation? saturation,
  TerminalColorSupport? colorSupport,
}) {
  List<IndexedColor> colorPalette() {
    if (saturation == null) {
      return [
        ...readableColorsLowSaturation,
        ...readableColorsMediumSaturation
      ];
    }
    return switch (saturation) {
      ColorSaturation.low => readableColorsLowSaturation,
      ColorSaturation.mid => readableColorsMediumSaturation,
      ColorSaturation.high => readableColorsHighSaturation,
    };
  }

  final support = colorSupport ?? platformColorSupport;
  return switch (support) {
    TerminalColorSupport.none => DefaultColor(),
    TerminalColorSupport.ansi16 => _hashColorAnsi16(object),
    TerminalColorSupport.ansi256 => hashColorAnsi256(object, colorPalette()),
    TerminalColorSupport.truecolor =>
      hashColorTruecolor(object, colorPalette()),
  };
}