SPB Git

Repository Public MIT

GlassTableModel.swift 9.5 KB 239 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassData/Data/GlassTableModel.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 SPGlassComponents4546/// Horizontal alignment of the cells and the header of a ``GlassTableColumn``.47public enum GlassTableColumnAlignment: String, CaseIterable, Sendable {48    /// Text and names.49    case leading50    /// Numbers and amounts, drawn with tabular digits so that they line up.51    case trailing52}5354/// One column of a ``GlassTable``, described by values: a title, the text shown for a row and how rows compare.55///56/// ```swift57/// GlassTableColumn<City>("Name", id: "name") { $0.name }58/// GlassTableColumn<City>("Population", id: "population", sortingBy: { $0.population }) {59///     $0.population.formatted(.number)60/// }61/// .aligned(.trailing)62/// GlassTableColumn<City>("Status", id: "status") { $0.status.name }63///     .badged { $0.status == .open ? .success : .warning }64/// ```65public struct GlassTableColumn<Row>: Identifiable, Sendable {66    /// Stable identifier of the column, used by ``GlassTableSort``.67    public let id: String68    /// Header title, localised by the host application.69    public let title: LocalizedStringResource70    /// The text displayed for a row in this column.71    public let text: @Sendable (Row) -> String72    /// Ascending comparison of two rows for this column.73    public let comparator: @Sendable (Row, Row) -> ComparisonResult74    /// Alignment of the cells and the header. Leading by default.75    public private(set) var alignment: GlassTableColumnAlignment = .leading76    /// When set and it returns a tone, the cell's text is drawn as a soft badge of that tone.77    public private(set) var badgeTone: (@Sendable (Row) -> GlassBadgeTone?)?7879    /// The same column with another alignment. Use `.trailing` for numbers.80    public func aligned(_ alignment: GlassTableColumnAlignment) -> GlassTableColumn {81        var copy = self82        copy.alignment = alignment83        return copy84    }8586    /// The same column with its text drawn as a status badge. The text still carries the meaning: the tone87    /// only colours it. Return `nil` for rows that keep plain text.88    public func badged(_ tone: @escaping @Sendable (Row) -> GlassBadgeTone?) -> GlassTableColumn {89        var copy = self90        copy.badgeTone = tone91        return copy92    }9394    /// Creates a column with an explicit comparator.95    public init(96        _ title: LocalizedStringResource,97        id: String,98        text: @escaping @Sendable (Row) -> String,99        comparator: @escaping @Sendable (Row, Row) -> ComparisonResult100    ) {101        self.id = id102        self.title = title103        self.text = text104        self.comparator = comparator105    }106107    /// Creates a column sorted by its displayed text, compared the way Finder compares names108    /// (case-insensitive, numbers by value, according to the current locale).109    public init(_ title: LocalizedStringResource, id: String, text: @escaping @Sendable (Row) -> String) {110        self.init(title, id: id, text: text) { lhs, rhs in111            text(lhs).localizedStandardCompare(text(rhs))112        }113    }114115    /// Creates a column sorted by a typed value (a number, a date…) while displaying formatted text.116    public init<Value: Comparable & Sendable>(117        _ title: LocalizedStringResource,118        id: String,119        sortingBy value: @escaping @Sendable (Row) -> Value,120        text: @escaping @Sendable (Row) -> String121    ) {122        self.init(title, id: id, text: text) { lhs, rhs in123            let left = value(lhs), right = value(rhs)124            if left < right { return .orderedAscending }125            if right < left { return .orderedDescending }126            return .orderedSame127        }128    }129}130131/// The current sort of a ``GlassTable``: one column and a direction.132public struct GlassTableSort: Hashable, Sendable {133    /// Identifier of the sorted column.134    public var columnID: String135    /// `.forward` is ascending, `.reverse` descending.136    public var order: SortOrder137138    public init(columnID: String, order: SortOrder = .forward) {139        self.columnID = columnID140        self.order = order141    }142143    /// The same column in the other direction.144    public var toggled: GlassTableSort {145        GlassTableSort(columnID: columnID, order: order == .forward ? .reverse : .forward)146    }147}148149/// How rows of a ``GlassTable`` can be selected.150public enum GlassTableSelection<ID: Hashable> {151    /// Rows are not selectable.152    case none153    /// At most one selected row.154    case single(Binding<ID?>)155    /// Any number of selected rows.156    case multiple(Binding<Set<ID>>)157}158159/// Sorting and selection rules of ``GlassTable``, free of any view so that they can be tested.160public enum GlassTableLogic {161    /// Sorts rows by a column. The sort is stable in both directions: rows that compare equal keep the162    /// order they had in `rows`. An unknown column or a `nil` sort returns the rows unchanged.163    public static func sorted<Rows: Sequence>(164        _ rows: Rows,165        by sort: GlassTableSort?,166        columns: [GlassTableColumn<Rows.Element>]167    ) -> [Rows.Element] {168        let source = Array(rows)169        guard let sort, let column = columns.first(where: { $0.id == sort.columnID }) else { return source }170        let ascending = sort.order == .forward171        return source.enumerated().sorted { lhs, rhs in172            switch column.comparator(lhs.element, rhs.element) {173            case .orderedAscending: return ascending174            case .orderedDescending: return !ascending175            case .orderedSame: return lhs.offset < rhs.offset176            }177        }.map(\.element)178    }179180    /// Most columns the dense compact table can hold; beyond it rows are stacked in a list.181    public static let denseCompactColumnLimit = 4182183    /// Whether a compact-width table is drawn as a dense table (true) or as a list of stacked rows (false).184    public static func usesDenseCompactForm(columnCount: Int, isAccessibilitySize: Bool) -> Bool {185        columnCount > 0 && columnCount <= denseCompactColumnLimit && !isAccessibilitySize186    }187188    /// Relative widths of the columns of the dense compact table: the first column, which names the row,189    /// is wider than the others.190    public static func columnWeights(count: Int) -> [Double] {191        guard count > 0 else { return [] }192        return [1.5] + Array(repeating: 1, count: count - 1)193    }194195    /// The sort after the user picks a column: a new column starts ascending, the current one flips.196    public static func sort(afterSelecting columnID: String, current: GlassTableSort?) -> GlassTableSort {197        if let current, current.columnID == columnID { return current.toggled }198        return GlassTableSort(columnID: columnID)199    }200201    /// The selection after a row is activated in multiple-selection mode: the row is toggled.202    public static func toggling<ID: Hashable>(_ id: ID, in selection: Set<ID>) -> Set<ID> {203        var next = selection204        if next.remove(id) == nil { next.insert(id) }205        return next206    }207208    /// The selection after a row is activated in single-selection mode: activating the selected row clears it.209    public static func toggling<ID: Hashable>(_ id: ID, in selection: ID?) -> ID? {210        selection == id ? nil : id211    }212}213214/// Bridges a ``GlassTableColumn`` to the `SortComparator` the system `Table` expects for its sortable headers.215struct GlassTableColumnComparator<Row>: SortComparator {216    let columnID: String217    var order: SortOrder218    let comparator: @Sendable (Row, Row) -> ComparisonResult219220    func compare(_ lhs: Row, _ rhs: Row) -> ComparisonResult {221        let result = comparator(lhs, rhs)222        guard order == .reverse else { return result }223        switch result {224        case .orderedAscending: return .orderedDescending225        case .orderedDescending: return .orderedAscending226        case .orderedSame: return .orderedSame227        }228    }229230    static func == (lhs: Self, rhs: Self) -> Bool {231        lhs.columnID == rhs.columnID && lhs.order == rhs.order232    }233234    func hash(into hasher: inout Hasher) {235        hasher.combine(columnID)236        hasher.combine(order)237    }238}239
Files main
Menu

Theme