Skip to content

Commit

Permalink
Add log method for printing multiline text above a spinner (ref #36 & #…
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Oct 17, 2020
1 parent 6773721 commit 0ff727b
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 10 deletions.
45 changes: 35 additions & 10 deletions lib/tty/spinner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -350,23 +350,31 @@ def kill
#
# @api public
def spin
return if done?

synchronize do
return if @done
emit(:spin)

if @hide_cursor && !spinning?
write(TTY::Cursor.hide)
end

data = message.gsub(MATCHER, @frames[@current])
data = replace_tokens(data)
write(data, true)
render
@current = (@current + 1) % @length
@state = :spinning
data
end
end

# Render spinner to the output
#
# @api private
def render
return if done?

if @hide_cursor && !spinning?
write(TTY::Cursor.hide)
end

data = message.gsub(MATCHER, @frames[@current])
data = replace_tokens(data)
write(data, true)
end

# Redraw the indent for this spinner, if it exists
#
# @api private
Expand Down Expand Up @@ -474,6 +482,23 @@ def update(tokens)
end
end

# Log text above the current spinner
#
# @param [String] text
# the message to log out
#
# @api public
def log(text)
synchronize do
cleared_text = text.to_s.lines.map do |line|
TTY::Cursor.clear_line + line
end.join

write("#{cleared_text}#{"\n" unless cleared_text.end_with?("\n")}", false)
render
end
end

# Check if IO is attached to a terminal
#
# return [Boolean]
Expand Down
60 changes: 60 additions & 0 deletions spec/unit/log_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
RSpec.describe TTY::Spinner, "#log" do
let(:output) { StringIO.new('', 'w+') }

it "logs a message above a spinner" do
spinner = TTY::Spinner.new(output: output)

2.times {
spinner.log "foo\nbar"
spinner.spin
}
output.rewind

expect(output.read).to eq([
"\e[2K\e[1Gfoo\n",
"\e[2K\e[1Gbar\n",
"\e[1G|",
"\e[1G|",
"\e[2K\e[1Gfoo\n",
"\e[2K\e[1Gbar\n",
"\e[1G/",
"\e[1G/",
].join)
end

it "logs a message ending with a newline above a spinner" do
spinner = TTY::Spinner.new(output: output)

2.times {
spinner.log "foo\n"
spinner.spin
}
output.rewind

expect(output.read).to eq([
"\e[2K\e[1Gfoo\n",
"\e[1G|",
"\e[1G|",
"\e[2K\e[1Gfoo\n",
"\e[1G/",
"\e[1G/",
].join)
end

it "logs message under a spinner when done" do
spinner = TTY::Spinner.new(output: output)
2.times { spinner.spin }
spinner.stop

spinner.log "foo\nbar"

output.rewind
expect(output.read).to eq([
"\e[1G|",
"\e[1G/",
"\e[0m\e[2K\e[1G/\n",
"\e[2K\e[1Gfoo\n",
"\e[2K\e[1Gbar\n"
].join)
end
end

0 comments on commit 0ff727b

Please sign in to comment.