SPB Git

Repository Public MIT

GlassTable.swift 18.6 KB 465 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassData/Data/GlassTable.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/// A sortable, selectable table: the system `Table` on macOS and regular-width iPad, a dense themed table in50/// compact width.51///52/// ```swift53/// @State private var sort: GlassTableSort? = GlassTableSort(columnID: "name")54/// @State private var selection: Set<City.ID> = []55///56/// GlassTable(cities, columns: [57///     GlassTableColumn("Name", id: "name") { $0.name },58///     GlassTableColumn("Population", id: "population", sortingBy: { $0.population }) {59///         $0.population.formatted(.number)60///     },61/// ], sort: $sort, selection: .multiple($selection))62/// ```63///64/// The table sorts the rows it displays with ``GlassTableLogic/sorted(_:by:columns:)``; the host keeps its own65/// collection untouched and owns the sort and the selection through bindings. On macOS and regular-width iPad66/// the system draws the table. In compact width, up to four columns are drawn as a dense table on an opaque67/// surface (sortable headers with a direction indicator, hairlines, aligned numbers, a marked selected row);68/// with more columns, or at accessibility text sizes, each row becomes a stack of labelled values in a `List`.69public struct GlassTable<Row: Identifiable>: View {70    @GlassThemed private var theme71    #if os(iOS)72    @Environment(\.horizontalSizeClass) private var horizontalSizeClass73    #endif74    @Environment(\.dynamicTypeSize) private var dynamicTypeSize75    private let rows: [Row]76    private let columns: [GlassTableColumn<Row>]77    @Binding private var sort: GlassTableSort?78    private let selection: GlassTableSelection<Row.ID>79    private let emptyTitle: Text8081    /// - Parameters:82    ///   - rows: the rows, in the host's order. They are sorted for display only.83    ///   - columns: the columns, leading to trailing. The first one is the row's main text in the list form.84    ///   - sort: the current sort, or `nil` to keep the host's order.85    ///   - selection: none, single or multiple selection.86    ///   - emptyTitle: text of the empty state. Defaults to the localised "No data".87    public init<Rows: Sequence>(88        _ rows: Rows,89        columns: [GlassTableColumn<Row>],90        sort: Binding<GlassTableSort?> = .constant(nil),91        selection: GlassTableSelection<Row.ID> = .none,92        emptyTitle: LocalizedStringKey? = nil93    ) where Rows.Element == Row {94        self.rows = Array(rows)95        self.columns = columns96        self._sort = sort97        self.selection = selection98        self.emptyTitle = emptyTitle.map { Text($0) } ?? Text(GlassL10n.string(.noData))99    }100101    public var body: some View {102        if rows.isEmpty {103            VStack(spacing: theme.spacing.xs) {104                Image(systemName: "tablecells")105                    .font(.system(.title, weight: .light))106                    .foregroundStyle(theme.color(.textSecondary))107                    .accessibilityHidden(true)108                emptyTitle109                    .font(theme.font(.headline))110                    .foregroundStyle(theme.color(.textPrimary))111                    .multilineTextAlignment(.center)112            }113            .frame(maxWidth: .infinity, minHeight: 140)114            .padding(theme.spacing.md)115            .glassOpaqueSurface(in: theme.shape(\.large))116        } else {117            let sortedRows = GlassTableLogic.sorted(rows, by: sort, columns: columns)118            #if os(iOS)119            if horizontalSizeClass == .compact {120                if GlassTableLogic.usesDenseCompactForm(columnCount: columns.count, isAccessibilitySize: dynamicTypeSize.isAccessibilitySize) {121                    compactTable(sortedRows)122                } else {123                    compactList(sortedRows)124                }125            } else {126                nativeTable(sortedRows)127            }128            #else129            nativeTable(sortedRows)130            #endif131        }132    }133134    // MARK: Native table135136    @ViewBuilder137    private func nativeTable(_ sortedRows: [Row]) -> some View {138        switch selection {139        case .none:140            Table(sortedRows, sortOrder: sortOrder) { tableColumns }141        case .single(let binding):142            Table(sortedRows, selection: binding, sortOrder: sortOrder) { tableColumns }143        case .multiple(let binding):144            Table(sortedRows, selection: binding, sortOrder: sortOrder) { tableColumns }145        }146    }147148    @TableColumnBuilder<Row, GlassTableColumnComparator<Row>>149    private var tableColumns: some TableColumnContent<Row, GlassTableColumnComparator<Row>> {150        TableColumnForEach(columns) { column in151            TableColumn(152                Text(column.title),153                sortUsing: GlassTableColumnComparator(columnID: column.id, order: .forward, comparator: column.comparator)154            ) { row in155                cell(column, row)156                    .frame(maxWidth: .infinity, alignment: column.alignment == .trailing ? .trailing : .leading)157            }158        }159    }160161    /// The content of one cell: a soft badge when the column asks for one, otherwise text.162    @ViewBuilder163    private func cell(_ column: GlassTableColumn<Row>, _ row: Row) -> some View {164        let text = column.text(row)165        if let tone = column.badgeTone?(row), !text.isEmpty {166            GlassBadge(text, tone: tone, style: .soft)167        } else if column.alignment == .trailing {168            Text(verbatim: text).monospacedDigit()169        } else {170            Text(verbatim: text)171        }172    }173174    // MARK: Compact table175176    private var hasSelection: Bool {177        if case .none = selection { false } else { true }178    }179180    private func isSelected(_ row: Row) -> Bool {181        switch selection {182        case .none: false183        case .single(let binding): binding.wrappedValue == row.id184        case .multiple(let binding): binding.wrappedValue.contains(row.id)185        }186    }187188    private func toggle(_ row: Row) {189        switch selection {190        case .none: break191        case .single(let binding): binding.wrappedValue = GlassTableLogic.toggling(row.id, in: binding.wrappedValue)192        case .multiple(let binding): binding.wrappedValue = GlassTableLogic.toggling(row.id, in: binding.wrappedValue)193        }194    }195196    private var rowLayout: GlassTableRowLayout {197        GlassTableRowLayout(weights: GlassTableLogic.columnWeights(count: columns.count), spacing: theme.spacing.sm)198    }199200    private var hairline: some View {201        Rectangle()202            .fill(theme.color(.separator).opacity(0.7))203            .frame(height: 1)204            .accessibilityHidden(true)205    }206207    private func compactTable(_ sortedRows: [Row]) -> some View {208        VStack(spacing: 0) {209            headerRow210            hairline211            // A short table takes its own height; a long one scrolls and stays lazy.212            ViewThatFits(in: .vertical) {213                tableRows(sortedRows)214                ScrollView(.vertical) { tableRows(sortedRows) }215            }216        }217        .clipShape(theme.shape(\.large))218        .glassOpaqueSurface(in: theme.shape(\.large))219    }220221    private func tableRows(_ sortedRows: [Row]) -> some View {222        LazyVStack(spacing: 0) {223            ForEach(sortedRows) { row in224                tableRow(row)225            }226        }227    }228229    private var headerRow: some View {230        HStack(spacing: 0) {231            rowLayout {232                ForEach(columns) { column in233                    let isSorted = sort?.columnID == column.id234                    Button {235                        sort = GlassTableLogic.sort(afterSelecting: column.id, current: sort)236                    } label: {237                        HStack(spacing: 3) {238                            Text(column.title)239                                .font(.system(.caption2, weight: .semibold))240                                .textCase(.uppercase)241                                .tracking(0.5)242                                .lineLimit(2)243                                .multilineTextAlignment(column.alignment == .trailing ? .trailing : .leading)244                            if let sort, isSorted {245                                Image(systemName: sort.order == .forward ? "chevron.up" : "chevron.down")246                                    .font(.system(size: 9, weight: .heavy))247                                    .accessibilityHidden(true)248                            }249                        }250                        .foregroundStyle(theme.color(isSorted ? .textPrimary : .textSecondary))251                        .frame(maxWidth: .infinity, minHeight: 40, alignment: column.alignment == .trailing ? .trailing : .leading)252                        .contentShape(Rectangle())253                    }254                    .buttonStyle(.plain)255                    .accessibilityHint(Text(GlassL10n.string(.sortBy)))256                    .accessibilityValue(sortDescription(for: column))257                }258            }259            if hasSelection {260                Color.clear.frame(width: 28, height: 1).accessibilityHidden(true)261            }262        }263        .padding(.horizontal, theme.spacing.md)264        .background(theme.color(.textPrimary).opacity(0.035))265    }266267    @ViewBuilder268    private func tableRow(_ row: Row) -> some View {269        if hasSelection {270            let selected = isSelected(row)271            Button { toggle(row) } label: { tableRowContent(row, isSelected: selected) }272                .buttonStyle(.plain)273                .accessibilityAddTraits(selected ? .isSelected : [])274        } else {275            tableRowContent(row, isSelected: false)276        }277    }278279    private func tableRowContent(_ row: Row, isSelected: Bool) -> some View {280        HStack(spacing: 0) {281            rowLayout {282                ForEach(Array(columns.enumerated()), id: \.element.id) { index, column in283                    cell(column, row)284                        .font(index == 0 ? theme.font(.callout).weight(.medium) : theme.font(.callout))285                        .foregroundStyle(theme.color(index == 0 || column.alignment == .trailing ? .textPrimary : .textSecondary))286                        .lineLimit(2)287                        .frame(maxWidth: .infinity, alignment: column.alignment == .trailing ? .trailing : .leading)288                }289            }290            if hasSelection {291                Image(systemName: "checkmark")292                    .font(.system(.footnote, weight: .bold))293                    .foregroundStyle(theme.color(.accent))294                    .opacity(isSelected ? 1 : 0)295                    .frame(width: 28, alignment: .trailing)296                    .accessibilityHidden(true)297            }298        }299        .padding(.horizontal, theme.spacing.md)300        .padding(.vertical, theme.spacing.xs)301        .frame(minHeight: 44)302        .background(isSelected ? theme.color(.accent).opacity(theme.isDark ? 0.2 : 0.1) : .clear)303        .overlay(alignment: .leading) {304            if isSelected {305                Rectangle().fill(theme.color(.accent)).frame(width: 3).accessibilityHidden(true)306            }307        }308        .overlay(alignment: .bottom) { hairline.opacity(0.7) }309        .contentShape(Rectangle())310        .accessibilityElement(children: .combine)311    }312313    /// The system table works with an array of comparators; GlassTable exposes the first one as its sort.314    private var sortOrder: Binding<[GlassTableColumnComparator<Row>]> {315        Binding {316            guard let sort, let column = columns.first(where: { $0.id == sort.columnID }) else { return [] }317            return [GlassTableColumnComparator(columnID: column.id, order: sort.order, comparator: column.comparator)]318        } set: { comparators in319            sort = comparators.first.map { GlassTableSort(columnID: $0.columnID, order: $0.order) }320        }321    }322323    // MARK: Compact list324325    private func compactList(_ sortedRows: [Row]) -> some View {326        List {327            Section {328                ForEach(sortedRows) { row in329                    compactRow(row)330                }331            } header: {332                sortMenu333            }334        }335    }336337    private var sortMenu: some View {338        Menu {339            ForEach(columns) { column in340                Button {341                    sort = GlassTableLogic.sort(afterSelecting: column.id, current: sort)342                } label: {343                    if let sort, sort.columnID == column.id {344                        Label { Text(column.title) } icon: {345                            Image(systemName: sort.order == .forward ? "chevron.up" : "chevron.down")346                        }347                    } else {348                        Text(column.title)349                    }350                }351                .accessibilityValue(sortDescription(for: column))352            }353        } label: {354            Label {355                if let column = sortedColumn {356                    Text("\(GlassL10n.string(.sortBy)): \(Text(column.title))")357                } else {358                    Text(GlassL10n.string(.sortBy))359                }360            } icon: {361                Image(systemName: "arrow.up.arrow.down")362            }363        }364        .accessibilityValue(sortedColumn.map(sortDescription(for:)) ?? Text(verbatim: ""))365    }366367    private var sortedColumn: GlassTableColumn<Row>? {368        guard let sort else { return nil }369        return columns.first { $0.id == sort.columnID }370    }371372    private func sortDescription(for column: GlassTableColumn<Row>) -> Text {373        guard let sort, sort.columnID == column.id else { return Text(verbatim: "") }374        return Text(GlassL10n.string(sort.order == .forward ? .sortAscending : .sortDescending))375    }376377    @ViewBuilder378    private func compactRow(_ row: Row) -> some View {379        switch selection {380        case .none:381            compactRowContent(row)382        case .single(let binding):383            selectableRow(row, isSelected: binding.wrappedValue == row.id) {384                binding.wrappedValue = GlassTableLogic.toggling(row.id, in: binding.wrappedValue)385            }386        case .multiple(let binding):387            selectableRow(row, isSelected: binding.wrappedValue.contains(row.id)) {388                binding.wrappedValue = GlassTableLogic.toggling(row.id, in: binding.wrappedValue)389            }390        }391    }392393    private func selectableRow(_ row: Row, isSelected: Bool, toggle: @escaping @MainActor () -> Void) -> some View {394        Button(action: toggle) {395            HStack(alignment: .firstTextBaseline, spacing: theme.spacing.sm) {396                compactRowContent(row)397                Spacer(minLength: 0)398                if isSelected {399                    Image(systemName: "checkmark")400                        .foregroundStyle(theme.color(.accent))401                        .accessibilityHidden(true)402                }403            }404            .contentShape(Rectangle())405        }406        .buttonStyle(.plain)407        .accessibilityAddTraits(isSelected ? .isSelected : [])408    }409410    private func compactRowContent(_ row: Row) -> some View {411        VStack(alignment: .leading, spacing: theme.spacing.xxs) {412            ForEach(Array(columns.enumerated()), id: \.element.id) { index, column in413                if index == 0 {414                    Text(verbatim: column.text(row))415                        .font(theme.font(.headline))416                        .foregroundStyle(theme.color(.textPrimary))417                } else {418                    LabeledContent {419                        Text(verbatim: column.text(row))420                    } label: {421                        Text(column.title)422                    }423                    .font(theme.font(.callout))424                }425            }426        }427        .accessibilityElement(children: .combine)428    }429}430431/// Lays the cells of a table row out in columns whose widths follow fixed weights, so that every row and432/// the header share the same columns without measuring each other.433struct GlassTableRowLayout: Layout {434    let weights: [Double]435    let spacing: Double436437    private func widths(for subviews: Subviews, in width: Double) -> [Double] {438        let count = subviews.count439        guard count > 0 else { return [] }440        let used = (0..<count).map { $0 < weights.count ? max(weights[$0], 0.01) : 1 }441        let total = used.reduce(0, +)442        let available = max(0, width - spacing * Double(count - 1))443        return used.map { available * $0 / total }444    }445446    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {447        let width = proposal.width ?? 320448        let widths = widths(for: subviews, in: width)449        var height: CGFloat = 0450        for (subview, cellWidth) in zip(subviews, widths) {451            height = max(height, subview.sizeThatFits(ProposedViewSize(width: cellWidth, height: nil)).height)452        }453        return CGSize(width: width, height: height)454    }455456    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {457        let widths = widths(for: subviews, in: bounds.width)458        var x = bounds.minX459        for (subview, cellWidth) in zip(subviews, widths) {460            subview.place(at: CGPoint(x: x, y: bounds.midY), anchor: .leading, proposal: ProposedViewSize(width: cellWidth, height: bounds.height))461            x += cellWidth + spacing462        }463    }464}465
Files main
Menu

Theme