add padding widget

This commit is contained in:
PeaAshMeter 2025-08-17 06:32:17 +03:00
parent 017f971311
commit 9613e660c3
2 changed files with 58 additions and 1 deletions

View File

@ -471,6 +471,62 @@ local function mk_ctor(class)
return class
end
-- =============== Padding (single child) ===============
---@class Padding: SingleChildElement
---@field padding {left?: number, right?: number, top?: number, bottom?: number}
local Padding = setmetatable({}, { __index = SingleChildElement })
Padding.__index = Padding
---@param props { padding?: {left?: number, right?: number, top?: number, bottom?: number}, child?: Element }|nil
---@return Padding
function Padding:new(props)
local o = SingleChildElement.new(self, props)
---@cast o Padding
local p = o.padding or {}
o.padding = {
left = tonumber(p.left) or 0,
right = tonumber(p.right) or 0,
top = tonumber(p.top) or 0,
bottom = tonumber(p.bottom) or 0,
}
return o
end
function Padding:layout(constraints)
local L = self.padding.left
local R = self.padding.right
local T = self.padding.top
local B = self.padding.bottom
local hp = L + R
local vp = T + B
-- Вычитаем паддинги из ограничений для ребёнка
local child_min_w = math.max(0, constraints.min_w - hp)
local child_min_h = math.max(0, constraints.min_h - vp)
local child_max_w = math.max(0, constraints.max_w - hp)
local child_max_h = math.max(0, constraints.max_h - vp)
local child_c = make_constraints(child_min_w, child_min_h, child_max_w, child_max_h)
if self.child then
self.child:layout(child_c)
local w = self.child.size.x + hp
local h = self.child.size.y + vp
self.size.x, self.size.y = clamp_size(w, h, constraints)
else
-- Нет ребёнка: размер равен сумме паддингов (с учётом ограничений)
self.size.x, self.size.y = clamp_size(hp, vp, constraints)
end
end
function Padding:arrange(origin)
self.origin = Vec3 { origin.x, origin.y, origin.z or 0 }
if not self.child then return end
local L = self.padding.left
local T = self.padding.top
self.child:arrange(Vec3 { self.origin.x + L, self.origin.y + T, self.origin.z })
end
ui.Element = Element
ui.Root = mk_ctor(Root)
ui.Align = mk_ctor(Align)
@ -478,6 +534,7 @@ ui.Row = mk_ctor(Row)
ui.Column = mk_ctor(Column)
ui.Rectangle = mk_ctor(Rectangle)
ui.Expanded = mk_ctor(Expanded)
ui.Padding = mk_ctor(Padding)
-- Экспорт вспомогательных, если пригодится
ui.constraints = {

View File

@ -33,7 +33,7 @@ function love.load()
children = {
ui.Rectangle { size = Vec3 { 100, 100 }, color = { 0, 0, 1 } },
ui.Rectangle { size = Vec3 { 200, 100 }, color = { 1, 0, 0 } },
ui.Expanded { flex = 1, child = ui.Rectangle { size = Vec3 { 100, 150 }, color = { 0, 1, 0 } } },
ui.Padding { padding = { left = 10, right = 10 }, child = ui.Rectangle { size = Vec3 { 100, 150 }, color = { 0, 1, 0 } } },
ui.Rectangle { size = Vec3 { 100, 100 }, color = { 1, 1, 0 } },
}
},