Class: Thaum::Select

Inherits:
Object
  • Object
show all
Includes:
Sigil
Defined in:
lib/thaum/sigils/select.rb

Constant Summary collapse

SelectedEvent =
Thaum::Event.define(:index, :item)

Instance Attribute Summary collapse

Attributes included from Sigil

#handler_parent, #rect, #thaum_app

Instance Method Summary collapse

Methods included from Sigil

#emit, #focusable?, #focused?, #on_blur, #on_focus, #on_mount, #on_mouse, #on_paste, #on_tick, #on_unmount, #on_update, #request_render

Constructor Details

#initialize(items:, cursor: 0) ⇒ Select

Returns a new instance of Select.



11
12
13
14
# File 'lib/thaum/sigils/select.rb', line 11

def initialize(items:, cursor: 0)
  @items  = items
  @cursor = cursor
end

Instance Attribute Details

#cursorObject (readonly)

Returns the value of attribute cursor.



9
10
11
# File 'lib/thaum/sigils/select.rb', line 9

def cursor
  @cursor
end

#itemsObject (readonly)

Returns the value of attribute items.



9
10
11
# File 'lib/thaum/sigils/select.rb', line 9

def items
  @items
end

Instance Method Details

#currentObject



16
# File 'lib/thaum/sigils/select.rb', line 16

def current = items[cursor]

#on_key(event) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/thaum/sigils/select.rb', line 18

def on_key(event)
  case event.key
  when :down  then @cursor = [cursor + 1, items.length - 1].min if items.any?
  when :up    then @cursor = [cursor - 1, 0].max
  when :enter then emit_selected
  else emit(event)
  end
end

#render(canvas:, theme:) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/thaum/sigils/select.rb', line 27

def render(canvas:, theme:)
  offset = scroll_offset(canvas.height)
  visible_range = offset...(offset + canvas.height)

  visible_range.each_with_index do |item_idx, row_idx|
    item = items[item_idx] or next
    row  = canvas.row(row_idx) or break

    bg = item_idx == cursor ? theme.selection : theme.bg
    fg = item_idx == cursor ? theme.selection_fg : theme.fg
    row.fill(bg: bg)
    row.text(content: item.to_s, fg: fg, bg: bg)
  end
end