Class: TuiTui::Style

Inherits:
Object
  • Object
show all
Defined in:
lib/tui_tui/style.rb

Overview

Value object for SGR styling. It downgrades richer colors to the selected terminal depth instead of emitting unsupported escape sequences.

Constant Summary collapse

NAMED =
{
  black: 30,
  red: 31,
  green: 32,
  yellow: 33,
  blue: 34,
  magenta: 35,
  cyan: 36,
  white: 37,
  bright_black: 90,
  bright_red: 91,
  bright_green: 92,
  bright_yellow: 93,
  bright_blue: 94,
  bright_magenta: 95,
  bright_cyan: 96,
  bright_white: 97
}.freeze
ATTRS =
{bold: 1, dim: 2, italic: 3, underline: 4, reverse: 7}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fg: nil, bg: nil, attrs: []) ⇒ Style

Returns a new instance of Style.



32
33
34
35
36
37
# File 'lib/tui_tui/style.rb', line 32

def initialize(fg: nil, bg: nil, attrs: [])
  @fg = fg
  @bg = bg
  @attrs = attrs
  @palette = Palette.new
end

Instance Attribute Details

#attrsObject (readonly)

Returns the value of attribute attrs.



30
31
32
# File 'lib/tui_tui/style.rb', line 30

def attrs
  @attrs
end

#bgObject (readonly)

Returns the value of attribute bg.



30
31
32
# File 'lib/tui_tui/style.rb', line 30

def bg
  @bg
end

#fgObject (readonly)

Returns the value of attribute fg.



30
31
32
# File 'lib/tui_tui/style.rb', line 30

def fg
  @fg
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



43
44
45
46
# File 'lib/tui_tui/style.rb', line 43

def ==(other)
  # Canvas diffing relies on equivalent styles comparing equal.
  other.is_a?(Style) && fg == other.fg && bg == other.bg && attrs == other.attrs
end

#hashObject



50
# File 'lib/tui_tui/style.rb', line 50

def hash = [fg, bg, attrs].hash

#paint(text, depth: :ansi256, enabled: true) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/tui_tui/style.rb', line 52

def paint(text, depth: :ansi256, enabled: true)
  return text if !enabled || depth == :none

  codes = sgr_codes(depth)
  return text if codes.empty?

  "\e[#{codes.join(";")}m#{text}\e[0m"
end

#sgr_codes(depth) ⇒ Object



61
62
63
64
65
66
# File 'lib/tui_tui/style.rb', line 61

def sgr_codes(depth)
  codes = @attrs.map { |attr| ATTRS.fetch(attr) }
  codes.concat(color_codes(@fg, depth, ground: :fg))
  codes.concat(color_codes(@bg, depth, ground: :bg))
  codes
end

#with(fg: @fg, bg: @bg, attrs: @attrs) ⇒ Object



39
40
41
# File 'lib/tui_tui/style.rb', line 39

def with(fg: @fg, bg: @bg, attrs: @attrs)
  self.class.new(fg: fg, bg: bg, attrs: attrs)
end