nvim/lua/plugins/codecompanion/fidget-spinner.lua

87 lines
2.3 KiB
Lua

local notify = require("notify")
local spinner_frames = { "", "", "", "", "", "", "", "", "", "" }
local M = {}
function M:init()
local group = vim.api.nvim_create_augroup("CodeCompanionFidgetHooks", {})
vim.api.nvim_create_autocmd({ "User" }, {
pattern = "CodeCompanionRequestStarted",
group = group,
callback = function(request)
local handle = M:create_progress_handle(request)
M:store_progress_handle(request.data.id, handle)
end,
})
vim.api.nvim_create_autocmd({ "User" }, {
pattern = "CodeCompanionRequestFinished",
group = group,
callback = function(request)
local handle = M:pop_progress_handle(request.data.id)
if handle then
M:report_exit_status(handle, request)
handle:finish()
end
end,
})
end
M.handles = {}
function M:store_progress_handle(id, handle)
M.handles[id] = handle
end
function M:pop_progress_handle(id)
local handle = M.handles[id]
M.handles[id] = nil
return handle
end
function M:create_progress_handle(request)
local title = " Requesting assistance (" .. request.data.strategy .. ")"
local idx = 1
local notification_id = notify(spinner_frames[idx] .. " In progress...", "info", { title = title, timeout = false })
local handle = { notification_id = notification_id, title = title }
local timer = vim.loop.new_timer()
if timer == nil then
return
end
timer:start(
0,
100,
vim.schedule_wrap(function()
idx = idx % #spinner_frames + 1
local new_id = notify(
spinner_frames[idx] .. " In progress...",
"info",
{ replace = handle.notification_id, title = title, timeout = false }
)
handle.notification_id = new_id
end)
)
handle.timer = timer
handle.finish = function()
if handle.timer then
handle.timer:stop()
handle.timer:close()
handle.timer = nil
end
end
return handle
end
function M:report_exit_status(handle, request)
local title = handle.title or (" Requesting assistance (" .. request.data.strategy .. ")")
if request.data.status == "success" then
notify("Completed", "info", { replace = handle.notification_id, title = title })
elseif request.data.status == "error" then
notify(" Error", "error", { replace = handle.notification_id, title = title })
else
notify("󰜺 Cancelled", "warn", { replace = handle.notification_id, title = title })
end
end
return M