Class: Charming::Presentation::UI::Canvas

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(width, height) ⇒ Canvas

Returns a new instance of Canvas.



11
12
13
14
15
# File 'lib/charming/presentation/ui/canvas.rb', line 11

def initialize(width, height)
  @width = width
  @height = height
  @grid = Array.new(height) { " " * width }
end

Class Method Details

.offset(value, available, size) ⇒ Object



46
47
48
49
50
# File 'lib/charming/presentation/ui/canvas.rb', line 46

def self.offset(value, available, size)
  return [(available - size) / 2, 0].max if value == :center

  value
end

.parse(string) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/charming/presentation/ui/canvas.rb', line 17

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



38
39
40
41
42
43
44
# File 'lib/charming/presentation/ui/canvas.rb', line 38

def overlay(other, top: :center, left: :center)
  overlay_lines = other.to_s.lines(chomp: true)
  row = Canvas.offset(top, @grid.length, overlay_lines.length)
  column = Canvas.offset(left, @width, UI.block_width(overlay_lines))
  draw_lines(overlay_lines, row: row, column: column, onto: @grid)
  self
end

#place(block, top: 0, left: 0, background: nil) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/charming/presentation/ui/canvas.rb', line 29

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_sObject



25
26
27
# File 'lib/charming/presentation/ui/canvas.rb', line 25

def to_s
  @grid.join("\n")
end