SPB Git

Repository Public MIT

DataDescriptors.swift 20.0 KB 354 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/DataDescriptors.swift8// Module           : GlassStudio9// 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 SwiftUI42import SPGlassKit4344extension ComponentCatalog {45    static var dataDescriptors: [ComponentDescriptor] {46        [glassTable, glassChart, glassMetricCard, glassDataGrid, glassTimeline]47    }4849    // MARK: GlassTable5051    /// Fictitious stations. Rows are chart points because a snippet cannot declare a row type of its own52    /// inside a view body; a host passes its own `Identifiable` model.53    private static let stations: [(id: String, name: String, line: String, riders: Double)] = [54        ("s1", "Harbour Square", "Blue", 48_200),55        ("s2", "Élan–Université", "Green", 31_750),56        ("s3", "North Mills", "Blue", 9_640),57        ("s4", "Parc des Érables", "Orange", 22_310),58        ("s5", "Old Foundry", "Green", 9_640),59    ]6061    private static func tableSort(_ values: InspectorValues) -> GlassTableSort? {62        values.choice("sort") == "none" ? nil : GlassTableSort(columnID: values.choice("sort"), order: values.bool("descending") ? .reverse : .forward)63    }6465    private static var glassTable: ComponentDescriptor {66        ComponentDescriptor(67            "glass-table",68            fields: [69                .number("rows", "Rows", in: 0...5, default: 5),70                .choice("sort", "Sorted by", options: [.init("none", "Unsorted"), .init("name", "Station"), .init("riders", "Daily riders")]),71                .toggle("descending", "Descending"),72                .choice("selection", "Selection", options: [.init("none", "None"), .init("single", "Single"), .init("multiple", "Multiple")]),73                .text("emptyTitle", "Empty state title", default: "No station", maxLength: 60),74            ],75            variants: [76                ComponentVariant("sorted", "Sorted", ["sort": .choice("riders"), "descending": .bool(true)]),77                ComponentVariant("selection", "Multiple selection", ["selection": .choice("multiple")]),78                ComponentVariant("empty", "Empty", ["rows": .number(0)]),79            ],80            preview: { values in81                let count = Int(values.number("rows"))82                TablePreview(83                    rows: stations.prefix(count).map { GlassChartPoint(id: $0.id, label: $0.name, value: $0.riders, series: $0.line) },84                    sort: tableSort(values),85                    selectionMode: values.choice("selection"),86                    selected: count >= 2 ? "s2" : nil,87                    emptyTitle: values.text("emptyTitle")88                )89                .id(values)90            },91            snippet: { values in92                let count = Int(values.number("rows"))93                let rows = stations.prefix(count).map {94                    "        GlassChartPoint(id: \(SwiftLiteral.string($0.id)), label: \(SwiftLiteral.string($0.name)), value: \(SwiftLiteral.number($0.riders)), series: \(SwiftLiteral.string($0.line))),"95                }.joined(separator: "\n")96                var arguments = [97                    count == 0 ? "    [GlassChartPoint](),": "    [\n\(rows)\n    ],",98                    "    columns: [\n        GlassTableColumn(\"Station\", id: \"name\") { $0.x.label() },\n        GlassTableColumn(\"Line\", id: \"line\") { $0.series ?? \"\" },\n        GlassTableColumn(\"Daily riders\", id: \"riders\", sortingBy: { $0.value }) { $0.value.formatted(.number) },\n    ]",99                ]100                if let sort = tableSort(values) {101                    let order = sort.order == .reverse ? ", order: .reverse" : ""102                    arguments.append("    sort: .constant(GlassTableSort(columnID: \(SwiftLiteral.string(sort.columnID))\(order)))")103                }104                let selected = count >= 2105                switch values.choice("selection") {106                case "single": arguments.append("    selection: .single(.constant(\(selected ? "\"s2\"" : "nil")))")107                case "multiple": arguments.append("    selection: .multiple(.constant(\(selected ? "[\"s2\"]" : "[]")))")108                default: break109                }110                if !values.text("emptyTitle").isEmpty { arguments.append("    emptyTitle: \(SwiftLiteral.string(values.text("emptyTitle")))") }111                let head = arguments.removeFirst()112                return "// Fictitious rows: pass your own Identifiable values. Bind sort and selection to your own @State.\nGlassTable(\n\(head)\n\(arguments.joined(separator: ",\n"))\n)\n.frame(minHeight: 320)"113            }114        )115    }116117    // MARK: GlassChart118119    private static let chartMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]120    private static let chartNorth: [Double] = [42, 48, 55, 61, 58, 70]121    private static let chartSouth: [Double] = [65, 60, 57, 52, 49, 44]122123    /// Fictitious energy production: (month, value, series).124    private static func chartSample(_ values: InspectorValues) -> [(label: String, value: Double, series: String?)] {125        let count = Int(values.number("points"))126        let twoSeries = values.bool("twoSeries")127        let north = zip(chartMonths, chartNorth).prefix(count).map { (label: $0, value: $1, series: twoSeries ? "North" : String?.none) }128        let south = zip(chartMonths, chartSouth).prefix(count).map { (label: $0, value: $1, series: String?.some("South")) }129        return twoSeries ? north + south : north130    }131132    private static var glassChart: ComponentDescriptor {133        ComponentDescriptor(134            "glass-chart",135            fields: [136                .text("title", "Title", default: "Energy produced", maxLength: 60),137                .choice("kind", "Mark", options: [.init("line", "Line"), .init("bar", "Bar"), .init("area", "Area")]),138                .number("points", "Points", in: 0...6, default: 6),139                .toggle("twoSeries", "Two series"),140                .text("unit", "Unit", default: "MWh", maxLength: 8),141                .toggle("summary", "Show summary", default: true),142            ],143            variants: [144                ComponentVariant("bar", "Bar", ["kind": .choice("bar")]),145                ComponentVariant("area", "Area", ["kind": .choice("area")]),146                ComponentVariant("series", "Two series", ["twoSeries": .bool(true)]),147                ComponentVariant("empty", "Empty", ["points": .number(0), "title": .text("Nothing measured yet")]),148            ],149            isComposable: true,150            preview: { values in151                VStack(alignment: .leading, spacing: 8) {152                    GlassChart(153                        LocalizedStringKey(values.text("title")),154                        points: chartSample(values).map { GlassChartPoint(label: $0.label, value: $0.value, series: $0.series) },155                        kind: GlassChartKind(rawValue: values.choice("kind")) ?? .line,156                        xAxisTitle: L("Month"),157                        yAxisTitle: L("Energy"),158                        unit: values.text("unit").isEmpty ? nil : values.text("unit"),159                        showsSummary: values.bool("summary")160                    )161                    Text(verbatim: L("Fictitious sample data")).font(.caption).foregroundStyle(.secondary)162                }163            },164            snippet: { values in165                let sample = chartSample(values)166                let points = sample.map { point in167                    "    GlassChartPoint(label: \(SwiftLiteral.string(point.label)), value: \(SwiftLiteral.number(point.value))" + (point.series.map { ", series: \(SwiftLiteral.string($0))" } ?? "") + "),"168                }.joined(separator: "\n")169                var arguments = [sample.isEmpty ? "points: []" : "points: [\n\(points)\n]"]170                if values.choice("kind") != "line" { arguments.append("kind: \(SwiftLiteral.enumCase(values.choice("kind"), fallback: "line"))") }171                arguments += ["xAxisTitle: \"Month\"", "yAxisTitle: \"Energy\""]172                if !values.text("unit").isEmpty { arguments.append("unit: \(SwiftLiteral.string(values.text("unit")))") }173                if !values.bool("summary") { arguments.append("showsSummary: false") }174                return "GlassChart(\(SwiftLiteral.string(values.text("title"))), \(arguments.joined(separator: ", ")))"175            }176        )177    }178179    // MARK: GlassMetricCard180181    private static let metricPeriod = "vs last week"182    private static let metricFailure = "The report could not be loaded."183184    private static var glassMetricCard: ComponentDescriptor {185        ComponentDescriptor(186            "glass-metric-card",187            fields: [188                .text("title", "Title", default: "Response time", maxLength: 40),189                .choice("state", "State", options: [.init("loaded", "Loaded"), .init("loading", "Loading"), .init("empty", "Empty"), .init("idle", "Idle"), .init("failed", "Failed")]),190                .number("value", "Value", in: 0...1000, default: 182),191                .text("unit", "Unit", default: "ms", maxLength: 8),192                .number("change", "Change (%)", in: -50...50, step: 0.5, default: -6),193                .choice("tone", "Tone", options: [.init("neutral", "Neutral"), .init("positiveIsGood", "Up is good"), .init("negativeIsGood", "Down is good")], default: "negativeIsGood"),194            ],195            variants: [196                ComponentVariant("growth", "Up is good", ["title": .text("Monthly revenue"), "value": .number(482), "unit": .text("k$"), "change": .number(4), "tone": .choice("positiveIsGood")]),197                ComponentVariant("loading", "Loading", ["state": .choice("loading")]),198                ComponentVariant("empty", "Empty", ["state": .choice("empty")]),199                ComponentVariant("failed", "Failed", ["state": .choice("failed")]),200            ],201            isComposable: true,202            preview: { values in203                let state: GlassLoadState<GlassMetric> = switch values.choice("state") {204                case "loading": .loading205                case "empty": .empty206                case "idle": .idle207                case "failed": .failed(message: L(metricFailure))208                default: .loaded(GlassMetric(209                    value: values.number("value"),210                    unit: values.text("unit").isEmpty ? nil : values.text("unit"),211                    change: values.number("change") / 100,212                    period: L(metricPeriod),213                    tone: GlassMetricTone(rawValue: values.choice("tone")) ?? .neutral214                ))215                }216                MetricCardPreview(title: values.text("title"), state: state)217                    .id(values)218            },219            snippet: { values in220                let title = SwiftLiteral.string(values.text("title"))221                switch values.choice("state") {222                case "loading", "empty", "idle":223                    return "GlassMetricCard(\(title), state: \(SwiftLiteral.enumCase(values.choice("state"), fallback: "idle")))"224                case "failed":225                    return "GlassMetricCard(\(title), state: .failed(message: \(SwiftLiteral.string(metricFailure))), onRetry: { })"226                default:227                    var metric = ["value: \(SwiftLiteral.number(values.number("value")))"]228                    if !values.text("unit").isEmpty { metric.append("unit: \(SwiftLiteral.string(values.text("unit")))") }229                    metric += ["change: \(SwiftLiteral.number(values.number("change") / 100))", "period: \(SwiftLiteral.string(metricPeriod))"]230                    if values.choice("tone") != "neutral" { metric.append("tone: \(SwiftLiteral.enumCase(values.choice("tone"), fallback: "neutral"))") }231                    return "GlassMetricCard(\(title), state: .loaded(GlassMetric(\(metric.joined(separator: ", ")))))"232                }233            }234        )235    }236237    // MARK: GlassDataGrid238239    private static let gridSpacings: [GlassSpacingStep] = [.xs, .sm, .md, .lg]240241    private static var glassDataGrid: ComponentDescriptor {242        ComponentDescriptor(243            "glass-data-grid",244            fields: [245                .number("items", "Items", in: 0...24, default: 12),246                .choice("layout", "Layout", options: [.init("adaptive", "Adaptive"), .init("fixed", "Fixed columns")]),247                .number("columns", "Columns", in: 2...5, default: 3),248                .choice("spacing", "Spacing", options: gridSpacings.map { .init($0.rawValue, $0.rawValue) }, default: "sm"),249                .toggle("selectable", "Selectable"),250            ],251            variants: [252                ComponentVariant("fixed", "Fixed columns", ["layout": .choice("fixed")]),253                ComponentVariant("selectable", "Selectable", ["selectable": .bool(true)]),254                ComponentVariant("empty", "Empty", ["items": .number(0)]),255            ],256            preview: { values in257                DataGridPreview(258                    count: Int(values.number("items")),259                    layout: values.choice("layout") == "fixed" ? .fixed(Int(values.number("columns"))) : .adaptive(minimum: 140),260                    spacing: GlassSpacingStep(rawValue: values.choice("spacing")) ?? .sm,261                    selectable: values.bool("selectable")262                )263                .id(values)264            },265            snippet: { values in266                var arguments = ["    (0..<\(SwiftLiteral.number(values.number("items")))).map { GlassChartPoint(label: \"Sample \\($0 + 1)\", value: Double($0 * 37 % 100)) }"]267                if values.choice("layout") == "fixed" { arguments.append("    layout: .fixed(\(SwiftLiteral.number(values.number("columns"))))") }268                if values.choice("spacing") != "sm" { arguments.append("    spacing: \(SwiftLiteral.enumCase(values.choice("spacing"), fallback: "sm"))") }269                if values.bool("selectable") { arguments.append("    selection: .constant([])") }270                arguments.append("    emptyTitle: \"No sample\"")271                let selectable = values.bool("selectable")272                let cell = [273                    selectable ? "{ sample, isSelected in" : "{ sample in",274                    "    VStack(alignment: .leading, spacing: 4) {",275                    "        Text(verbatim: sample.x.label()).font(.headline)",276                    "        Text(verbatim: \"\\(Int(sample.value)) %\").font(.callout.monospacedDigit()).foregroundStyle(.secondary)",277                    selectable ? "        Image(systemName: isSelected ? \"checkmark.circle.fill\" : \"circle\")" : nil,278                    "    }",279                    "    .frame(maxWidth: .infinity, alignment: .leading)",280                    "    .padding(12)",281                    "    .background(.quaternary, in: RoundedRectangle(cornerRadius: 12, style: .continuous))",282                    "}",283                ].compactMap { $0 }.joined(separator: "\n")284                let hint = "// Generated sample cells: pass your own Identifiable values." + (selectable ? " Bind selection to your own @State." : "")285                return "\(hint)\nGlassDataGrid(\n\(arguments.joined(separator: ",\n"))\n) \(cell)\n.frame(minHeight: 320)"286            }287        )288    }289290    // MARK: GlassTimeline291292    /// A fixed instant, so that the sample is reproducible.293    private static let timelineStart = 1_780_300_800.0294295    /// Fictitious delivery log: hours after the start, title, detail, symbol.296    private static let timelineSample: [(id: String, hours: Double, title: String, detail: String?, symbol: String)] = [297        ("ordered", 0, "Order placed", "Order A-1042, three items", "cart"),298        ("paid", 0.5, "Payment confirmed", nil, "creditcard"),299        ("packed", 21, "Parcel packed", "Warehouse 4, aisle 12", "shippingbox"),300        ("shipped", 27.5, "Handed to the carrier", nil, "truck.box"),301        ("delivered", 76, "Delivered", "Left at the front desk", "checkmark.circle"),302    ]303304    private static var glassTimeline: ComponentDescriptor {305        ComponentDescriptor(306            "glass-timeline",307            fields: [308                .number("events", "Events", in: 0...5, default: 4),309                .choice("order", "Order", options: [.init("ascending", "Oldest first"), .init("descending", "Newest first")]),310                .toggle("details", "Show details", default: true),311                .toggle("symbols", "Show symbols", default: true),312                .text("emptyTitle", "Empty state title", default: "Nothing has happened yet", maxLength: 60),313            ],314            variants: [315                ComponentVariant("newest", "Newest first", ["order": .choice("descending")]),316                ComponentVariant("titles", "Titles only", ["details": .bool(false), "symbols": .bool(false)]),317                ComponentVariant("empty", "Empty", ["events": .number(0)]),318            ],319            isComposable: true,320            preview: { values in321                GlassTimeline(322                    timelineSample.prefix(Int(values.number("events"))).map {323                        GlassTimelineEvent(324                            id: $0.id,325                            date: Date(timeIntervalSince1970: timelineStart + $0.hours * 3600),326                            title: L($0.title),327                            detail: values.bool("details") ? $0.detail.map(L) : nil,328                            systemImage: values.bool("symbols") ? $0.symbol : nil329                        )330                    },331                    order: values.choice("order") == "descending" ? .descending : .ascending,332                    emptyTitle: values.text("emptyTitle").isEmpty ? nil : LocalizedStringKey(values.text("emptyTitle"))333                )334            },335            snippet: { values in336                let events = timelineSample.prefix(Int(values.number("events"))).map { event in337                    var arguments = [338                        "id: \(SwiftLiteral.string(event.id))",339                        "date: Date(timeIntervalSince1970: \(SwiftLiteral.number(timelineStart + event.hours * 3600)))",340                        "title: \(SwiftLiteral.string(event.title))",341                    ]342                    if values.bool("details"), let detail = event.detail { arguments.append("detail: \(SwiftLiteral.string(detail))") }343                    if values.bool("symbols") { arguments.append("systemImage: \(SwiftLiteral.string(event.symbol))") }344                    return "    GlassTimelineEvent(\(arguments.joined(separator: ", "))),"345                }.joined(separator: "\n")346                var arguments = [events.isEmpty ? "[]" : "[\n\(events)\n]"]347                if values.choice("order") == "descending" { arguments.append("order: .descending") }348                if !values.text("emptyTitle").isEmpty { arguments.append("emptyTitle: \(SwiftLiteral.string(values.text("emptyTitle")))") }349                return "GlassTimeline(\(arguments.joined(separator: ", ")))"350            }351        )352    }353}354
Files main
Menu

Theme