Class: SuperDiff::Csi::FourBitColor

Inherits:
Color
  • Object
show all
Defined in:
lib/super_diff/csi/four_bit_color.rb

Constant Summary collapse

VALID_TYPES =
[:foreground, :background].freeze
VALID_CODES_BY_NAME =
{
  black: { foreground: 30, background: 40 },
  red: { foreground: 31, background: 41 },
  green: { foreground: 32, background: 42 },
  yellow: { foreground: 33, background: 43 },
  blue: { foreground: 34, background: 44 },
  magenta: { foreground: 35, background: 45 },
  cyan: { foreground: 36, background: 46 },
  white: { foreground: 37, background: 47 },
  bright_black: { foreground: 90, background: 100 },
  bright_red: { foreground: 91, background: 101 },
  bright_green: { foreground: 92, background: 102 },
  bright_yellow: { foreground: 93, background: 103 },
  bright_blue: { foreground: 94, background: 104 },
  bright_magenta: { foreground: 95, background: 105 },
  bright_cyan: { foreground: 96, background: 106 },
  bright_white: { foreground: 97, background: 107 },
}.freeze
COLORS_BY_CODE =
VALID_CODES_BY_NAME.reduce({}) do |hash, (name, value)|
  hash.merge(
    value[:foreground] => { name: name, layer: :foreground },
    value[:background] => { name: name, layer: :background },
  )
end
VALID_NAMES =
VALID_CODES_BY_NAME.keys
VALID_CODE_RANGES =
[30..37, 40..47, 90..97, 100..107].freeze
OPENING_REGEX =
/\e\[(\d+)m/.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Color

#background?, #foreground?, resolve, sub_colorized_areas_in

Constructor Details

#initialize(value, layer: nil) ⇒ FourBitColor

Returns a new instance of FourBitColor.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/super_diff/csi/four_bit_color.rb', line 41

def initialize(value, layer: nil)
  if value.is_a?(Symbol)
    @name = interpret_name!(value)
    @layer = interpret_layer!(layer)
  else
    pair =
      if value.start_with?("\e[")
        interpret_sequence!(value)
      else
        interpret_code!(value)
      end

    @name = pair.fetch(:name)
    @layer = pair.fetch(:layer)
  end
end

Class Method Details

.exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/super_diff/csi/four_bit_color.rb', line 33

def self.exists?(name)
  VALID_CODES_BY_NAME.has_key?(name)
end

.opening_regexObject



37
38
39
# File 'lib/super_diff/csi/four_bit_color.rb', line 37

def self.opening_regex
  OPENING_REGEX
end

Instance Method Details

#to_foregroundObject



63
64
65
# File 'lib/super_diff/csi/four_bit_color.rb', line 63

def to_foreground
  self.class.new(name, layer: :foreground)
end

#to_sObject



58
59
60
61
# File 'lib/super_diff/csi/four_bit_color.rb', line 58

def to_s
  code = VALID_CODES_BY_NAME.fetch(name).fetch(layer)
  "\e[#{code}m"
end