SPB Git

Repository Public MIT

GlassLocationButton.swift 7.9 KB 179 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMaps/Maps/GlassLocationButton.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/// The location state a host reports to a ``GlassLocationButton``.49public enum GlassLocationState: String, CaseIterable, Sendable {50    /// The position is not shown; tapping asks the host to show it.51    case idle52    /// The host is waiting for a position.53    case locating54    /// The map follows the user's position.55    case following56    /// The user refused the location permission.57    case denied58    /// Location is not available (restricted, no hardware, services off).59    case unavailable60}6162/// How a location state is presented: symbol, label and whether the button reacts.63public struct GlassLocationPresentation: Equatable, Sendable {64    public let symbolName: String65    public let labelKey: GlassL10n.Key66    /// False only for `.unavailable`: a denied button stays active so that the host can explain or open Settings.67    public let isEnabled: Bool68    /// True when the map follows the user: the symbol takes the theme's primary colour.69    public let isEmphasized: Bool70    /// True while a position is awaited.71    public let isBusy: Bool7273    public init(_ state: GlassLocationState) {74        switch state {75        case .idle:76            self.init(symbolName: "location", labelKey: .locate, isEnabled: true, isEmphasized: false, isBusy: false)77        case .locating:78            self.init(symbolName: "location", labelKey: .locating, isEnabled: true, isEmphasized: false, isBusy: true)79        case .following:80            self.init(symbolName: "location.fill", labelKey: .locationFollowing, isEnabled: true, isEmphasized: true, isBusy: false)81        case .denied:82            self.init(symbolName: "location.slash", labelKey: .locationDenied, isEnabled: true, isEmphasized: false, isBusy: false)83        case .unavailable:84            self.init(symbolName: "location.slash", labelKey: .locationUnavailable, isEnabled: false, isEmphasized: false, isBusy: false)85        }86    }8788    private init(symbolName: String, labelKey: GlassL10n.Key, isEnabled: Bool, isEmphasized: Bool, isBusy: Bool) {89        self.symbolName = symbolName90        self.labelKey = labelKey91        self.isEnabled = isEnabled92        self.isEmphasized = isEmphasized93        self.isBusy = isBusy94    }9596    /// The localised accessibility label.97    public var label: String { GlassL10n.string(labelKey) }98}99100/// A round glass button that shows the location state reported by the host and calls its action.101///102/// ```swift103/// GlassLocationButton(state: model.locationState, hint: "Opens Settings to allow location access") {104///     model.locationButtonTapped()      // the host requests permission, starts updates, or opens Settings105/// }106/// ```107///108/// The button never requests the location permission and never reads the position: it displays ``GlassLocationState``109/// and calls `action`. Denied and unavailable are conveyed by a slashed symbol and by the accessibility label,110/// not by colour.111public struct GlassLocationButton: View {112    @GlassThemed private var theme113    @GlassAccessibility private var accessibility114    private let state: GlassLocationState115    private let hint: String?116    private let size: GlassControlSize117    private let action: @MainActor () -> Void118119    /// - Parameters:120    ///   - state: the state reported by the host.121    ///   - hint: an optional explanation, read as the accessibility hint and shown as the tooltip on macOS122    ///     (for example why access is denied and what tapping does).123    public init(state: GlassLocationState, hint: String? = nil, size: GlassControlSize = .regular, action: @escaping @MainActor () -> Void) {124        self.state = state125        self.hint = hint126        self.size = size127        self.action = action128    }129130    public var body: some View {131        let presentation = GlassLocationPresentation(state)132        let side = GlassIconButtonMetrics.hitTarget(size, metrics: theme.metrics)133        Button(action: action) {134            Image(systemName: presentation.symbolName)135                .font(.system(size: theme.metrics.iconSize(size), weight: .medium))136                .symbolEffect(.pulse, isActive: presentation.isBusy && !accessibility.reduceMotion)137                .foregroundStyle(symbolColor(presentation))138                // The arrow's visual weight sits towards its tip: nudge it back to the optical centre.139                .offset(x: -side * 0.02, y: side * 0.02)140                .frame(width: side, height: side)141                .overlay {142                    if presentation.isBusy {143                        // A static arc on the rim: "waiting" stays readable when the pulse is disabled.144                        Circle()145                            .trim(from: 0.02, to: 0.3)146                            .stroke(theme.color(.primary), style: StrokeStyle(lineWidth: 2, lineCap: .round))147                            .rotationEffect(.degrees(-90))148                            .padding(3)149                    }150                }151                .glassSurface(.interactive.tinted(.none), in: Circle())152                .overlay(alignment: .topTrailing) {153                    if state == .denied {154                        Image(systemName: "exclamationmark")155                            .font(.system(size: side * 0.2, weight: .heavy))156                            .foregroundStyle(theme.onColor(.destructive))157                            .frame(width: side * 0.36, height: side * 0.36)158                            .background(theme.color(.destructive), in: Circle())159                            .overlay(Circle().strokeBorder(theme.color(.background), lineWidth: 1.5))160                            .offset(x: side * 0.04, y: -side * 0.04)161                            .accessibilityHidden(true)162                    }163                }164                .contentShape(Circle())165        }166        .buttonStyle(.plain)167        .disabled(!presentation.isEnabled)168        .accessibilityLabel(Text(presentation.label))169        .accessibilityHint(Text(verbatim: hint ?? ""))170        .accessibilityAddTraits(presentation.isBusy ? .updatesFrequently : [])171        .help(hint ?? presentation.label)172    }173174    private func symbolColor(_ presentation: GlassLocationPresentation) -> Color {175        if presentation.isEmphasized { return theme.color(.primary) }176        return presentation.isEnabled ? theme.color(.textPrimary) : theme.color(.textSecondary).opacity(0.6)177    }178}179
Files main
Menu

Theme