SPB Git

Repository Public MIT

GlassDataGrid.swift 8.1 KB 201 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassData/Data/GlassDataGrid.swift8// Module           : SPGlassData9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SwiftUI43import SPGlassCore44import SPGlassTokens45import SPGlassThemes46import SPGlassEffects47import SPGlassComponents4849/// How the tracks (columns of a vertical grid, rows of a horizontal one) of a ``GlassDataGrid`` are sized.50public enum GlassGridLayout: Hashable, Sendable {51    /// As many tracks as fit, each at least `minimum` points wide and at most `maximum` (unbounded when `nil`).52    case adaptive(minimum: Double, maximum: Double? = nil)53    /// A fixed number of tracks of equal size. Values below one are treated as one.54    case fixed(Int)5556    /// The `GridItem` description of the layout.57    public func gridItems(spacing: Double) -> [GridItem] {58        switch self {59        case .adaptive(let minimum, let maximum):60            let lower = max(1, minimum)61            let upper = maximum.map { max(lower, $0) } ?? .infinity62            return [GridItem(.adaptive(minimum: lower, maximum: upper), spacing: spacing)]63        case .fixed(let count):64            return Array(repeating: GridItem(.flexible(), spacing: spacing), count: max(1, count))65        }66    }6768    /// Number of tracks the layout produces in `length` points, following the rule `LazyVGrid` applies to69    /// adaptive items: as many minimum-size tracks as fit, and never fewer than one.70    public func trackCount(in length: Double, spacing: Double) -> Int {71        switch self {72        case .fixed(let count):73            return max(1, count)74        case .adaptive(let minimum, _):75            let lower = max(1, minimum)76            guard length.isFinite, length > lower else { return 1 }77            return max(1, Int(((length + max(0, spacing)) / (lower + max(0, spacing))).rounded(.down)))78        }79    }80}8182/// A lazy grid over a collection, for large data sets.83///84/// ```swift85/// GlassDataGrid(photos, layout: .adaptive(minimum: 120), selection: $selected) { photo, isSelected in86///     PhotoCell(photo: photo)87/// }88/// ```89///90/// The grid scrolls along its axis and creates cells only as they come on screen (`LazyVGrid` / `LazyHGrid`91/// over the collection itself, identified by the elements' own `id`). Nothing is computed per element in92/// `body`, so collections of tens of thousands of elements are fine as long as the collection has93/// constant-time indexing. Cells are plain content: the grid never puts glass on them.94public struct GlassDataGrid<Data: RandomAccessCollection, Cell: View>: View where Data.Element: Identifiable {95    @GlassThemed private var theme96    private let data: Data97    private let layout: GlassGridLayout98    private let axis: Axis99    private let spacing: GlassSpacingStep100    private let selection: Binding<Set<Data.Element.ID>>?101    private let emptyTitle: Text102    private let cell: (Data.Element, Bool) -> Cell103104    /// - Parameters:105    ///   - data: the elements. Identifiers must be stable and unique.106    ///   - layout: adaptive or fixed tracks.107    ///   - axis: scrolling direction. A horizontal grid needs a bounded height from its container.108    ///   - spacing: distance between cells, from the theme's spacing scale.109    ///   - selection: identifiers of the selected elements; with a binding every cell becomes a toggle.110    ///   - emptyTitle: text of the empty state. Defaults to the localised "No data".111    ///   - cell: the content of one cell and whether it is selected.112    public init(113        _ data: Data,114        layout: GlassGridLayout = .adaptive(minimum: 140),115        axis: Axis = .vertical,116        spacing: GlassSpacingStep = .sm,117        selection: Binding<Set<Data.Element.ID>>? = nil,118        emptyTitle: LocalizedStringKey? = nil,119        @ViewBuilder cell: @escaping (_ element: Data.Element, _ isSelected: Bool) -> Cell120    ) {121        self.data = data122        self.layout = layout123        self.axis = axis124        self.spacing = spacing125        self.selection = selection126        self.emptyTitle = emptyTitle.map { Text($0) } ?? Text(GlassL10n.string(.noData))127        self.cell = cell128    }129130    public var body: some View {131        if data.isEmpty {132            ContentUnavailableView {133                Label { emptyTitle } icon: { Image(systemName: "square.grid.2x2") }134            }135        } else {136            let gap = theme.spacing[spacing]137            let items = layout.gridItems(spacing: gap)138            switch axis {139            case .vertical:140                ScrollView(.vertical) {141                    LazyVGrid(columns: items, spacing: gap) { cells }142                        .padding(gap)143                }144            case .horizontal:145                ScrollView(.horizontal) {146                    LazyHGrid(rows: items, spacing: gap) { cells }147                        .padding(gap)148                }149            }150        }151    }152153    private var cells: some View {154        ForEach(data) { element in155            if let selection {156                selectableCell(element, selection: selection)157            } else {158                cell(element, false)159            }160        }161    }162163    private func selectableCell(_ element: Data.Element, selection: Binding<Set<Data.Element.ID>>) -> some View {164        let isSelected = selection.wrappedValue.contains(element.id)165        return Button {166            selection.wrappedValue = GlassTableLogic.toggling(element.id, in: selection.wrappedValue)167        } label: {168            cell(element, isSelected)169                .overlay(alignment: .topTrailing) {170                    if isSelected {171                        Image(systemName: "checkmark.circle.fill")172                            .symbolRenderingMode(.palette)173                            .foregroundStyle(theme.onColor(.accent), theme.color(.accent))174                            .font(theme.font(.headline))175                            .padding(theme.spacing.xxs)176                            .accessibilityHidden(true)177                    }178                }179                .contentShape(Rectangle())180        }181        .buttonStyle(.plain)182        .accessibilityAddTraits(isSelected ? .isSelected : [])183    }184}185186extension GlassDataGrid {187    /// Creates a grid without selection, whose cells only depend on their element.188    public init(189        _ data: Data,190        layout: GlassGridLayout = .adaptive(minimum: 140),191        axis: Axis = .vertical,192        spacing: GlassSpacingStep = .sm,193        emptyTitle: LocalizedStringKey? = nil,194        @ViewBuilder cell: @escaping (_ element: Data.Element) -> Cell195    ) {196        self.init(data, layout: layout, axis: axis, spacing: spacing, selection: nil, emptyTitle: emptyTitle) { element, _ in197            cell(element)198        }199    }200}201
Files main
Menu

Theme