blob: e4b405fcb7e20caa9edfc4eb738f77b115ce9933 [file] [edit]
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package layout
// GridMap manages a 2D spatial arrangement of elements.
// It is essentially a pair of LinearMaps that define a regular grid,
// allowing for efficient O(log N) lookup of cells and intersection ranges.
//
// The map is defined in local coordinates, starting from an origin of (0,0).
type GridMap struct {
XMap *LinearMap
YMap *LinearMap
}
// NewGridMap creates a new map from a set of column widths and row heights.
func NewGridMap(widths, heights []int) *GridMap {
return &GridMap{
XMap: NewLinearMap(widths),
YMap: NewLinearMap(heights),
}
}
// Cell returns the rectangle for the cell at coordinates p.
//
// Example:
//
// For a 2x2 grid with dimensions:
// Widths: [10, 20], Heights: [5, 15]
// Cell(Point{X: 1, Y: 0}) -> Rect{X: {10, 20}, Y: {0, 5}}
func (m *GridMap) Cell(p Point) Rect {
return Rect{
X: m.XMap.Span(p.X),
Y: m.YMap.Span(p.Y),
}
}
// VisibleRange returns the indices of cells that intersect the given viewport.
// This allows a component to perform "windowed rendering" by only processing
// cells that are actually visible to the user.
//
// Example:
//
// For a 2x2 grid with dimensions:
// Widths: [10, 20], Heights: [5, 15]
// VisibleRange(Rect{X: {15, 5}, Y: {10, 5}}) -> BoundingBox{Rows: {1, 2}, Cols: {1, 2}}
func (m *GridMap) VisibleRange(viewport Rect) BoundingBox {
return BoundingBox{
Rows: m.YMap.Intersects(viewport.Y),
Cols: m.XMap.Intersects(viewport.X),
}
}
// TotalWidth returns the full horizontal extent of the map.
func (m *GridMap) TotalWidth() int { return m.XMap.Total() }
// TotalHeight returns the full vertical extent of the map.
func (m *GridMap) TotalHeight() int { return m.YMap.Total() }