// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassData/Data/GlassDataGrid.swift // Module : SPGlassData // Repository : https://git.spboucher.ai/sp-glasskit // Project Website : https://glass.spboucher.ai // Created : 2026-12-02 // Last Modified : 2026-12-02 // // Author : Simon-Pierre Boucher // Position : Professor of Finance // Institution : Université du Québec en Outaouais (UQO) // Organization : SP Boucher // Website : https://spboucher.ai // Git : https://git.spboucher.ai // // Preferred Contact: contact@spboucher.ai // Development : dev@spboucher.ai // Support : support@spboucher.ai // Security/Admin : admin@spboucher.ai // // Copyright (c) 2026 // Simon-Pierre Boucher // All rights reserved where applicable. This file is governed by the // applicable project license, copyright notices and relevant law. // Existing third-party rights and notices remain unaffected. // // License : MIT // // Do not embed credentials, private keys, access tokens, // certificates or confidential personal information. // // ============================================================================= // END OF SP BOUCHER SOURCE HEADER // ============================================================================= import Foundation import SwiftUI /// How the tracks (columns of a vertical grid, rows of a horizontal one) of a ``GlassDataGrid`` are sized. public enum GlassGridLayout: Hashable, Sendable { /// As many tracks as fit, each at least `minimum` points wide and at most `maximum` (unbounded when `nil`). case adaptive(minimum: Double, maximum: Double? = nil) /// A fixed number of tracks of equal size. Values below one are treated as one. case fixed(Int) /// The `GridItem` description of the layout. public func gridItems(spacing: Double) -> [GridItem] { switch self { case .adaptive(let minimum, let maximum): let lower = max(1, minimum) let upper = maximum.map { max(lower, $0) } ?? .infinity return [GridItem(.adaptive(minimum: lower, maximum: upper), spacing: spacing)] case .fixed(let count): return Array(repeating: GridItem(.flexible(), spacing: spacing), count: max(1, count)) } } /// Number of tracks the layout produces in `length` points, following the rule `LazyVGrid` applies to /// adaptive items: as many minimum-size tracks as fit, and never fewer than one. public func trackCount(in length: Double, spacing: Double) -> Int { switch self { case .fixed(let count): return max(1, count) case .adaptive(let minimum, _): let lower = max(1, minimum) guard length.isFinite, length > lower else { return 1 } return max(1, Int(((length + max(0, spacing)) / (lower + max(0, spacing))).rounded(.down))) } } } /// A lazy grid over a collection, for large data sets. /// /// ```swift /// GlassDataGrid(photos, layout: .adaptive(minimum: 120), selection: $selected) { photo, isSelected in /// PhotoCell(photo: photo) /// } /// ``` /// /// The grid scrolls along its axis and creates cells only as they come on screen (`LazyVGrid` / `LazyHGrid` /// over the collection itself, identified by the elements' own `id`). Nothing is computed per element in /// `body`, so collections of tens of thousands of elements are fine as long as the collection has /// constant-time indexing. Cells are plain content: the grid never puts glass on them. public struct GlassDataGrid: View where Data.Element: Identifiable { @GlassThemed private var theme private let data: Data private let layout: GlassGridLayout private let axis: Axis private let spacing: GlassSpacingStep private let selection: Binding>? private let emptyTitle: Text private let cell: (Data.Element, Bool) -> Cell /// - Parameters: /// - data: the elements. Identifiers must be stable and unique. /// - layout: adaptive or fixed tracks. /// - axis: scrolling direction. A horizontal grid needs a bounded height from its container. /// - spacing: distance between cells, from the theme's spacing scale. /// - selection: identifiers of the selected elements; with a binding every cell becomes a toggle. /// - emptyTitle: text of the empty state. Defaults to the localised "No data". /// - cell: the content of one cell and whether it is selected. public init( _ data: Data, layout: GlassGridLayout = .adaptive(minimum: 140), axis: Axis = .vertical, spacing: GlassSpacingStep = .sm, selection: Binding>? = nil, emptyTitle: LocalizedStringKey? = nil, @ViewBuilder cell: @escaping (_ element: Data.Element, _ isSelected: Bool) -> Cell ) { self.data = data self.layout = layout self.axis = axis self.spacing = spacing self.selection = selection self.emptyTitle = emptyTitle.map { Text($0) } ?? Text(GlassL10n.string(.noData)) self.cell = cell } public var body: some View { if data.isEmpty { ContentUnavailableView { Label { emptyTitle } icon: { Image(systemName: "square.grid.2x2") } } } else { let gap = theme.spacing[spacing] let items = layout.gridItems(spacing: gap) switch axis { case .vertical: ScrollView(.vertical) { LazyVGrid(columns: items, spacing: gap) { cells } .padding(gap) } case .horizontal: ScrollView(.horizontal) { LazyHGrid(rows: items, spacing: gap) { cells } .padding(gap) } } } } private var cells: some View { ForEach(data) { element in if let selection { selectableCell(element, selection: selection) } else { cell(element, false) } } } private func selectableCell(_ element: Data.Element, selection: Binding>) -> some View { let isSelected = selection.wrappedValue.contains(element.id) return Button { selection.wrappedValue = GlassTableLogic.toggling(element.id, in: selection.wrappedValue) } label: { cell(element, isSelected) .overlay(alignment: .topTrailing) { if isSelected { Image(systemName: "checkmark.circle.fill") .symbolRenderingMode(.palette) .foregroundStyle(theme.onColor(.accent), theme.color(.accent)) .font(theme.font(.headline)) .padding(theme.spacing.xxs) .accessibilityHidden(true) } } .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityAddTraits(isSelected ? .isSelected : []) } } extension GlassDataGrid { /// Creates a grid without selection, whose cells only depend on their element. public init( _ data: Data, layout: GlassGridLayout = .adaptive(minimum: 140), axis: Axis = .vertical, spacing: GlassSpacingStep = .sm, emptyTitle: LocalizedStringKey? = nil, @ViewBuilder cell: @escaping (_ element: Data.Element) -> Cell ) { self.init(data, layout: layout, axis: axis, spacing: spacing, selection: nil, emptyTitle: emptyTitle) { element, _ in cell(element) } } }