Files
ox_lib/resource/interface/client/context.lua

95 lines
2.7 KiB
Lua
Raw Normal View History

2022-04-01 21:22:14 +02:00
local contextMenus = {}
local openContextMenu = nil
2022-04-01 21:22:14 +02:00
---@class ContextMenuItem
---@field title? string
---@field menu? string
---@field icon? string
---@field iconColor? string
---@field onSelect? fun(args: any)
---@field arrow? boolean
---@field description? string
---@field metadata? string | { [string]: any } | string[]
---@field event? string
---@field serverEvent? string
---@field args? any
---@class ContextMenuArrayItem : ContextMenuItem
---@field title string
---@class ContextMenuProps
---@field id string
---@field title string
---@field menu? string
---@field onExit? fun()
---@field canClose? boolean
---@field options { [string]: ContextMenuItem } | ContextMenuArrayItem[]
local function closeContext(_, cb, onExit)
if cb then cb(1) end
if (cb or onExit) and contextMenus[openContextMenu].onExit then contextMenus[openContextMenu].onExit() end
SetNuiFocus(false, false)
if not cb then SendNUIMessage({ action = 'hideContext' }) end
openContextMenu = nil
end
---@param id string
function lib.showContext(id)
if not contextMenus[id] then error('No context menu of such id found.') end
2022-04-01 21:22:14 +02:00
local data = contextMenus[id]
openContextMenu = id
2022-04-01 21:22:14 +02:00
SetNuiFocus(true, true)
SendNuiMessage(json.encode({
2022-04-01 21:22:14 +02:00
action = 'showContext',
data = {
title = data.title,
canClose = data.canClose,
2022-04-01 21:22:14 +02:00
menu = data.menu,
options = data.options
}
}, { sort_keys = true }))
2022-04-01 21:22:14 +02:00
end
---@param context ContextMenuProps | ContextMenuProps[]
function lib.registerContext(context)
2022-04-01 21:22:14 +02:00
for k, v in pairs(context) do
if type(k) == 'number' then
contextMenus[v.id] = v
else
contextMenus[context.id] = context
break
end
end
end
---@return string?
function lib.getOpenContextMenu() return openContextMenu end
---@param onExit boolean?
function lib.hideContext(onExit) closeContext(nil, nil, onExit) end
2022-04-11 16:14:32 +02:00
RegisterNUICallback('openContext', function(id, cb)
cb(1)
lib.showContext(id)
2022-04-01 21:22:14 +02:00
end)
RegisterNUICallback('clickContext', function(id, cb)
2022-04-11 16:14:32 +02:00
cb(1)
if math.type(tonumber(id)) == 'float' then
id = math.tointeger(id)
elseif tonumber(id) then
id += 1
end
local data = contextMenus[openContextMenu].options[id]
if not data.event and not data.serverEvent and not data.onSelect then return end
openContextMenu = nil
SetNuiFocus(false, false)
if data.onSelect then data.onSelect(data.args) end
2022-04-01 21:22:14 +02:00
if data.event then TriggerEvent(data.event, data.args) end
if data.serverEvent then TriggerServerEvent(data.serverEvent, data.args) end
SendNUIMessage({
action = 'hideContext'
})
end)
RegisterNUICallback('closeContext', closeContext)