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

#hide_cursorObject



91
92
93
# File 'lib/fatty/ansi/renderer.rb', line 91

def hide_cursor
  "#{CSI}?25l"
end

#ioObject



83
84
85
# File 'lib/fatty/ansi/renderer.rb', line 83

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
24
25
26
27
28
29
30
31
32
33
34
# 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", " ")

  segments = Fatty::Ansi.segment(msg).map do |segment_text, style|
    {
      text: segment_text,
      role: role,
      style: style,
    }
  end

  render_segments_line(
    row: row,
    col: col,
    width: width,
    segments: segments,
    palette: palette,
    fill_role: role,
  )
end

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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/fatty/ansi/renderer.rb', line 36

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

#show_cursorObject



87
88
89
# File 'lib/fatty/ansi/renderer.rb', line 87

def show_cursor
  "#{CSI}?25h"
end

#write_ansi(*parts) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/fatty/ansi/renderer.rb', line 70

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