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/.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.



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

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)


88
89
90
# File 'lib/super_diff/csi/four_bit_color.rb', line 88

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

.opening_regexObject



92
93
94
# File 'lib/super_diff/csi/four_bit_color.rb', line 92

def self.opening_regex
  OPENING_REGEX
end

Instance Method Details

#to_foregroundObject



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

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

#to_sObject



113
114
115
116
# File 'lib/super_diff/csi/four_bit_color.rb', line 113

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