Class: CLI::UI::Wrap

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/cli/ui/wrap.rb

Instance Method Summary collapse

Methods included from T::Sig

sig

Constructor Details

#initialize(input) ⇒ Wrap

Returns a new instance of Wrap.



15
16
17
# File 'lib/cli/ui/wrap.rb', line 15

def initialize(input)
  @input = input
end

Instance Method Details

#wrap(total_width = Terminal.width) ⇒ Object



20
21
22
23
24
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
58
59
60
# File 'lib/cli/ui/wrap.rb', line 20

def wrap(total_width = Terminal.width)
  max_width = total_width - Frame.prefix_width
  width = T.let(0, Integer)
  final = []
  # Create an alternation of format codes of parameter lengths 1-20, since + and {1,n} not allowed in lookbehind
  format_codes = (1..20).map { |n| /\x1b\[[\d;]{#{n}}m/ }.join('|')
  codes = ''
  @input.split(/(?=\s|\x1b\[[\d;]+m|\r)|(?<=\s|#{format_codes})/).each do |token|
    case token
    when '\x1B[0?m'
      codes = ''
      final << token
    when /\x1b\[[\d;]+m/
      codes += token # Track in use format codes so that they are resent after frame coloring
      final << token
    when "\n"
      final << "\n#{codes}"
      width = 0
    when /\s/
      token_width = ANSI.printing_width(token)
      if width + token_width <= max_width
        final << token
        width += token_width
      else
        final << "\n#{codes}"
        width = 0
      end
    else
      token_width = ANSI.printing_width(token)
      if width + token_width <= max_width
        final << token
        width += token_width
      else
        final << "\n#{codes}"
        final << token
        width = token_width
      end
    end
  end
  final.join
end