feat(util): added Snacks.util.on_module to execute a callback when a module loads (or immediately when already loaded)

This commit is contained in:
Folke Lemaitre 2024-12-11 18:23:14 +01:00
parent 6c27ff2a36
commit f540b7b6cc
No known key found for this signature in database
GPG key ID: 41F8B1FBACAE2040

View file

@ -119,7 +119,6 @@ function M.blend(fg, bg, alpha)
end
local transparent ---@type boolean?
--- Check if the colorscheme is transparent.
function M.is_transparent()
if transparent == nil then
@ -158,4 +157,39 @@ function M.redraw(win)
end
end
local mod_timer = assert((vim.uv or vim.loop).new_timer())
local mod_cb = {} ---@type table<string, fun(modname:string)[]>
---@return boolean waiting
local function mod_check()
for modname, cbs in pairs(mod_cb) do
if package.loaded[modname] then
mod_cb[modname] = nil
for _, cb in ipairs(cbs) do
cb(modname)
end
end
end
return next(mod_cb) ~= nil
end
--- Call a function when a module is loaded.
--- The callback is called immediately if the module is already loaded.
--- Otherwise, it is called when the module is loaded.
---@param modname string
---@param cb fun(modname:string)
function M.on_module(modname, cb)
mod_cb[modname] = mod_cb[modname] or {}
table.insert(mod_cb[modname], cb)
if mod_check() then
mod_timer:start(
100,
100,
vim.schedule_wrap(function()
return not mod_check() and mod_timer:stop()
end)
)
end
end
return M