|
| 1 | +local grid = {} |
| 2 | + |
| 3 | +--- Calculates positions for all children in a grid layout |
| 4 | +--- @param instance table The layout instance |
| 5 | +--- - container: the container to layout |
| 6 | +--- - options: layout options |
| 7 | +--- - rows: number of rows (optional, auto-calculated if not provided) |
| 8 | +--- - columns: number of columns (optional, auto-calculated if not provided) |
| 9 | +--- - spacing: gap between cells (default: 0) |
| 10 | +--- - padding: padding around the grid (default: 0) |
| 11 | +function grid.calculate(instance) |
| 12 | + local container = instance.container |
| 13 | + local options = instance.options or {} |
| 14 | + |
| 15 | + local children = container.get("children") |
| 16 | + local containerWidth = container.get("width") |
| 17 | + local containerHeight = container.get("height") |
| 18 | + |
| 19 | + local spacing = options.spacing or 0 |
| 20 | + local padding = options.padding or 0 |
| 21 | + local rows = options.rows |
| 22 | + local columns = options.columns |
| 23 | + |
| 24 | + local childCount = #children |
| 25 | + if not rows and not columns then |
| 26 | + columns = math.ceil(math.sqrt(childCount)) |
| 27 | + rows = math.ceil(childCount / columns) |
| 28 | + elseif rows and not columns then |
| 29 | + columns = math.ceil(childCount / rows) |
| 30 | + elseif columns and not rows then |
| 31 | + rows = math.ceil(childCount / columns) |
| 32 | + end |
| 33 | + |
| 34 | + local availableWidth = containerWidth - (2 * padding) - ((columns - 1) * spacing) |
| 35 | + local availableHeight = containerHeight - (2 * padding) - ((rows - 1) * spacing) |
| 36 | + local cellWidth = math.floor(availableWidth / columns) |
| 37 | + local cellHeight = math.floor(availableHeight / rows) |
| 38 | + |
| 39 | + local positions = {} |
| 40 | + |
| 41 | + for i, child in ipairs(children) do |
| 42 | + local row = math.floor((i - 1) / columns) |
| 43 | + local col = (i - 1) % columns |
| 44 | + |
| 45 | + local x = padding + 1 + (col * (cellWidth + spacing)) |
| 46 | + local y = padding + 1 + (row * (cellHeight + spacing)) |
| 47 | + |
| 48 | + positions[child] = { |
| 49 | + x = x, |
| 50 | + y = y, |
| 51 | + width = cellWidth, |
| 52 | + height = cellHeight |
| 53 | + } |
| 54 | + end |
| 55 | + |
| 56 | + instance._positions = positions |
| 57 | +end |
| 58 | + |
| 59 | +return grid |
0 commit comments