SPB Git

Repository Public

VQDataTable.swift 9.7 KB 189 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Components/VQDataTable.swift3// Description: The dense table: overline headers with the unit, tabular right-aligned numbers, hairline rows, sort,4//              a pinned header and lazy rows when a height is given.5import SwiftUI6import VQuantKit78public struct VQTableColumn: Identifiable, Sendable, Hashable {9    public enum Alignment: Sendable, Hashable { case leading, trailing, center }10    public var id: String11    public var title: String12    /// Shown once in the header ("%", "$ US"), not in every cell.13    public var unit: String?14    public var alignment: Alignment15    public var sortable: Bool16    public init(id: String, title: String, unit: String? = nil, alignment: Alignment = .leading, sortable: Bool = true) {17        self.id = id; self.title = title; self.unit = unit; self.alignment = alignment; self.sortable = sortable18    }19}2021public struct VQTableCell: Sendable, Hashable {22    public var text: String23    /// Numbers are set in the mono face with tabular figures.24    public var numeric: Bool25    /// Sort key for numbers (text cells sort by their text).26    public var sortValue: Double?27    /// Colours the cell with the person's up/down pair (a sign or arrow must be in the text).28    public var direction: VQDirection?29    public init(_ text: String, numeric: Bool = false, sortValue: Double? = nil, direction: VQDirection? = nil) {30        self.text = text; self.numeric = numeric; self.sortValue = sortValue; self.direction = direction31    }32}3334public struct VQTableRow: Identifiable, Sendable, Hashable {35    public var id: String36    public var cells: [VQTableCell]37    public init(id: String, cells: [VQTableCell]) { self.id = id; self.cells = cells }38}3940public struct VQDataTable: View {41    private let label: String42    private let columns: [VQTableColumn]43    private let rows: [VQTableRow]44    private let maxHeight: CGFloat?45    private let onSelect: ((VQTableRow) -> Void)?46    @State private var sortColumn: Int?47    @State private var ascending = true48    @ScaledMetric(relativeTo: .body) private var unit: CGFloat = 149    @Environment(\.vqTheme) private var theme50    @Environment(\.vqStaticRender) private var isStatic5152    /// - Parameters:53    ///   - maxHeight: with a height the body scrolls under a pinned header and rows are created lazily (long tables);54    ///     without one the table takes its natural height (reports, exports).55    public init(_ label: String, columns: [VQTableColumn], rows: [VQTableRow], maxHeight: CGFloat? = nil, onSelect: ((VQTableRow) -> Void)? = nil) {56        self.label = label; self.columns = columns; self.rows = rows; self.maxHeight = maxHeight; self.onSelect = onSelect57    }5859    private var sorted: [VQTableRow] {60        guard let c = sortColumn else { return rows }61        let out = rows.sorted { a, b in62            let x = a.cells.indices.contains(c) ? a.cells[c] : VQTableCell(""), y = b.cells.indices.contains(c) ? b.cells[c] : VQTableCell("")63            switch (x.sortValue, y.sortValue) {64            case let (p?, q?): return p < q65            case (nil, _?): return false          // missing values last66            case (_?, nil): return true67            default: return x.text.localizedStandardCompare(y.text) == .orderedAscending68            }69        }70        return ascending ? out : out.reversed()71    }7273    /// Column widths from the content: mono digits are 0.62 em wide, text about 0.56 em.74    private var widths: [CGFloat] {75        columns.enumerated().map { i, col in76            let header = CGFloat((col.title + (col.unit.map { "  " + $0 + " " } ?? "")).split(separator: " ").map(\.count).max() ?? 0) * 8.2 + 16      // the longest word must fit: headers wrap between words77            var longest: CGFloat = 078            for row in rows.prefix(400) where row.cells.indices.contains(i) {79                let cell = row.cells[i]80                longest = max(longest, CGFloat(cell.text.count) * (cell.numeric ? 7.4 : 6.9))81            }82            return min(320, max(48, max(header, longest) + 4)) * unit83        }84    }8586    private func alignment(_ a: VQTableColumn.Alignment) -> Alignment { a == .leading ? .leading : a == .trailing ? .trailing : .center }8788    private func header(_ widths: [CGFloat]) -> some View {89        HStack(spacing: VQS.s4) {90            ForEach(Array(columns.enumerated()), id: \.offset) { i, col in91                Button {92                    guard col.sortable else { return }93                    if sortColumn == i { if ascending { ascending = false } else { sortColumn = nil; ascending = true } } else { sortColumn = i; ascending = true }94                } label: {95                    HStack(spacing: 3) {96                        if col.alignment == .trailing, sortColumn == i { VQDirectionGlyph(ascending ? .up : .down, size: 6) }97                        Text(col.title + (col.unit.map { " (\($0))" } ?? "")).vqFont(VQTokens.Typography.overline).lineLimit(3).multilineTextAlignment(col.alignment == .trailing ? .trailing : .leading).fixedSize(horizontal: false, vertical: true)98                        if col.alignment != .trailing, sortColumn == i { VQDirectionGlyph(ascending ? .up : .down, size: 6) }99                    }100                    .foregroundStyle(sortColumn == i ? VQP.text1 : VQP.text3)101                    .frame(minWidth: widths[i], maxWidth: col.alignment == .leading ? .infinity : widths[i], alignment: alignment(col.alignment))102                    .contentShape(Rectangle())103                }104                .buttonStyle(.plain)105                .accessibilityLabel(col.title)106                .accessibilityValue(sortColumn == i ? (ascending ? theme.l("sorted ascending") : theme.l("sorted descending")) : "")107                .accessibilityAddTraits(.isHeader)108            }109        }110        .padding(.horizontal, VQS.s3).padding(.vertical, VQS.s2)111        .background(VQP.ink1)112        .overlay(alignment: .bottom) { Rectangle().fill(VQP.lineStrong).frame(height: VQTokens.hairline) }113    }114115    private func line(_ row: VQTableRow, _ widths: [CGFloat]) -> some View {116        HStack(spacing: VQS.s4) {117            ForEach(Array(columns.enumerated()), id: \.offset) { i, col in118                let cell = row.cells.indices.contains(i) ? row.cells[i] : VQTableCell(VQFormat.nullText)119                Text(cell.text)120                    .vqFont(cell.numeric ? VQTokens.Typography.numSm : VQTokens.Typography.caption)121                    .foregroundStyle(cell.direction.map { theme.color($0) } ?? (cell.text == VQFormat.nullText ? VQP.text3 : VQP.text1))122                    .lineLimit(2)123                    .multilineTextAlignment(col.alignment == .trailing ? .trailing : .leading)124                    .frame(minWidth: widths[i], maxWidth: col.alignment == .leading ? .infinity : widths[i], alignment: alignment(col.alignment))125            }126        }127        .padding(.horizontal, VQS.s3).padding(.vertical, 5)128        .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }129        .contentShape(Rectangle())130        .onTapGesture { onSelect?(row) }131        .accessibilityElement(children: .ignore)132        .accessibilityLabel(zip(columns, row.cells).map { "\($0.title) : \($1.text)" }.joined(separator: ", "))133        .accessibilityAddTraits(onSelect == nil ? [] : .isButton)134    }135136    @ViewBuilder private func table(_ widths: [CGFloat]) -> some View {137        if let maxHeight, !isStatic {138            ScrollView(.vertical) {139                LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {140                    Section { ForEach(sorted) { line($0, widths) } } header: { header(widths) }141                }142            }143            .frame(maxHeight: maxHeight)144        } else {145            VStack(alignment: .leading, spacing: 0) {146                header(widths)147                ForEach(sorted) { line($0, widths) }148            }149        }150    }151152    public var body: some View {153        let w = widths154        ViewThatFits(in: .horizontal) {155            table(w)156            if isStatic {157                // an export cannot scroll: narrower columns, cells wrap on two lines158                table(w.map { $0 * 0.82 })159                table(w.map { $0 * 0.66 })160                table(w.map { $0 * 0.5 })161                table(w.map { $0 * 0.5 }).frame(minWidth: 0, maxWidth: .infinity, alignment: .leading).clipped()     // narrower than that: cut on the right162            } else {163                ScrollView(.horizontal) { table(w) }164            }165        }166        .accessibilityElement(children: .contain)167        .accessibilityLabel(label)168    }169}170171public extension VQDataTable {172    /// A `lab/1` table. Numbers are right-aligned; the unit goes in the header for `days` and `count`.173    init(_ table: VQLabResult.Table, rowLimit: Int? = nil, maxHeight: CGFloat? = nil, locale: VQNumberLocale = .frCA) {174        let numericColumns: [Bool] = table.columns.map { col in table.rows.contains { $0[col.key]?.doubleValue != nil } && !table.rows.contains { $0[col.key]?.stringValue != nil } }175        let columns = table.columns.enumerated().map { i, c in176            VQTableColumn(id: c.key, title: c.label, alignment: c.align == "left" ? .leading : c.align == "right" ? .trailing : c.align == "center" ? .center : (numericColumns[i] ? .trailing : .leading))177        }178        let plain = table.yearLikeColumns179        let shown = rowLimit.map { Array(table.rows.prefix($0)) } ?? table.rows180        let rows = shown.enumerated().map { i, row in181            VQTableRow(id: String(i), cells: table.columns.map { c in182                let (text, numeric) = table.cell(row, c, plainInteger: plain.contains(c.key), locale: locale)183                return VQTableCell(text, numeric: numeric, sortValue: row[c.key]?.doubleValue)184            })185        }186        self.init(table.title, columns: columns, rows: rows, maxHeight: maxHeight)187    }188}189
Files main
Menu

Theme