z_mirror/RecipeBook

git clone https://git.raiguard.me/z_mirror/RecipeBook

Caleb HeuerUpdate to 2.0214f243

trunk
1.9 KiB71 linesraw
1local flib_gui = require("__flib__.gui")
2
3--- @class ContextMenu
4--- @field overlay LuaGuiElement
5--- @field window LuaGuiElement
6local context_menu = {}
7local mt = { __index = context_menu }
8script.register_metatable("context_menu", mt)
9
10--- @param player LuaPlayer
11--- @param items LocalisedString[]
12--- @param location GuiLocation
13--- @return ContextMenu
14function context_menu.new(player, items, location)
15  local resolution = player.display_resolution
16  local scale = player.display_scale
17  local overlay_size = { resolution.width / scale, resolution.height / scale }
18
19  local overlay = player.gui.screen.add({
20    type = "frame",
21    name = "rb_context_overlay",
22    style = "invisible_frame",
23    tags = flib_gui.format_handlers({ [defines.events.on_gui_click] = context_menu.on_overlay_clicked }),
24  })
25  overlay.style.size = overlay_size
26  overlay.bring_to_front()
27
28  local window = player.gui.screen.add({
29    type = "frame",
30    name = "rb_context_menu",
31    style = "invisible_frame",
32    direction = "vertical",
33  })
34  window.location = location
35  for i = 1, #items do
36    window.add({
37      type = "button",
38      style = "list_box_item",
39      caption = items[i],
40      tags = flib_gui.format_handlers({ [defines.events.on_gui_click] = context_menu.on_result_clicked }),
41    })
42  end
43  window.bring_to_front()
44
45  --- @type ContextMenu
46  local self = {
47    overlay = overlay,
48    window = window,
49  }
50  return setmetatable(self, mt)
51end
52
53--- @param e EventData.on_gui_click
54function context_menu.on_result_clicked(e)
55  game.print(e.element.caption)
56  context_menu.on_overlay_clicked(e)
57end
58
59--- @param e EventData.on_gui_click
60function context_menu.on_overlay_clicked(e)
61  local player = game.get_player(e.player_index)
62  if not player then
63    return
64  end
65  player.gui.screen.rb_context_overlay.destroy()
66  player.gui.screen.rb_context_menu.destroy()
67end
68
69flib_gui.add_handlers(context_menu, nil, "context_menu")
70
71return context_menu