SPB Git

Repository Public BSD-3-Clause

MapScreen.swift 12.7 KB 272 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Map/MapScreen.swift10// Module           : Map11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ORIXDesignSystem89import ORIXGeoCore90import ORIXLocation91import ORIXMapRenderer92import ORIXMapStyle93import SwiftUI9495/// The root screen: the map fills the display; controls float above it; the panel is a sheet on iPhone and a side96/// column on iPad.97struct MapScreen: View {98    @Environment(AppModel.self) private var app99    @Environment(\.horizontalSizeClass) private var sizeClass100    @Environment(\.colorScheme) private var colorScheme101    @Environment(\.accessibilityReduceMotion) private var reduceMotion102    @State private var detent: PresentationDetent = PanelDetent.peek103104    var body: some View {105        @Bindable var app = app106        let compact = sizeClass == .compact107        ZStack(alignment: .topLeading) {108            MapCanvas(controller: app.map) { name in MapImages.image(named: name, dark: app.effectiveTheme.isDark) }109                .ignoresSafeArea()110                .accessibilityElement()111                .accessibilityLabel("Map")112                .accessibilityValue(mapAccessibilityValue)113                .accessibilityAddTraits(.allowsDirectInteraction)114                .accessibilityIdentifier("map.canvas")115            if !compact {116                PanelHost(detent: $detent)117                    .frame(width: 380)118                    // An opaque surface: on a material, the secondary texts and the light fills of the cards (route119                    // details, statistics captions, secondary buttons) are too faint to read over the map.120                    .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: ORIX.Radius.card))121                    .clipShape(.rect(cornerRadius: ORIX.Radius.card))122                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card).strokeBorder(.primary.opacity(0.08)))123                    .shadow(color: .black.opacity(0.18), radius: 16, y: 6)124                    .padding(ORIX.Spacing.l)125                    .frame(maxHeight: .infinity, alignment: .top)126            }127            MapControls()128                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)129                .padding(.trailing, ORIX.Spacing.m)130                .padding(.top, ORIX.Spacing.s)131            // Data credit, always visible on the map; it opens the full list of sources and licences.132            Button { app.modal = .about } label: {133                Text("© OpenStreetMap")134                    .font(.caption2.weight(.medium))135                    .foregroundStyle(.primary.opacity(0.75))136                    .padding(.horizontal, 7).padding(.vertical, 3)137                    .background(.regularMaterial, in: .capsule)138                    .frame(minWidth: ORIX.minimumTarget, minHeight: ORIX.minimumTarget, alignment: .topLeading)139                    .contentShape(.rect)140            }141            .buttonStyle(.plain)142            .accessibilityLabel("Map data credits")143            .accessibilityIdentifier("map.attribution")144            .padding(.leading, compact ? ORIX.Spacing.m : 412)145            .padding(.top, ORIX.Spacing.s)146            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)147            if let toast = app.toast {148                Text(toast)149                    .font(.subheadline.weight(.medium))150                    .padding(.horizontal, 14).padding(.vertical, 10)151                    .background(.thickMaterial, in: .capsule)152                    .shadow(color: .black.opacity(0.15), radius: 8, y: 2)153                    .frame(maxWidth: .infinity, alignment: .center)154                    .padding(.top, ORIX.Spacing.s)155                    .transition(.move(edge: .top).combined(with: .opacity))156                    .accessibilityAddTraits(.updatesFrequently)157                    .accessibilityIdentifier("toast")158            }159        }160        .animation(ORIX.Motion.standard(reduceMotion: reduceMotion), value: app.toast)161        .sheet(isPresented: .constant(compact)) {162            PanelHost(detent: $detent)163                .presentationDetents(PanelDetent.all, selection: $detent)164                .presentationBackgroundInteraction(.enabled(upThrough: PanelDetent.half))165                .presentationDragIndicator(.visible)166                .presentationCornerRadius(ORIX.Radius.card)167                .interactiveDismissDisabled()168                .sheet(item: $app.modal) { ModalHost(route: $0) }169        }170        .sheet(item: compact ? .constant(nil) : $app.modal) { ModalHost(route: $0) }171        .onChange(of: colorScheme, initial: true) { _, scheme in app.isDarkInterface = scheme == .dark }172        .onChange(of: reduceMotion, initial: true) { _, reduce in app.reduceMotion = reduce }173        .onChange(of: app.location.lastFix) { _, _ in app.positionDidChange() }174        .onChange(of: app.location.heading) { _, _ in app.positionDidChange() }175        .onChange(of: app.location.authorization) { _, _ in app.authorizationDidChange() }176        .onChange(of: app.route) { _, route in177            // A new card opens half-way so that the map stays visible behind it.178            switch route {179            case .home: break180            case .navigation: detent = PanelDetent.guidance181            default: if detent == PanelDetent.peek { detent = PanelDetent.half }182            }183        }184        .onChange(of: detent, initial: true) { _, d in185            guard compact else { app.map.setContentInsets(MapInsets(left: 396), animated: false); return }186            let bottom: Double = d == PanelDetent.peek ? 96 : (d == PanelDetent.guidance ? 300 : (d == PanelDetent.half ? 380 : 96))187            app.map.setContentInsets(MapInsets(bottom: bottom), animated: !reduceMotion)188        }189        .preferredColorScheme(app.settings.appearance == .system ? nil : (app.settings.appearance == .dark ? .dark : .light))190    }191192    private var mapAccessibilityValue: Text {193        let c = app.map.camera194        return Text("Centered on \(CoordinateText.format(c.center, style: app.settings.coordinateStyle)), zoom level \(Int(c.zoom.rounded()))")195    }196}197198enum PanelDetent {199    static let peek = PresentationDetent.height(96)200    /// Guidance: room for the maneuver banner, the three figures and the buttons.201    static let guidance = PresentationDetent.height(300)202    static let half = PresentationDetent.fraction(0.46)203    static let full = PresentationDetent.large204    static let all: Set<PresentationDetent> = [peek, guidance, half, full]205}206207/// Floating buttons at the top right of the map.208struct MapControls: View {209    @Environment(AppModel.self) private var app210    @Environment(\.accessibilityReduceMotion) private var reduceMotion211212    var body: some View {213        VStack(spacing: ORIX.Spacing.s) {214            MapControlButton("Map layers and themes", systemImage: "square.3.layers.3d") { app.modal = .layers }215                .accessibilityIdentifier("map.layers")216            MapControlButton(app.map.camera.pitch > 5 ? "Switch to flat view" : "Switch to 3D view", isActive: app.map.camera.pitch > 5, action: { app.toggle3D(reduceMotion: reduceMotion) }) {217                Text(verbatim: app.map.camera.pitch > 5 ? "2D" : "3D").font(.system(size: 15, weight: .bold, design: .rounded))218            }219            .accessibilityIdentifier("map.3d")220            MapControlButton(trackingLabel, systemImage: trackingIcon, isActive: app.tracking != .none) { app.cycleTracking(reduceMotion: reduceMotion) }221                .accessibilityIdentifier("map.location")222            if abs(app.map.camera.bearing) > 0.5 || app.map.camera.pitch > 0.5 {223                MapControlButton("Reset to north", action: { app.resetNorth(reduceMotion: reduceMotion) }) {224                    CompassNeedle().rotationEffect(.degrees(-app.map.camera.bearing))225                }226                .accessibilityValue(Text("Heading \(Int(app.map.camera.bearing.rounded())) degrees"))227                .accessibilityIdentifier("map.compass")228                .transition(.scale.combined(with: .opacity))229            }230        }231        .animation(ORIX.Motion.standard(reduceMotion: reduceMotion), value: abs(app.map.camera.bearing) > 0.5 || app.map.camera.pitch > 0.5)232    }233234    private var trackingIcon: String {235        switch app.tracking {236        case .none: app.location.authorization == .denied || app.location.authorization == .restricted ? "location.slash" : "location"237        case .follow: "location.fill"238        case .followWithHeading: "location.north.line.fill"239        }240    }241242    private var trackingLabel: LocalizedStringKey {243        switch app.tracking {244        case .none: "Show my position"245        case .follow: "Following my position. Tap to follow my heading"246        case .followWithHeading: "Following my heading. Tap to stop"247        }248    }249}250251/// A two-colour compass needle pointing to north.252struct CompassNeedle: View {253    var body: some View {254        ZStack {255            Triangle().fill(ORIX.Palette.danger).frame(width: 9, height: 13).offset(y: -6.5)256            Triangle().fill(Color.secondary).frame(width: 9, height: 13).rotationEffect(.degrees(180)).offset(y: 6.5)257        }258        .accessibilityHidden(true)259    }260}261262nonisolated struct Triangle: Shape {263    func path(in rect: CGRect) -> Path {264        Path { p in265            p.move(to: CGPoint(x: rect.midX, y: rect.minY))266            p.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))267            p.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))268            p.closeSubpath()269        }270    }271}272
Files main
Menu

Theme