Class: Fatty::Ansi::Renderer

Inherits:
Object
  • Object
show all
Defined in:
lib/fatty/ansi/renderer.rb

Constant Summary collapse

CSI =
"\e["

Instance Method Summary collapse

Constructor Details

#initialize(io: nil) ⇒ Renderer

Returns a new instance of Renderer.



8
9
10
# File 'lib/fatty/ansi/renderer.rb', line 8

def initialize(io: nil)
  @io = io
end

Instance Method Details

#ioObject



72
73
74
# File 'lib/fatty/ansi/renderer.rb', line 72

def io
  @io || $stdout
end

#render_line(row:, col:, width:, text:, role:, palette:) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/fatty/ansi/renderer.rb', line 12

def render_line(row:, col:, width:, text:, role:, palette:)
  spec = palette&.[](role)
  return unless spec

  msg = text.to_s.tr("\r\n", " ")
  msg = Fatty::Ansi.truncate_visible(msg, width)
  visible = Fatty::Ansi.visible_length(msg)
  pad = width - visible
  sgr = sgr_for_spec(spec)
  padding = pad.positive? ? " " * pad : ""
  write_ansi("#{CSI}#{row + 1};#{col + 1}H", sgr, msg, sgr, padding, reset)
end

#render_segments_line(row:, col:, width:, segments:, palette:, fill_role: :output) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/fatty/ansi/renderer.rb', line 25

def render_segments_line(row:, col:, width:, segments:, palette:, fill_role: :output)
  rendered = +""
  visible = 0
  segments.each do |seg|
    spec = palette&.[](seg[:role])
    next unless spec

    remaining = width - visible
    break if remaining <= 0

    text = Fatty::Ansi.truncate_visible(seg[:text].to_s, remaining)
    next if text.empty?

    visible += Fatty::Ansi.visible_length(text)

    sgr =
      if seg[:style]
        sgr_for_style(seg[:style], fallback_spec: spec)
      else
        sgr_for_spec(spec)
      end

    rendered << sgr
    rendered << text
  end

  if visible < width
    spec = palette&.[](fill_role)
    rendered << sgr_for_spec(spec) if spec
    rendered << (" " * (width - visible))
  end
  write_ansi("#{CSI}#{row + 1};#{col + 1}H", rendered, reset)
end

#write_ansi(*parts) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/fatty/ansi/renderer.rb', line 59

def write_ansi(*parts)
  text = parts.join

  if defined?(::Curses) && ::Curses.respond_to?(:putp)
    ::Curses.putp(text)
  else
    io.write(text)
    io.flush
  end

  nil
end