Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Apps/ORIXMaps/Sources/Directions/DirectionsPanel.swift10// Module : Directions11// 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 ORIXNavigation91import ORIXRouting92import SwiftUI9394extension TravelMode {95 var symbol: String {96 switch self {97 case .car: "car.fill"98 case .bicycle: "bicycle"99 case .pedestrian: "figure.walk"100 }101 }102 var label: LocalizedStringKey {103 switch self {104 case .car: "Drive"105 case .bicycle: "Cycle"106 case .pedestrian: "Walk"107 }108 }109}110111extension Maneuver {112 /// SF Symbol of the maneuver for lists and the guidance banner.113 var symbol: String {114 switch type {115 case .depart: return "location.fill"116 case .arrive: return "flag.checkered"117 case .waypoint: return "mappin.circle.fill"118 case .roundabout, .exitRoundabout: return "arrow.triangle.capsulepath"119 case .ferry: return "ferry.fill"120 case .uTurn: return "arrow.uturn.left"121 case .merge: return "arrow.merge"122 case .continue: return "arrow.up"123 case .turn, .fork, .onRamp, .offRamp:124 switch modifier {125 case .left?, .sharpLeft?: return "arrow.turn.up.left"126 case .right?, .sharpRight?: return "arrow.turn.up.right"127 case .slightLeft?: return "arrow.up.left"128 case .slightRight?: return "arrow.up.right"129 case .uTurn?: return "arrow.uturn.left"130 default: return "arrow.up"131 }132 }133 }134}135136/// The route planner: stops, mode, the computed routes with their warnings, and the steps.137struct DirectionsPanel: View {138 @Environment(AppModel.self) private var app139 @State private var showSteps = false140 @Environment(\.dynamicTypeSize) private var dynamicTypeSize141142 private var d: DirectionsModel { app.directions }143144 var body: some View {145 @Bindable var directions = app.directions146 let f = app.settings.formatter147 ScrollView {148 VStack(alignment: .leading, spacing: ORIX.Spacing.l) {149 PanelHeader(title: String(localized: "Directions"), subtitle: nil) { d.clear(); app.route = .home }150 Picker("Travel mode", selection: $directions.mode) {151 ForEach(TravelMode.allCases, id: \.self) { m in Label(m.label, systemImage: m.symbol).tag(m) }152 }153 .pickerStyle(.segmented)154 .onChange(of: d.mode) { _, _ in d.compute() }155 .accessibilityIdentifier("directions.mode")156 VStack(spacing: 0) {157 ForEach(Array(d.points.enumerated()), id: \.element.id) { i, p in158 HStack(spacing: ORIX.Spacing.m) {159 Image(systemName: i == 0 ? "circle.fill" : (i == d.points.count - 1 ? "flag.checkered" : "mappin.circle.fill"))160 .foregroundStyle(i == 0 ? ORIX.Palette.accent : ORIX.Palette.route).frame(minWidth: 24).accessibilityHidden(true)161 Text(p.title).lineLimit(dynamicTypeSize.isAccessibilitySize ? 3 : 1)162 Spacer()163 if d.points.count > 2 {164 Button { d.removePoint(p.id) } label: { Image(systemName: "minus.circle").frame(width: 36, height: 36) }165 .buttonStyle(.plain).foregroundStyle(.secondary).accessibilityLabel(Text("Remove \(p.title)"))166 }167 }168 .frame(minHeight: ORIX.minimumTarget)169 if i < d.points.count - 1 { Divider().padding(.leading, 36) }170 }171 }172 .padding(.horizontal, ORIX.Spacing.m)173 .background(.quaternary.opacity(0.6), in: .rect(cornerRadius: ORIX.Radius.control))174 AdaptiveStack {175 Button { d.reverse() } label: { Label("Reverse", systemImage: "arrow.up.arrow.down").frame(minHeight: ORIX.minimumTarget).contentShape(.rect) }.buttonStyle(.borderless)176 Spacer(minLength: 0)177 Text("Add a stop: open a place, then “Add stop”.").font(.caption).foregroundStyle(.secondary).multilineTextAlignment(.trailing)178 }179 .font(.subheadline)180 if d.isComputing { HStack { ProgressView(); Text("Computing the route…").foregroundStyle(.secondary) } }181 if let failure = d.failure { failureView(failure) }182 ForEach(Array(d.routes.enumerated()), id: \.offset) { i, route in183 routeCard(route, index: i, f: f)184 }185 if let route = d.route {186 Button { app.startNavigation(simulated: false) } label: { Label("Start", systemImage: "location.north.line.fill") }187 .buttonStyle(PrimaryButtonStyle(tint: ORIX.Palette.route))188 .accessibilityIdentifier("directions.start")189 Button { app.startNavigation(simulated: true) } label: { Label("Preview the trip (simulation)", systemImage: "play.circle") }190 .buttonStyle(SecondaryButtonStyle())191 .accessibilityIdentifier("directions.simulate")192 DisclosureGroup(isExpanded: $showSteps) {193 VStack(alignment: .leading, spacing: 0) {194 ForEach(Array(route.maneuvers.enumerated()), id: \.offset) { _, m in195 HStack(alignment: .top, spacing: ORIX.Spacing.m) {196 Image(systemName: m.symbol).frame(width: 28).foregroundStyle(ORIX.Palette.route).accessibilityHidden(true)197 VStack(alignment: .leading, spacing: 2) {198 Text(verbatim: d.formatter.instruction(for: m))199 if m.distanceMeters > 0 { Text(verbatim: f.distance(m.distanceMeters)).font(.footnote).foregroundStyle(.secondary) }200 }201 }202 .padding(.vertical, 8)203 .accessibilityElement(children: .combine)204 }205 }206 } label: { Text("\(route.maneuvers.count) steps").font(.subheadline.weight(.semibold)) }207 .accessibilityIdentifier("directions.steps")208 // The limits of an offline route are always stated; the date of the data when the region gives it.209 Group {210 if let date = d.response?.osmTimestamp {211 Text("Computed on this device from map data of \(date.formatted(date: .abbreviated, time: .omitted)). No traffic, closures or roadworks.")212 } else {213 Text("Computed on this device from the installed maps. No traffic, closures or roadworks.")214 }215 }216 .font(.caption).foregroundStyle(.secondary).accessibilityIdentifier("directions.note")217 }218 }219 .padding(ORIX.Spacing.l)220 }221 .accessibilityIdentifier("directions.panel")222 }223224 private func routeCard(_ route: Route, index: Int, f: MeasureFormatter) -> some View {225 let selected = index == d.selectedRoute226 return Button { d.selectedRoute = index } label: {227 VStack(alignment: .leading, spacing: 6) {228 HStack(alignment: .firstTextBaseline) {229 Text(verbatim: f.duration(route.durationSeconds)).font(.title2.weight(.bold).monospacedDigit())230 Text(verbatim: f.distance(route.distanceMeters)).foregroundStyle(.secondary)231 Spacer()232 if selected { Image(systemName: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.route).accessibilityHidden(true) }233 }234 let main = route.segments.sorted { $0.distanceMeters > $1.distanceMeters }.compactMap { $0.ref ?? $0.name }.reduce(into: [String]()) { if !$0.contains($1) && $0.count < 2 { $0.append($1) } }235 if !main.isEmpty { Text("Via \(main.joined(separator: ", "))").font(.subheadline).foregroundStyle(.secondary).lineLimit(1) }236 ForEach(route.warnings, id: \.kind) { w in237 Label(warningText(w, f: f), systemImage: w.kind == .assumedSpeeds ? "clock.badge.questionmark" : "exclamationmark.triangle")238 .font(.footnote).foregroundStyle(.secondary)239 }240 }241 .padding(ORIX.Spacing.m)242 .frame(maxWidth: .infinity, alignment: .leading)243 .background(selected ? ORIX.Palette.route.opacity(0.10) : Color.clear, in: .rect(cornerRadius: ORIX.Radius.control))244 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control).strokeBorder(selected ? ORIX.Palette.route : Color.primary.opacity(0.12), lineWidth: selected ? 2 : 1))245 .contentShape(.rect)246 }247 .buttonStyle(.plain)248 .accessibilityAddTraits(selected ? .isSelected : [])249 .accessibilityIdentifier("directions.route.\(index)")250 }251252 private func warningText(_ w: RouteWarning, f: MeasureFormatter) -> String {253 switch w.kind {254 case .ferry: String(localized: "Includes a ferry (\(f.distance(w.distanceMeters))). Schedules are not known.")255 case .toll: String(localized: "Includes toll roads (\(f.distance(w.distanceMeters))).")256 case .unpaved: String(localized: "Includes unpaved roads (\(f.distance(w.distanceMeters))).")257 case .restrictedAccess: String(localized: "Uses private or destination-only roads (\(f.distance(w.distanceMeters))).")258 case .assumedSpeeds: String(localized: "Duration is an estimate: \(Int((w.share * 100).rounded())) % of the route has no posted speed in the data.")259 }260 }261262 @ViewBuilder private func failureView(_ failure: DirectionsFailure) -> some View {263 switch failure {264 case .noPosition:265 if app.location.authorization == .denied || app.location.authorization == .restricted {266 NoticeView("Position access is off, so the route cannot start from your position. Turn access on in Settings, or add a stop on the map and remove “My position”.", kind: .warning)267 .accessibilityIdentifier("directions.noposition.denied")268 } else {269 NoticeView("Waiting for your position. If position access is off, choose a starting point on the map instead.", kind: .warning)270 .accessibilityIdentifier("directions.noposition")271 }272 Button("Try again") { d.compute() }.buttonStyle(SecondaryButtonStyle())273 case .noRoutingData:274 NoticeView("No installed region includes directions. Download a region to get routes offline.", kind: .warning)275 Button("Browse maps") { app.modal = .downloads }.buttonStyle(SecondaryButtonStyle())276 case .notCovered:277 NoticeView("These points are not all inside one installed region. Routes cannot cross between regions or leave them yet.", kind: .warning)278 Button("Browse maps") { app.modal = .downloads }.buttonStyle(SecondaryButtonStyle())279 case .tooFarFromRoad(let i):280 NoticeView("\(i < d.points.count ? d.points[i].title : "") is too far from a road usable in this mode.", kind: .warning)281 case .noConnection:282 NoticeView("No route was found between these points in this mode with the current avoid options.", kind: .warning)283 case .other:284 // The underlying message is a developer diagnostic in English: it is logged by the router, not shown.285 NoticeView("The route could not be computed.", kind: .error)286 }287 }288}289290/// The guidance panel: next maneuver, remaining distance and time, controls.291struct NavigationPanel: View {292 @Environment(AppModel.self) private var app293294 private var d: DirectionsModel { app.directions }295296 var body: some View {297 let f = app.settings.formatter298 ScrollView {299 VStack(alignment: .leading, spacing: ORIX.Spacing.m) {300 if d.arrived {301 HStack(spacing: ORIX.Spacing.m) {302 Image(systemName: "flag.checkered").font(.title).foregroundStyle(ORIX.Palette.success)303 Text("You have arrived").font(.title2.weight(.bold))304 }305 Button("Done") { app.endNavigation() }.buttonStyle(PrimaryButtonStyle(tint: AppColor.primaryFill)).accessibilityIdentifier("navigation.done")306 } else if let p = d.progress, let route = d.session?.route, route.maneuvers.indices.contains(p.nextManeuverIndex) {307 let m = route.maneuvers[p.nextManeuverIndex]308 HStack(alignment: .center, spacing: ORIX.Spacing.m) {309 Image(systemName: m.symbol).font(.system(size: 34, weight: .bold)).foregroundStyle(.white)310 .frame(width: 64, height: 64).background(ORIX.Palette.route, in: .rect(cornerRadius: 16)).accessibilityHidden(true)311 VStack(alignment: .leading, spacing: 2) {312 Text(verbatim: f.distance(p.distanceToNextManeuver)).font(.system(.title, design: .rounded).weight(.bold).monospacedDigit())313 Text(verbatim: d.formatter.instruction(for: m)).font(.headline).lineLimit(2).minimumScaleFactor(0.8)314 }315 }316 .accessibilityElement(children: .combine)317 .accessibilityIdentifier("navigation.banner")318 if d.isRerouting {319 NoticeView("Off the route. Computing a new one…", kind: .warning)320 } else if !p.isOnRoute {321 NoticeView("Off the route.", kind: .warning)322 }323 HStack {324 StatView("Arrival", value: p.eta(from: Date()).formatted(date: .omitted, time: .shortened))325 StatView("Remaining", value: f.duration(p.durationRemaining))326 StatView("Distance", value: f.distance(p.distanceRemaining))327 }328 if d.isSimulating { NoticeView("Simulation: the position shown is replayed along the route, not your real position.") }329 AdaptiveStack {330 Button { d.toggleVoice() } label: { Image(systemName: app.settings.voiceGuidance ? "speaker.wave.2.fill" : "speaker.slash.fill").frame(maxWidth: .infinity) }331 .buttonStyle(SecondaryButtonStyle())332 .accessibilityLabel(app.settings.voiceGuidance ? "Mute spoken instructions" : "Unmute spoken instructions")333 if !d.followsPosition {334 Button("Recentre") { d.followsPosition = true }.buttonStyle(SecondaryButtonStyle())335 }336 Button("End") { app.endNavigation() }.buttonStyle(PrimaryButtonStyle(tint: AppColor.dangerFill)).accessibilityIdentifier("navigation.end")337 }338 } else {339 HStack { ProgressView(); Text("Waiting for a position…").foregroundStyle(.secondary) }340 if app.location.authorization == .denied || app.location.authorization == .restricted {341 NoticeView("Position access is off. Guidance cannot follow you; use the simulation or turn access on in Settings.", kind: .error)342 }343 Button("End") { app.endNavigation() }.buttonStyle(PrimaryButtonStyle(tint: AppColor.dangerFill))344 }345 }346 .padding(ORIX.Spacing.l)347 .frame(maxWidth: .infinity, alignment: .leading)348 }349 .scrollBounceBehavior(.basedOnSize)350 .accessibilityElement(children: .contain)351 .accessibilityIdentifier("navigation.panel")352 }353}354