CCCPaste

Basic UI Animation Manager

--[[
    Basic UI Animation Manager by darraghd493
 
    A basic management library for UI libraries.
]]


local TweenService = game:GetService("TweenService")

local UIAnimationManager = {}
UIAnimationManager.ActiveTweens = {}

function UIAnimationManager:Play(instance: Instance, tweenInfo: TweenInfo, properties: table, tag: string?)
	assert(instance, "Instance is required")
	assert(tweenInfo, "TweenInfo is required")
	assert(properties, "Properties table is required")

	self:Cancel(instance, tag)

	local tween = TweenService:Create(instance, tweenInfo, properties)
	local tweenTag = tag or "default"

	self.ActiveTweens[instance] = self.ActiveTweens[instance] or {}
	self.ActiveTweens[instance][tweenTag] = tween

	tween.Completed:Connect(function()
		if self.ActiveTweens[instance] then
			self.ActiveTweens[instance][tweenTag] = nil
			if next(self.ActiveTweens[instance]) == nil then
				self.ActiveTweens[instance] = nil
			end
		end
	end)

	tween:Play()
	return tween
end

function UIAnimationManager:Cancel(instance: Instance, tag: string?)
	local instanceTweens = self.ActiveTweens[instance]
	if not instanceTweens then return end

	if tag then
		local tween = instanceTweens[tag]
		if tween then
			tween:Cancel()
			instanceTweens[tag] = nil
		end
	else
		for key, tween in pairs(instanceTweens) do
			tween:Cancel()
			instanceTweens[key] = nil
		end
	end

	if next(instanceTweens) == nil then
		self.ActiveTweens[instance] = nil
	end
end

function UIAnimationManager:CancelAll()
	for instance, _ in pairs(self.ActiveTweens) do
		self:Cancel(instance)
	end
end

return UIAnimationManager