SPB Git

Repository Public MIT

GlassMapPanel.swift 19.9 KB 457 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMaps/Maps/GlassMapPanel.swift8// Module           : SPGlassMaps9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0313//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 SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects46import SPGlassComponents4748/// How far a ``GlassMapPanel`` is extended.49public enum GlassMapPanelDetent: String, CaseIterable, Sendable {50    /// Only the title is visible; the map is almost entirely free.51    case peek52    /// About half of the height.53    case half54    /// The whole height.55    case full56}5758/// The form a ``GlassMapPanel`` takes.59public enum GlassMapPanelForm: Equatable, Sendable {60    /// A native sheet with detents, for compact widths (iPhone, narrow iPad windows).61    case sheet62    /// A glass panel floating over the leading edge of the map, for regular widths and macOS.63    case side64    /// A glass panel docked to the bottom of the map's own bounds, with a grabber and the three detents.65    /// For a map that takes only part of the screen (a column, a card, a widget-sized area), where a system66    /// sheet would cover content that is not the map. Never chosen automatically: ask for it with `form:`.67    case docked68}6970/// Layout decisions of ``GlassMapPanel``, separated from the view so that they can be tested.71public enum GlassMapPanelLayout {72    /// Height of the `peek` detent in points.73    public static let peekHeight: CGFloat = 967475    /// The sheet form for compact widths on iOS and iPadOS, the side form everywhere else.76    public static func form(isCompactWidth: Bool, platform: GlassPlatform = .current) -> GlassMapPanelForm {77        platform != .macOS && isCompactWidth ? .sheet : .side78    }7980    /// The largest detent at which the map behind the sheet stays interactive.81    public static let largestInteractiveDetent: GlassMapPanelDetent = .half8283    /// Whether the map behind the sheet receives touches at `detent`.84    public static func isMapInteractive(at detent: GlassMapPanelDetent) -> Bool {85        detent != .full86    }8788    /// Width of the side panel for a container width: about a third, between 280 and 380 points, and never89    /// wider than the container minus its margins.90    public static func sideWidth(container: CGFloat, margin: CGFloat = 16) -> CGFloat {91        let preferred = min(max(container * 0.34, 280), 380)92        return max(min(preferred, container - 2 * margin), 0)93    }9495    /// The detent after toggling the side panel's collapse button.96    public static func toggled(_ detent: GlassMapPanelDetent) -> GlassMapPanelDetent {97        detent == .peek ? .half : .peek98    }99100    /// Height of the docked panel in a container: the peek height, 55 % of the container, or the container101    /// less a top margin. Never above the container less its margins, never negative.102    public static func dockedHeight(_ detent: GlassMapPanelDetent, container: CGFloat, margin: CGFloat = 8) -> CGFloat {103        let available = max(container - 2 * margin, 0)104        switch detent {105        case .peek: return min(peekHeight, available)106        case .half: return min(max(container * 0.55, peekHeight), available)107        case .full: return max(available - 3 * margin, min(peekHeight, available))108        }109    }110111    /// The detent after dragging the grabber of the docked panel by `translation` points (negative is up).112    /// Short drags leave the detent unchanged.113    public static func detent(after detent: GlassMapPanelDetent, dragTranslation translation: CGFloat, threshold: CGFloat = 36) -> GlassMapPanelDetent {114        let order = GlassMapPanelDetent.allCases115        guard let index = order.firstIndex(of: detent), translation.isFinite, abs(translation) >= threshold else { return detent }116        return order[min(max(index + (translation < 0 ? 1 : -1), 0), order.count - 1)]117    }118119    static func presentationDetent(_ detent: GlassMapPanelDetent) -> PresentationDetent {120        switch detent {121        case .peek: .height(peekHeight)122        case .half: .medium123        case .full: .large124        }125    }126127    static func detent(for presentationDetent: PresentationDetent) -> GlassMapPanelDetent {128        GlassMapPanelDetent.allCases.first { self.presentationDetent($0) == presentationDetent } ?? .half129    }130}131132/// A results panel over a map that leaves the map interactive.133///134/// ```swift135/// GlassMapPanel("Nearby", isPresented: $showsResults, detent: $detent) {136///     MapView(engine: engine)137/// } content: {138///     GlassMapResultList(results: results, selection: selection) { result in select(result) }139/// }140/// ```141///142/// On compact widths (iPhone) the panel is the system sheet with three detents; the map stays interactive up to143/// the half detent through `presentationBackgroundInteraction`. On regular widths and on macOS it is a glass144/// panel floating over the leading edge of the map, which can be collapsed to its title. With145/// `form: .docked` it is a glass panel at the bottom of the map's own bounds, with a grabber that moves it146/// between the three detents — for maps that take only part of the screen.147public struct GlassMapPanel<MapContent: View, PanelContent: View>: View {148    @GlassThemed private var theme149    @GlassAccessibility private var accessibility150    @Environment(\.horizontalSizeClass) private var horizontalSizeClass151    private let title: Text152    @Binding private var isPresented: Bool153    @Binding private var detent: GlassMapPanelDetent154    private let isDismissable: Bool155    private let requestedForm: GlassMapPanelForm?156    private let map: MapContent157    private let content: PanelContent158159    /// - Parameters:160    ///   - title: heading of the panel.161    ///   - isPresented: whether the panel is shown.162    ///   - detent: how far the panel is extended; the user changes it by dragging the sheet or the grabber,163    ///     or with the collapse button of the side panel.164    ///   - isDismissable: when false the sheet cannot be swiped away and the panel has no close button.165    ///   - form: forces a form. `nil` (default) picks the sheet on compact widths and the side panel elsewhere.166    ///   - map: the map (any view) the panel sits over.167    ///   - content: the search field, results or details. It scrolls itself if it needs to.168    public init(169        _ title: LocalizedStringKey,170        isPresented: Binding<Bool>,171        detent: Binding<GlassMapPanelDetent>,172        isDismissable: Bool = true,173        form: GlassMapPanelForm? = nil,174        @ViewBuilder map: () -> MapContent,175        @ViewBuilder content: () -> PanelContent176    ) {177        self.title = Text(title)178        _isPresented = isPresented179        _detent = detent180        self.isDismissable = isDismissable181        requestedForm = form182        self.map = map()183        self.content = content()184    }185186    public var body: some View {187        switch requestedForm ?? GlassMapPanelLayout.form(isCompactWidth: horizontalSizeClass == .compact) {188        case .sheet:189            map.sheet(isPresented: $isPresented) { sheetBody }190        case .side:191            GeometryReader { proxy in192                map.overlay(alignment: .topLeading) {193                    if isPresented {194                        sideBody195                            .frame(width: GlassMapPanelLayout.sideWidth(container: proxy.size.width, margin: theme.spacing.md))196                            .frame(maxHeight: detent == .full ? .infinity : nil, alignment: .top)197                            .padding(theme.spacing.md)198                    }199                }200            }201        case .docked:202            GeometryReader { proxy in203                map.overlay(alignment: .bottom) {204                    if isPresented {205                        dockedBody206                            .frame(height: GlassMapPanelLayout.dockedHeight(detent, container: proxy.size.height, margin: theme.spacing.xs), alignment: .top)207                            .padding(theme.spacing.xs)208                            .transition(.move(edge: .bottom).combined(with: .opacity))209                    }210                }211                .animation(theme.animation(.standard, reduceMotion: accessibility.reduceMotion), value: detent)212                .animation(theme.animation(.standard, reduceMotion: accessibility.reduceMotion), value: isPresented)213            }214        }215    }216217    private var sheetBody: some View {218        VStack(alignment: .leading, spacing: theme.spacing.sm) {219            header(showsCollapse: false, showsClose: false)220            content221                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)222        }223        .padding(.horizontal, theme.spacing.md)224        .padding(.top, theme.spacing.lg)225        .presentationDetents(226            Set(GlassMapPanelDetent.allCases.map(GlassMapPanelLayout.presentationDetent)),227            selection: Binding(228                get: { GlassMapPanelLayout.presentationDetent(detent) },229                set: { detent = GlassMapPanelLayout.detent(for: $0) }230            )231        )232        .presentationBackgroundInteraction(.enabled(upThrough: GlassMapPanelLayout.presentationDetent(GlassMapPanelLayout.largestInteractiveDetent)))233        .presentationDragIndicator(.visible)234        .interactiveDismissDisabled(!isDismissable)235    }236237    private var sideBody: some View {238        VStack(alignment: .leading, spacing: theme.spacing.sm) {239            header(showsCollapse: true, showsClose: isDismissable)240            if detent != .peek {241                content242                    .frame(maxWidth: .infinity, alignment: .top)243                    .frame(maxHeight: detent == .full ? .infinity : 360, alignment: .top)244            }245        }246        .padding(theme.spacing.md)247        .glassSurface(.regular.tinted(.none), in: theme.shape(\.large))248    }249250    private var dockedBody: some View {251        VStack(alignment: .leading, spacing: 0) {252            grabber253            header(showsCollapse: false, showsClose: isDismissable)254                .padding(.bottom, theme.spacing.xs)255            if detent != .peek {256                content257                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)258            }259        }260        .padding(.horizontal, theme.spacing.md)261        .padding(.bottom, theme.spacing.xs)262        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)263        .clipShape(theme.shape(\.extraLarge))264        .glassSurface(.regular.tinted(.none), in: theme.shape(\.extraLarge))265    }266267    /// The handle of the docked panel: drag it between detents, or activate it to expand or collapse.268    private var grabber: some View {269        let label: GlassL10n.Key = detent == .peek ? .expand : .collapse270        return Button {271            detent = GlassMapPanelLayout.toggled(detent)272        } label: {273            Capsule()274                .fill(theme.color(.textSecondary).opacity(0.45))275                .frame(width: 36, height: 5)276                .frame(maxWidth: .infinity)277                .frame(height: 22)278                .contentShape(Rectangle())279        }280        .buttonStyle(.plain)281        .simultaneousGesture(282            DragGesture(minimumDistance: 8).onEnded { value in283                detent = GlassMapPanelLayout.detent(after: detent, dragTranslation: value.translation.height)284            }285        )286        .accessibilityLabel(Text(GlassL10n.string(label)))287        .help(GlassL10n.string(label))288    }289290    private func header(showsCollapse: Bool, showsClose: Bool) -> some View {291        HStack(spacing: theme.spacing.xs) {292            title293                .font(theme.font(.title))294                .foregroundStyle(theme.color(.textPrimary))295                .lineLimit(1)296                .minimumScaleFactor(0.8)297                .accessibilityAddTraits(.isHeader)298            Spacer(minLength: theme.spacing.xs)299            if showsCollapse {300                panelButton(detent == .peek ? "chevron.down" : "chevron.up", label: detent == .peek ? .expand : .collapse) {301                    detent = GlassMapPanelLayout.toggled(detent)302                }303            }304            if showsClose {305                panelButton("xmark", label: .close) { isPresented = false }306            }307        }308    }309310    /// Small round buttons on a quiet fill: the panel is already glass, so its controls are not glass themselves.311    private func panelButton(_ systemImage: String, label: GlassL10n.Key, action: @escaping @MainActor () -> Void) -> some View {312        Button(action: action) {313            Image(systemName: systemImage)314                .font(.system(size: 12, weight: .bold))315                .foregroundStyle(theme.color(.textSecondary))316                .frame(width: 30, height: 30)317                .background(theme.color(.textSecondary).opacity(0.16), in: Circle())318                .glassMinimumHitTarget()319                .contentShape(Rectangle())320        }321        .buttonStyle(.plain)322        .accessibilityLabel(Text(GlassL10n.string(label)))323        .help(GlassL10n.string(label))324    }325}326327/// One result of a ``GlassMapResultList``.328public struct GlassMapResult: Identifiable, Hashable, Sendable {329    public let id: String330    public let title: String331    public let subtitle: String?332    public let systemImage: String333    /// A short trailing value such as a distance or a travel time ("350 m", "4 min").334    public let detail: String?335336    public init(id: String, title: String, subtitle: String? = nil, systemImage: String = "mappin", detail: String? = nil) {337        self.id = id338        self.title = title339        self.subtitle = subtitle340        self.systemImage = systemImage341        self.detail = detail342    }343}344345/// A plain list of map results for the content slot of a ``GlassMapPanel``.346///347/// Each row has a tinted icon tile, the name, a secondary line and an optional trailing detail. Rows are348/// buttons that call `onSelect`; the selected row is tinted, marked with a checkmark and carries the selected349/// trait. An empty list shows "No results".350public struct GlassMapResultList: View {351    @GlassThemed private var theme352    @Environment(\.dynamicTypeSize) private var dynamicTypeSize353    private let results: [GlassMapResult]354    private let selection: GlassMapResult.ID?355    private let onSelect: @MainActor (GlassMapResult) -> Void356357    public init(results: [GlassMapResult], selection: GlassMapResult.ID? = nil, onSelect: @escaping @MainActor (GlassMapResult) -> Void) {358        self.results = results359        self.selection = selection360        self.onSelect = onSelect361    }362363    private static var tileSide: CGFloat { 38 }364365    public var body: some View {366        if results.isEmpty {367            VStack(spacing: theme.spacing.xs) {368                Image(systemName: "magnifyingglass")369                    .font(.system(size: 20, weight: .medium))370                    .foregroundStyle(theme.color(.textSecondary))371                    .frame(width: 48, height: 48)372                    .background(theme.color(.textSecondary).opacity(0.12), in: Circle())373                    .accessibilityHidden(true)374                Text(GlassL10n.string(.noResults))375                    .font(theme.font(.callout))376                    .foregroundStyle(theme.color(.textSecondary))377            }378            .frame(maxWidth: .infinity)379            .padding(.vertical, theme.spacing.md)380            .accessibilityElement(children: .combine)381        } else {382            ScrollView {383                LazyVStack(alignment: .leading, spacing: 0) {384                    ForEach(results) { result in385                        row(result)386                        if result.id != results.last?.id {387                            Rectangle()388                                .fill(theme.color(.separator))389                                .frame(height: 0.5)390                                .padding(.leading, Self.tileSide + theme.spacing.sm + theme.spacing.xs)391                        }392                    }393                }394            }395            .accessibilityLabel(Text(GlassL10n.string(.results)))396        }397    }398399    private func row(_ result: GlassMapResult) -> some View {400        let isSelected = result.id == selection401        return Button {402            onSelect(result)403        } label: {404            HStack(spacing: theme.spacing.sm) {405                Image(systemName: result.systemImage)406                    .font(.system(size: 16, weight: .semibold))407                    .foregroundStyle(isSelected ? theme.onColor(.primary) : theme.color(.primary))408                    .frame(width: Self.tileSide, height: Self.tileSide)409                    .background(410                        theme.color(.primary).opacity(isSelected ? 1 : (theme.isDark ? 0.26 : 0.13)),411                        in: RoundedRectangle(cornerRadius: 11, style: .continuous)412                    )413                    .accessibilityHidden(true)414                VStack(alignment: .leading, spacing: 2) {415                    Text(verbatim: result.title)416                        .font(theme.font(.body).weight(.medium))417                        .foregroundStyle(theme.color(.textPrimary))418                        .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 2)419                    if let subtitle = result.subtitle {420                        Text(verbatim: subtitle)421                            .font(theme.font(.caption))422                            .foregroundStyle(theme.color(.textSecondary))423                            .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 2)424                    }425                }426                .multilineTextAlignment(.leading)427                Spacer(minLength: theme.spacing.xs)428                if let detail = result.detail, !detail.isEmpty {429                    Text(verbatim: detail)430                        .font(theme.font(.callout).monospacedDigit())431                        .foregroundStyle(theme.color(.textSecondary))432                        .lineLimit(1)433                        .layoutPriority(1)434                }435                if isSelected {436                    Image(systemName: "checkmark")437                        .font(.system(size: 13, weight: .bold))438                        .foregroundStyle(theme.color(.primary))439                        .accessibilityHidden(true)440                }441            }442            .padding(.vertical, theme.spacing.xs)443            .padding(.horizontal, theme.spacing.xs)444            .frame(maxWidth: .infinity, alignment: .leading)445            .background(446                theme.color(.primary).opacity(isSelected ? (theme.isDark ? 0.18 : 0.09) : 0),447                in: RoundedRectangle(cornerRadius: 14, style: .continuous)448            )449            .contentShape(Rectangle())450            .glassMinimumHitTarget()451        }452        .buttonStyle(.plain)453        .accessibilityElement(children: .combine)454        .accessibilityAddTraits(isSelected ? .isSelected : [])455    }456}457
Files main
Menu

Theme