Module: Thaum::Color

Defined in:
lib/thaum/color.rb

Overview

Capability detection and color-to-escape mapping with degradation (truecolor → 256 → 16 → none).

Constant Summary collapse

HEX_COLOR_PATTERN =
/\A#[0-9a-fA-F]{6}\z/
ANSI_16 =

16 ANSI color RGB approximations (VGA palette) and their SGR codes for foreground. Background = fg + 10. Bright = (90 or 100) base.

{
  black: { rgb: [0, 0, 0], fg: 30, bg: 40 },
  red: { rgb: [170, 0, 0], fg: 31, bg: 41 },
  green: { rgb: [0, 170, 0], fg: 32, bg: 42 },
  yellow: { rgb: [170, 85, 0], fg: 33, bg: 43 },
  blue: { rgb: [0,   0, 170], fg: 34, bg: 44 },
  magenta: { rgb: [170, 0, 170], fg: 35, bg: 45 },
  cyan: { rgb: [0, 170, 170], fg: 36, bg: 46 },
  white: { rgb: [170, 170, 170], fg: 37, bg: 47 },
  bright_black: { rgb: [85, 85, 85], fg: 90, bg: 100 },
  bright_red: { rgb: [255, 85, 85], fg: 91, bg: 101 },
  bright_green: { rgb: [85, 255, 85], fg: 92, bg: 102 },
  bright_yellow: { rgb: [255, 255, 85], fg: 93, bg: 103 },
  bright_blue: { rgb: [85, 85, 255], fg: 94, bg: 104 },
  bright_magenta: { rgb: [255, 85, 255], fg: 95, bg: 105 },
  bright_cyan: { rgb: [85, 255, 255], fg: 96, bg: 106 },
  bright_white: { rgb: [255, 255, 255], fg: 97, bg: 107 }
}.freeze

Class Method Summary collapse

Class Method Details

.detect(env) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/thaum/color.rb', line 30

def self.detect(env)
  colorterm = env["COLORTERM"]
  term      = env["TERM"]
  return :truecolor if %w[truecolor 24bit].include?(colorterm)
  return :none      if term.nil? || term.empty? || term == "dumb"
  return :"256"     if term.include?("256color")

  :ansi
end

.to_escape(color, capability:, base:) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/thaum/color.rb', line 40

def self.to_escape(color, capability:, base:)
  return "" if capability == :none
  return "" if color.nil?

  if color.is_a?(Array)
    hex, fallback = color
    return capability == :ansi ? to_escape(fallback, capability:, base:) : to_escape(hex, capability:, base:)
  end

  case color
  when Symbol then named_escape(name: color, base: base)
  when String then hex_escape(hex: color, capability: capability, base: base)
  else ""
  end
end