Class: Omnibar::Renderer

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

Constant Summary collapse

NON_ASCII_REGEX =
/[^\x00-\x7F]/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, results, selection) ⇒ Renderer

Returns a new instance of Renderer.



7
8
9
10
11
# File 'lib/omnibar/renderer.rb', line 7

def initialize(input, results, selection)
  @input = input
  @results = results
  @selection = selection
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



5
6
7
# File 'lib/omnibar/renderer.rb', line 5

def input
  @input
end

#resultsObject (readonly)

Returns the value of attribute results.



5
6
7
# File 'lib/omnibar/renderer.rb', line 5

def results
  @results
end

#selectionObject (readonly)

Returns the value of attribute selection.



5
6
7
# File 'lib/omnibar/renderer.rb', line 5

def selection
  @selection
end

Instance Method Details

#input_lineObject



34
35
36
37
38
39
40
# File 'lib/omnibar/renderer.rb', line 34

def input_line
  prompt = Omnibar.config.render.prompt
  if prompt.respond_to?(:call)
    prompt = prompt.call(max_label_length)
  end
  "#{prompt} #{input}"
end

#lpad(text, length = ) ⇒ Object



47
48
49
50
# File 'lib/omnibar/renderer.rb', line 47

def lpad(text, length = ANSI.size[:width])
  textlength = text.length + non_ascii_chars(text).length
  (' ' * [0, (length - textlength)].max) + text
end

#max_label_lengthObject



52
53
54
# File 'lib/omnibar/renderer.rb', line 52

def max_label_length
  @mll ||= results.map(&:first).map(&:length).max || 10
end

#non_ascii_chars(string) ⇒ Object



56
57
58
# File 'lib/omnibar/renderer.rb', line 56

def non_ascii_chars(string)
  string.chars.select { |c| c.match?(NON_ASCII_REGEX) }
end

#render!Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/omnibar/renderer.rb', line 13

def render!
  ANSI.clear_screen
  ANSI.move_cursor(0, 0)
  puts input_line
  ANSI.move_cursor(1, 0)
  results.each.with_index do |result, i|
    text = [
      lpad(result.first, max_label_length),
      rpad(result.last, ANSI.size[:width] - max_label_length - 2)
    ].join(': ')

    if i == selection
      text = ANSI.color(text,
                        fg: Omnibar.config.render.highlight.fg,
                        bg: Omnibar.config.render.highlight.bg)
    end
    print "#{text}\r\n"
  end
  ANSI.move_cursor(0, input_line.length)
end

#rpad(text, length = ) ⇒ Object



42
43
44
45
# File 'lib/omnibar/renderer.rb', line 42

def rpad(text, length = ANSI.size[:width])
  textlength = text.length + non_ascii_chars(text).length
  text + (' ' * [0, (length - textlength)].max)
end