Module: Fatty::MenuApi

Included in:
CallbackEnvironment
Defined in:
lib/fatty/api/menu.rb

Instance Method Summary collapse

Instance Method Details

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/fatty/api/menu.rb', line 5

def menu(prompt, choices:, initial_choice_idx: 0, cancel_value: nil)
  items = normalize_menu_choices(choices)
  raise ArgumentError, "choices must not be empty" if items.empty?

  labels = items.keys
  popup = Fatty::PopUpSession.new(
    source: labels,
    kind: :terminal_menu,
    title: "Menu",
    message: prompt,
    prompt: "Narrow: ",
    current: :top,
    validate_unique_labels: true,
    history: terminal.history,
    history_kind: :popup_filter,
    history_ctx: { kind: :popup_filter, popup: :menu, prompt: prompt.to_s },
  )
  popup.instance_variable_set(
    :@current,
    initial_choice_idx.to_i.clamp(0, labels.length - 1),
  )

  done = false
  result = nil
  acc_proc = ->(payload) do
    label = payload[:item]
    action = items[label]

    result =
      if action
        call_menu_action(action, label: label)
      else
        cancel_value
      end

    done = true
  end
  cancel_proc = -> do
    result = cancel_value
    done = true
  end
  owner = Fatty::Terminal::PopupOwner.new(
    on_result: acc_proc,
    on_cancel: cancel_proc,
  )

  begin
    terminal.apply_command(
      Command.terminal(:push_modal, session: popup, owner: owner),
    )
    terminal.render_frame

    while !done && terminal.running?
      dirty = false
      command = terminal.event_source.next_event
      if command
        terminal.apply_command(command)
        dirty = true
      end

      begin
        dirty ||= !!terminal.tick_active_session
      rescue StandardError => e
        Fatty.error(
          "MenuApi#menu tick failed: #{e.class}: #{e.message}",
          tag: :terminal,
        )
        dirty = true
      end

      terminal.render_frame if dirty
    end
  ensure
    terminal.render_frame
  end
  result
end