Class: Charming::Components::Table

Inherits:
Charming::Component show all
Includes:
KeyboardHandler
Defined in:
lib/charming/components/table.rb

Constant Summary collapse

KEY_ACTIONS =
{
  up: :move_up,
  down: :move_down,
  home: :move_home,
  end: :move_end
}.freeze
HEADER_HEIGHT =
2

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(header:, rows: [], selected_index: 0) ⇒ Table

Returns a new instance of Table.



21
22
23
24
25
26
# File 'lib/charming/components/table.rb', line 21

def initialize(header:, rows: [], selected_index: 0)
  super()
  @header = Array(header).map(&:to_s)
  @rows = Array(rows)
  @selected_index = clamp_index(selected_index)
end

Instance Attribute Details

#headerObject (readonly)

Returns the value of attribute header.



19
20
21
# File 'lib/charming/components/table.rb', line 19

def header
  @header
end

#rowsObject (readonly)

Returns the value of attribute rows.



19
20
21
# File 'lib/charming/components/table.rb', line 19

def rows
  @rows
end

#selected_indexObject (readonly)

Returns the value of attribute selected_index.



19
20
21
# File 'lib/charming/components/table.rb', line 19

def selected_index
  @selected_index
end

Instance Method Details

#handle_key(event) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/charming/components/table.rb', line 28

def handle_key(event)
  return nil if rows.empty?

  case Charming.key_of(event)
  when :enter then [:selected, selected_row]
  else super
  end
end

#handle_mouse(event) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/charming/components/table.rb', line 37

def handle_mouse(event)
  return nil if rows.empty?
  return nil unless event.respond_to?(:click?) && event.click?

  clicked = event.y - HEADER_HEIGHT
  return nil if clicked.negative? || clicked >= rows.length

  @selected_index = clicked
  :handled
end

#renderObject



52
53
54
55
56
57
58
59
60
61
# File 'lib/charming/components/table.rb', line 52

def render
  return "(empty table)" if header.empty? && rows.empty?

  normalized = rows.map { |row| normalize_row(row) }
  lines = TTY::Table.new(header: header, rows: normalized)
    .render(:unicode)
    .lines(chomp: true)

  compact_layout(lines)
end

#selected_rowObject



48
49
50
# File 'lib/charming/components/table.rb', line 48

def selected_row
  rows[selected_index]
end