Class: Charming::UI::Canvas
- Inherits:
-
Object
- Object
- Charming::UI::Canvas
- Defined in:
- lib/charming/presentation/ui/canvas.rb
Overview
Canvas is a 2D character grid of fixed width and height that supports placing content at (row, column) coordinates and overlaying one block on top of another. Construct via .new(width, height) for a blank grid or .parse(string) to reconstruct from rendered output.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(width, height) ⇒ Canvas
constructor
A new instance of Canvas.
- #overlay(other, top: :center, left: :center) ⇒ Object
- #place(block, top: 0, left: 0, background: nil) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(width, height) ⇒ Canvas
Returns a new instance of Canvas.
10 11 12 13 14 |
# File 'lib/charming/presentation/ui/canvas.rb', line 10 def initialize(width, height) @width = width @height = height @grid = Array.new(height) { " " * width } end |
Class Method Details
.offset(value, available, size) ⇒ Object
45 46 47 48 49 |
# File 'lib/charming/presentation/ui/canvas.rb', line 45 def self.offset(value, available, size) return [(available - size) / 2, 0].max if value == :center value end |
.parse(string) ⇒ Object
16 17 18 19 20 21 22 |
# File 'lib/charming/presentation/ui/canvas.rb', line 16 def self.parse(string) lines = string.to_s.lines(chomp: true) width = UI.block_width(lines) canvas = new(width, lines.length) lines.each_with_index { |line, i| canvas.instance_variable_get(:@grid)[i] = line } canvas end |
Instance Method Details
#overlay(other, top: :center, left: :center) ⇒ Object
37 38 39 40 41 42 43 |
# File 'lib/charming/presentation/ui/canvas.rb', line 37 def (other, top: :center, left: :center) = other.to_s.lines(chomp: true) row = Canvas.offset(top, @grid.length, .length) column = Canvas.offset(left, @width, UI.block_width()) draw_lines(, row: row, column: column, onto: @grid) self end |
#place(block, top: 0, left: 0, background: nil) ⇒ Object
28 29 30 31 32 33 34 35 |
# File 'lib/charming/presentation/ui/canvas.rb', line 28 def place(block, top: 0, left: 0, background: nil) lines = block.to_s.lines(chomp: true) row = Canvas.offset(top, @height, lines.length) column = Canvas.offset(left, @width, UI.block_width(lines)) draw_lines(lines, row: row, column: column, onto: @grid) rendered = to_s background ? UI::Style.new.background(background).render(rendered) : rendered end |
#to_s ⇒ Object
24 25 26 |
# File 'lib/charming/presentation/ui/canvas.rb', line 24 def to_s @grid.join("\n") end |