Review my button class

local TweenService = game:GetService("TweenService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local Replicated_Assets = ReplicatedStorage.Assets
local Container = Replicated_Assets.Container

local Packets = require(Replicated_Assets.Events.Packets)
local TweenInfoContainer = require(Container.TweenInfo)
local TypeContainer = require(Container.Types)

local rbxEvents = {
	["MouseButton1Down"] = function(self: ButtonClass)
		self.isPressed = true
		self:ChangeSize(1.5, TweenInfoContainer.List.MouseButton1Down)
	end,

	["MouseButton1Up"] = function(self: ButtonClass)
		self.isPressed = false

		if self.isMouseEnter then
			self:ChangeSize(1.25, TweenInfoContainer.List.MouseButton1Up)
		else
			self:ResetSize(TweenInfoContainer.List.MouseButton1Up)
		end
	end,

	["MouseEnter"] = function(self: ButtonClass)
		self.isMouseEnter = true
		self:ChangeSize(1.25, TweenInfoContainer.List.MouseEnter)
	end,

	["MouseLeave"] = function(self: ButtonClass)
		self.isMouseEnter = false
		self:ResetSize(TweenInfoContainer.List.MouseLeave)
	end,
}

local Button = {}
Button.__index = Button

function Button.new(button: TypeContainer.BaseButton, params: TypeContainer.ButtonParams)
	local self = setmetatable({}, Button)
	
	self.button = button
	self.params = params
	self.defaultSize = {
		ScaleX = button.Size.X.Scale,
		ScaleY = button.Size.Y.Scale
	}
	self.isMouseEnter = false
	self.isPressed = false
	self.isActive = false
	self.connections = {}
	
	return self
end

function Button:Active()
	if self.isActive and #self.connections >= 1 then return end
	
	for rbxEvent, func in rbxEvents do
		local connection
		
		connection = self.button[rbxEvent]:Connect(function()
			func(self)
		end)
		
		table.insert(self.connections, connection)
	end
end

function Button:Desactive()
	if not self.isActive and self.connections == 0 then return end
	
	for _, v: RBXScriptConnection in self.connections do
		v:Disconnect()
	end
end

function Button:ChangeSize(div: number, tweenInfo: TweenInfo)
	local scaleX, scaleY = self.defaultSize.ScaleX, self.defaultSize.ScaleY
	local newScaleX, newScaleY = (scaleX / div), (scaleY / div)
	local tween = TweenService:Create(self.button, tweenInfo, {Size = UDim2.new(newScaleX, 0, newScaleY, 0)})

	tween:Play()
end

function Button:ResetSize(tweenInfo: TweenInfo)
	local scaleX, scaleY = self.defaultSize.ScaleX, self.defaultSize.ScaleY
	local tween = TweenService:Create(self.button, tweenInfo, {Size = UDim2.new(scaleX, 0, scaleY, 0)})


	tween:Play()
end

function Button:Destroy()
	self.button:Destroy()
	table.clear(self)
	setmetatable(self, nil)
end

export type ButtonClass = typeof(Button.new(...))

return Button


1 Like