mirror of
https://github.com/folke/snacks.nvim
synced 2025-08-04 02:38:46 +00:00
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:
parent
6c27ff2a36
commit
f540b7b6cc
1 changed files with 35 additions and 1 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue