SPB Git

Repository Public MIT

MapsDescriptors.swift 19.7 KB 413 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/MapsDescriptors.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 mapDescriptors: [ComponentDescriptor] {46        [glassMapControls, glassCompass, glassLocationButton, glassMapPin, glassMapPanel]47    }4849    private static func sizeArgument(_ values: InspectorValues) -> String? {50        values.size() == .regular ? nil : "size: .\(values.size().rawValue)"51    }5253    // MARK: Map controls5455    private static var glassMapControls: ComponentDescriptor {56        ComponentDescriptor(57            "glass-map-controls",58            fields: [59                .choice("axis", "Axis", options: [.init("vertical", "Vertical"), .init("horizontal", "Horizontal")]),60                .size(),61                .toggle("canZoomIn", "Can zoom in", default: true),62                .toggle("canZoomOut", "Can zoom out", default: true),63                .toggle("compass", "Compass"),64            ],65            variants: [66                ComponentVariant("horizontal", "Horizontal", ["axis": .choice("horizontal"), "size": .size(.small)]),67                ComponentVariant("compass", "With compass", ["compass": .bool(true)]),68                ComponentVariant("closest", "Closest zoom", ["canZoomIn": .bool(false)]),69            ],70            isComposable: true,71            preview: { values in72                MapControlsPreview(73                    axis: values.choice("axis") == "horizontal" ? .horizontal : .vertical,74                    size: values.size(),75                    canZoomIn: values.bool("canZoomIn"),76                    canZoomOut: values.bool("canZoomOut"),77                    showsCompass: values.bool("compass")78                )79                .id(values)80            },81            snippet: { values in82                var arguments: [String] = []83                if !values.bool("canZoomIn") { arguments.append("canZoomIn: false") }84                if !values.bool("canZoomOut") { arguments.append("canZoomOut: false") }85                if values.choice("axis") == "horizontal" { arguments.append("axis: .horizontal") }86                if let size = sizeArgument(values) { arguments.append(size) }87                var code = "GlassMapControls" + (arguments.isEmpty ? "" : "(\(arguments.joined(separator: ", ")))")88                code += " {\n    // zoom the map in\n} onZoomOut: {\n    // zoom the map out\n}"89                if values.bool("compass") {90                    let compassArguments = (["heading: 40"] + [sizeArgument(values)].compactMap { $0 }).joined(separator: ", ")91                    code += " extra: {\n    GlassCompass(\(compassArguments)) {\n        // rotate the map back to north\n    }\n}"92                }93                return code94            }95        )96    }9798    // MARK: Compass99100    private static var glassCompass: ComponentDescriptor {101        ComponentDescriptor(102            "glass-compass",103            fields: [104                .toggle("available", "Heading available", default: true),105                .number("heading", "Heading", in: 0...359, default: 315),106                .size(),107            ],108            variants: [109                ComponentVariant("unavailable", "Unavailable", ["available": .bool(false)]),110                ComponentVariant("north", "North", ["heading": .number(0)]),111                ComponentVariant("large", "Large", ["size": .size(.large), "heading": .number(90)]),112            ],113            isComposable: true,114            preview: { values in115                MapPreviewState(values.number("heading")) { heading in116                    MapPlaceholder(heading: values.bool("available") ? heading.wrappedValue : 0)117                        .overlay(alignment: .topTrailing) {118                            GlassCompass(heading: values.bool("available") ? heading.wrappedValue : nil, size: values.size()) {119                                heading.wrappedValue = 0120                            }121                            .padding()122                        }123                }124                .id(values)125            },126            snippet: { values in127                var arguments = ["heading: \(values.bool("available") ? SwiftLiteral.number(values.number("heading")) : "nil")"]128                if let size = sizeArgument(values) { arguments.append(size) }129                return "GlassCompass(\(arguments.joined(separator: ", "))) {\n    // rotate the map back to north\n}"130            }131        )132    }133134    // MARK: Location button135136    private static var glassLocationButton: ComponentDescriptor {137        ComponentDescriptor(138            "glass-location-button",139            fields: [140                .choice("state", "State", options: [141                    .init("idle", "Idle"), .init("locating", "Locating"), .init("following", "Following"),142                    .init("denied", "Denied"), .init("unavailable", "Unavailable"),143                ]),144                .text("hint", "Hint", default: "", maxLength: 120),145                .size(),146            ],147            variants: [148                ComponentVariant("locating", "Locating", ["state": .choice("locating")]),149                ComponentVariant("following", "Following", ["state": .choice("following")]),150                ComponentVariant("denied", "Denied", ["state": .choice("denied"), "hint": .text("Location access was refused. Opens Settings.")]),151                ComponentVariant("unavailable", "Unavailable", ["state": .choice("unavailable"), "hint": .text("Location services are off on this device.")]),152            ],153            isComposable: true,154            preview: { values in155                MapPlaceholder()156                    .overlay(alignment: .bottomTrailing) {157                        // The state comes from the inspector: no permission is requested, no position is read.158                        GlassLocationButton(159                            state: GlassLocationState(rawValue: values.choice("state")) ?? .idle,160                            hint: values.text("hint").isEmpty ? nil : values.text("hint"),161                            size: values.size()162                        ) {}163                        .padding()164                    }165            },166            snippet: { values in167                var arguments = ["state: \(SwiftLiteral.enumCase(values.choice("state"), fallback: "idle"))"]168                if !values.text("hint").isEmpty { arguments.append("hint: \(SwiftLiteral.string(values.text("hint")))") }169                if let size = sizeArgument(values) { arguments.append(size) }170                return "GlassLocationButton(\(arguments.joined(separator: ", "))) {\n    // request the permission, start updates or open Settings\n}"171            }172        )173    }174175    // MARK: Map pin176177    private static let pinTints: [GlassColorToken] = [.primary, .secondary, .accent, .success, .warning, .destructive]178179    private static func pinTint(_ values: InspectorValues) -> GlassColorToken {180        pinTints.first { $0.rawValue == values.choice("tint") } ?? .primary181    }182183    private static var glassMapPin: ComponentDescriptor {184        ComponentDescriptor(185            "glass-map-pin",186            fields: [187                .choice("content", "Content", options: [.init("symbol", "Symbol"), .init("text", "Text"), .init("cluster", "Cluster")]),188                .text("symbol", "Symbol", default: "cup.and.saucer.fill", maxLength: 40),189                .text("text", "Marker text", default: "$$", maxLength: 8),190                .number("count", "Cluster count", in: 2...500, default: 12),191                .text("title", "Title", default: "Café Exemple", maxLength: 60),192                .choice("tint", "Tint", options: pinTints.map { .init($0.rawValue, $0.rawValue.prefix(1).uppercased() + $0.rawValue.dropFirst()) }),193                .toggle("selected", "Selected"),194            ],195            variants: [196                ComponentVariant("selected", "Selected", ["selected": .bool(true)]),197                ComponentVariant("text", "Text", ["content": .choice("text"), "title": .text("Mid-range"), "tint": .choice("accent")]),198                ComponentVariant("cluster", "Cluster", ["content": .choice("cluster"), "count": .number(132), "title": .text("Downtown"), "tint": .choice("secondary")]),199            ],200            isComposable: true,201            preview: { values in202                let title = values.text("title").isEmpty ? nil : values.text("title")203                MapPlaceholder()204                    .overlay {205                        switch values.choice("content") {206                        case "cluster":207                            GlassMapPin(clusterCount: Int(values.number("count")), title: title, tint: pinTint(values), isSelected: values.bool("selected"))208                        case "text":209                            GlassMapPin(.text(values.text("text")), title: title, tint: pinTint(values), isSelected: values.bool("selected"))210                        default:211                            GlassMapPin(.symbol(values.text("symbol").isEmpty ? "mappin" : values.text("symbol")), title: title, tint: pinTint(values), isSelected: values.bool("selected"))212                        }213                    }214            },215            snippet: { values in216                var arguments: [String]217                var defaultTint = GlassColorToken.primary218                switch values.choice("content") {219                case "cluster":220                    arguments = ["clusterCount: \(SwiftLiteral.number(values.number("count")))"]221                    defaultTint = .secondary222                case "text":223                    arguments = [".text(\(SwiftLiteral.string(values.text("text"))))"]224                default:225                    arguments = [".symbol(\(SwiftLiteral.string(values.text("symbol").isEmpty ? "mappin" : values.text("symbol"))))"]226                }227                if !values.text("title").isEmpty { arguments.append("title: \(SwiftLiteral.string(values.text("title")))") }228                if pinTint(values) != defaultTint { arguments.append("tint: .\(pinTint(values).rawValue)") }229                if values.bool("selected") { arguments.append("isSelected: true") }230                return "GlassMapPin(\(arguments.joined(separator: ", ")))"231            }232        )233    }234235    // MARK: Map panel236237    /// Fictitious places.238    private static let sampleResults = [239        GlassMapResult(id: "1", title: "Café Exemple", subtitle: "Sample data · 120 m", systemImage: "cup.and.saucer"),240        GlassMapResult(id: "2", title: "Bibliothèque fictive", subtitle: "Sample data · 350 m", systemImage: "books.vertical"),241        GlassMapResult(id: "3", title: "Parc d’essai", subtitle: "Sample data · 1.2 km", systemImage: "tree"),242        GlassMapResult(id: "4", title: "Musée fictif", subtitle: "Sample data · 2 km", systemImage: "building.columns"),243        GlassMapResult(id: "5", title: "Gare d’exemple", subtitle: "Sample data · 2.4 km", systemImage: "tram"),244    ]245246    private static var glassMapPanel: ComponentDescriptor {247        ComponentDescriptor(248            "glass-map-panel",249            fields: [250                .text("title", "Title", default: "Nearby", maxLength: 40),251                .toggle("presented", "Presented", default: true),252                .choice("detent", "Detent", options: [.init("peek", "Peek"), .init("half", "Half"), .init("full", "Full")], default: "half"),253                .toggle("dismissable", "Dismissable", default: true),254                .number("results", "Results", in: 0...5, default: 3),255            ],256            variants: [257                ComponentVariant("collapsed", "Collapsed", ["detent": .choice("peek")]),258                ComponentVariant("pinned", "Not dismissable", ["dismissable": .bool(false), "detent": .choice("full"), "results": .number(5)]),259                ComponentVariant("empty", "No results", ["results": .number(0)]),260            ],261            preview: { values in262                MapPanelPreview(263                    title: values.text("title"),264                    isPresented: values.bool("presented"),265                    detent: GlassMapPanelDetent(rawValue: values.choice("detent")) ?? .half,266                    isDismissable: values.bool("dismissable"),267                    results: Array(sampleResults.prefix(Int(values.number("results"))))268                )269                .id(values)270            },271            snippet: { values in272                var arguments = [273                    SwiftLiteral.string(values.text("title")),274                    "isPresented: .constant(\(SwiftLiteral.bool(values.bool("presented"))))",275                    "detent: .constant(\(SwiftLiteral.enumCase(values.choice("detent"), fallback: "half")))",276                ]277                if !values.bool("dismissable") { arguments.append("isDismissable: false") }278                let rows = sampleResults.prefix(Int(values.number("results"))).map {279                    "        GlassMapResult(id: \(SwiftLiteral.string($0.id)), title: \(SwiftLiteral.string($0.title)), subtitle: \(SwiftLiteral.string($0.subtitle ?? "")), systemImage: \(SwiftLiteral.string($0.systemImage))),"280                }281                let results = rows.isEmpty ? "[]" : "[\n\(rows.joined(separator: "\n"))\n    ]"282                return """283                GlassMapPanel(\(arguments.joined(separator: ", "))) {284                    Color.teal.opacity(0.2) // replace with your map view285                } content: {286                    GlassMapResultList(results: \(results)) { _ in287                        // select the result on the map288                    }289                }290                """291            }292        )293    }294}295296// MARK: - Preview support297298/// Holds a value the previewed component edits through a binding.299private struct MapPreviewState<Value, Content: View>: View {300    @State private var value: Value301    private let content: (Binding<Value>) -> Content302303    init(_ initialValue: Value, @ViewBuilder content: @escaping (Binding<Value>) -> Content) {304        _value = State(initialValue: initialValue)305        self.content = content306    }307308    var body: some View { content($value) }309}310311/// A drawn stand-in for a map: no MapKit, no tiles, no network and no location access. A grid of "streets"312/// that rotates and scales with the injected heading and zoom.313private struct MapPlaceholder: View {314    var heading: Double = 0315    var zoom: Double = 1316    var height: CGFloat = 240317318    var body: some View {319        Canvas { context, size in320            context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(Color(red: 0.86, green: 0.9, blue: 0.84)))321            context.translateBy(x: size.width / 2, y: size.height / 2)322            context.rotate(by: .degrees(-heading))323            let step = 56 * zoom324            let reach = max(size.width, size.height)325            var streets = Path()326            var offset = -reach327            while offset <= reach {328                streets.move(to: CGPoint(x: offset, y: -reach))329                streets.addLine(to: CGPoint(x: offset, y: reach))330                streets.move(to: CGPoint(x: -reach, y: offset))331                streets.addLine(to: CGPoint(x: reach, y: offset))332                offset += step333            }334            context.stroke(streets, with: .color(.white), lineWidth: 6 * min(zoom, 2))335            let park = CGRect(x: step * 0.15, y: -step * 1.85, width: step * 1.7, height: step * 0.7)336            context.fill(Path(roundedRect: park, cornerRadius: 6), with: .color(Color(red: 0.62, green: 0.8, blue: 0.6)))337            let water = CGRect(x: -step * 2.85, y: step * 1.15, width: step * 1.7, height: step * 1.7)338            context.fill(Path(ellipseIn: water), with: .color(Color(red: 0.6, green: 0.78, blue: 0.92)))339        }340        .overlay(alignment: .bottomLeading) {341            Text(verbatim: L("Sample data · drawn placeholder, not a real map"))342                .font(.caption2)343                .padding(6)344                .background(.background.opacity(0.8), in: RoundedRectangle(cornerRadius: 6))345                .padding(8)346        }347        .frame(maxWidth: 520)348        .frame(height: height)349        .clipShape(RoundedRectangle(cornerRadius: 12))350        .accessibilityElement(children: .contain)351        .accessibilityLabel(Text(verbatim: L("Sample map placeholder")))352    }353}354355/// Zoom buttons that scale the placeholder, within the limits set in the inspector.356private struct MapControlsPreview: View {357    let axis: Axis358    let size: GlassControlSize359    let canZoomIn: Bool360    let canZoomOut: Bool361    let showsCompass: Bool362    @State private var level = 2363    @State private var heading = 40.0364365    var body: some View {366        MapPlaceholder(heading: showsCompass ? heading : 0, zoom: pow(1.5, Double(level - 2)))367            .overlay(alignment: .topTrailing) {368                GlassMapControls(canZoomIn: canZoomIn && level < 4, canZoomOut: canZoomOut && level > 0, axis: axis, size: size) {369                    level = min(level + 1, 4)370                } onZoomOut: {371                    level = max(level - 1, 0)372                } extra: {373                    if showsCompass {374                        GlassCompass(heading: heading, size: size) { heading = 0 }375                    }376                }377                .padding()378            }379    }380}381382/// The panel over the placeholder. The side form is forced so that the preview stays inside its frame: on a383/// compact width the component would present a system sheet over the whole Studio window.384private struct MapPanelPreview: View {385    let title: String386    let isDismissable: Bool387    let results: [GlassMapResult]388    @State private var isPresented: Bool389    @State private var detent: GlassMapPanelDetent390    @State private var selection: String?391392    init(title: String, isPresented: Bool, detent: GlassMapPanelDetent, isDismissable: Bool, results: [GlassMapResult]) {393        self.title = title394        self.isDismissable = isDismissable395        self.results = results396        _isPresented = State(initialValue: isPresented)397        _detent = State(initialValue: detent)398    }399400    var body: some View {401        GlassMapPanel(LocalizedStringKey(title), isPresented: $isPresented, detent: $detent, isDismissable: isDismissable) {402            MapPlaceholder(height: 420)403        } content: {404            GlassMapResultList(results: results, selection: selection) { result in405                selection = result.id406            }407        }408        .environment(\.horizontalSizeClass, .regular)409        .frame(maxWidth: 520)410        .frame(height: 420)411    }412}413
Files main
Menu

Theme