Class: SuperDiff::Csi::FourBitColor

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

Constant Summary collapse

VALID_TYPES =
%i[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/

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.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/super_diff/csi/four_bit_color.rb', line 98

def initialize(value, layer: nil)
  super()
  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)


90
91
92
# File 'lib/super_diff/csi/four_bit_color.rb', line 90

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

.opening_regexObject



94
95
96
# File 'lib/super_diff/csi/four_bit_color.rb', line 94

def self.opening_regex
  OPENING_REGEX
end

Instance Method Details

#to_foregroundObject



121
122
123
# File 'lib/super_diff/csi/four_bit_color.rb', line 121

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

#to_sObject



116
117
118
119
# File 'lib/super_diff/csi/four_bit_color.rb', line 116

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