SPB Git

Repository Public BSD-3-Clause

HomePanel.swift 16.3 KB 322 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Panel/HomePanel.swift10// Module           : Panel11// 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 ORIXPlaces91import ORIXSearch92import SwiftUI9394/// The resting state of the panel: search field, results, shortcuts, recents and the main menu.95struct HomePanel: View {96    @Environment(AppModel.self) private var app97    @Binding var detent: PresentationDetent98    @State private var query = ""99    /// Text put back in the field when the panel reappears; it must not start a new search.100    @State private var restoredQuery: String?101    @FocusState private var searchFocused: Bool102    @Environment(\.dynamicTypeSize) private var dynamicTypeSize103104    private var language: String { app.settings.interfaceLanguageCode }105    private static let shortcuts: [PlaceCategory] = [.restaurant, .cafe, .grocery, .fuel, .chargingStation, .parking, .pharmacy, .lodging, .park, .viewpoint, .toilets, .transitStation]106107    var body: some View {108        VStack(spacing: 0) {109            searchBar110            ScrollView {111                LazyVStack(alignment: .leading, spacing: ORIX.Spacing.l) {112                    if !query.isEmpty || app.search.matchedCategory != nil {113                        results114                    } else {115                        resting116                    }117                }118                .padding(.horizontal, ORIX.Spacing.l)119                .padding(.bottom, ORIX.Spacing.xl)120            }121            .scrollDismissesKeyboard(.immediately)122        }123        .onChange(of: searchFocused) { _, focused in if focused { detent = PanelDetent.full } }124        .onChange(of: query) { _, text in125            if restoredQuery == text { restoredQuery = nil; return }126            restoredQuery = nil127            app.search.update(text: text, full: false)128        }129        .onAppear {130            // Coming back from a place card: the search that led to it is still there (its results are still drawn on131            // the map), with its text in the field and the button that clears it.132            if query.isEmpty, !app.search.answeredQuery.isEmpty, !app.search.results.isEmpty {133                restoredQuery = app.search.answeredQuery134                query = app.search.answeredQuery135            }136        }137    }138139    private var searchBar: some View {140        HStack(spacing: ORIX.Spacing.s) {141            HStack(spacing: ORIX.Spacing.s) {142                Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true)143                TextField("Search places, addresses, coordinates", text: $query)144                    .focused($searchFocused)145                    .textInputAutocapitalization(.never)146                    .autocorrectionDisabled()147                    .submitLabel(.search)148                    .onSubmit(submit)149                    .accessibilityIdentifier("search.field")150                if !query.isEmpty || app.search.matchedCategory != nil {151                    Button { query = ""; app.search.clear() } label: {152                        Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary).frame(width: ORIX.minimumTarget, height: ORIX.minimumTarget).contentShape(.rect)153                    }154                    .buttonStyle(.plain).accessibilityLabel("Clear search").accessibilityIdentifier("search.clear")155                    .padding(.trailing, -ORIX.Spacing.s)156                }157            }158            .padding(.horizontal, ORIX.Spacing.m)159            .frame(height: 46)160            .background(.quaternary, in: .rect(cornerRadius: ORIX.Radius.control))161            Menu {162                Button("Downloaded maps", systemImage: "arrow.down.circle") { app.modal = .downloads }163                Button("Collections", systemImage: "bookmark") { app.modal = .collections }164                Button("Tracks", systemImage: "point.topleft.down.to.point.bottomright.curvepath") { app.modal = .tracks }165                Button("Explore", systemImage: "binoculars") { app.modal = .explorer }166                Button("Trip planner", systemImage: "map") { app.modal = .planner }167                Divider()168                Button("Measure", systemImage: "ruler") { app.route = .measure }169                Button("Compass", systemImage: "safari") { app.modal = .compass }170                Button("Map Studio", systemImage: "paintpalette") { app.modal = .studio }171                Divider()172                Button("Settings", systemImage: "gearshape") { app.modal = .settings }173                Button("About and data sources", systemImage: "info.circle") { app.modal = .about }174            } label: {175                Image(systemName: "ellipsis")176                    .font(.system(size: 17, weight: .semibold))177                    .frame(width: 46, height: 46)178                    .background(.quaternary, in: .rect(cornerRadius: ORIX.Radius.control))179                    .contentShape(.rect)180            }181            .accessibilityLabel("Menu")182            .accessibilityIdentifier("home.menu")183        }184        .padding(.horizontal, ORIX.Spacing.l)185        .padding(.top, ORIX.Spacing.l)186        .padding(.bottom, ORIX.Spacing.m)187        // The bar has a fixed height (it is what shows when the panel is collapsed): its text stops growing at the188        // first accessibility size instead of being clipped. Everything under it follows the full text size.189        .dynamicTypeSize(...DynamicTypeSize.accessibility1)190    }191192    @ViewBuilder private var resting: some View {193        if app.regions.isEmpty {194            EmptyStateView("No map downloaded yet", message: "The world map is built in. Download a region to see streets, search places and get directions without a connection.", systemImage: "map") {195                Button("Browse maps") { app.modal = .downloads }.buttonStyle(PrimaryButtonStyle(tint: AppColor.primaryFill)).accessibilityIdentifier("home.browse")196            }197            .frame(maxWidth: .infinity)198        } else {199            if app.search.hasIndex {200                ScrollView(.horizontal, showsIndicators: false) {201                    HStack(spacing: ORIX.Spacing.s) {202                        ForEach(Self.shortcuts, id: \.self) { c in203                            Chip(LocalizedStringKey(c.label(languageCode: language)), systemImage: c.symbolName) { detent = PanelDetent.half; app.search.search(category: c) }204                                .accessibilityIdentifier("category.\(c.rawValue)")205                        }206                    }207                }208                .scrollClipDisabled()209            }210            let saved = app.library.places.prefix(6)211            if !saved.isEmpty {212                section("Saved places") {213                    ForEach(Array(saved)) { p in214                        row(symbol: p.symbol ?? app.library.collection(p.collectionID)?.symbol ?? "bookmark.fill", title: p.name, subtitle: p.note.isEmpty ? p.address : p.note) {215                            app.select(PlaceSelection(title: p.name, subtitle: p.address, coordinate: p.coordinate, origin: .saved(p.id.uuidString), category: p.category), moveCamera: true)216                        }217                        .accessibilityIdentifier("home.saved")218                    }219                }220            }221            if !app.library.history.isEmpty {222                section("Recent") {223                    ForEach(app.library.history.prefix(8)) { h in224                        row(symbol: h.kind == .search ? "clock.arrow.circlepath" : "mappin.circle", title: h.title, subtitle: h.subtitle) {225                            if let c = h.coordinate { app.select(PlaceSelection(title: h.title, subtitle: h.subtitle, coordinate: c, origin: .search), moveCamera: true) }226                            else { query = h.title; submit() }227                        }228                        .contextMenu { Button("Remove from history", role: .destructive) { Task { await app.library.deleteHistory(h) } } }229                        .accessibilityIdentifier("home.recent")230                    }231                }232            }233        }234    }235236    @ViewBuilder private var results: some View {237        let search = app.search238        if let c = search.matchedCategory, query.isEmpty {239            Text(verbatim: c.label(languageCode: language)).font(.headline).accessibilityAddTraits(.isHeader)240        }241        if !search.corrections.isEmpty {242            NoticeView("Showing results for \(search.corrections.flatMap(\.replacements).prefix(3).joined(separator: ", ")).")243        }244        let saved = query.isEmpty ? [] : app.library.places.filter { $0.name.localizedStandardContains(query) }.prefix(3)245        ForEach(Array(saved)) { p in246            row(symbol: "bookmark.fill", title: p.name, subtitle: String(localized: "Saved place")) {247                app.select(PlaceSelection(title: p.name, subtitle: p.address, coordinate: p.coordinate, origin: .saved(p.id.uuidString), category: p.category), moveCamera: true)248            }249        }250        // When the house number was found, the "street only" rows of the same query would contradict it: hide them.251        let numberFound = search.results.contains { $0.kind == .address && $0.addressMatch != .streetOnly }252        ForEach(search.results.filter { !(numberFound && $0.addressMatch == .streetOnly) }) { r in253            row(symbol: r.symbol, title: r.name, subtitle: subtitle(r), trailing: r.distance.map { app.settings.formatter.distance($0) }) {254                searchFocused = false255                // The card opens half-way: the place stays visible on the map above it.256                detent = PanelDetent.half257                app.select(r.selection(language: language), moveCamera: true)258            }259            .accessibilityIdentifier("search.result")260        }261        if search.results.isEmpty, saved.isEmpty, !search.isSearching {262            if !search.hasIndex {263                NoticeView("No installed region includes search. Coordinates still work: try “45.5017, -73.5673”.")264            } else {265                EmptyStateView("Nothing found", message: "Search covers the regions installed on this device. Check the spelling, or download the region you are looking in.", systemImage: "magnifyingglass")266                    .frame(maxWidth: .infinity)267            }268        }269        if !search.results.isEmpty, let date = search.indexes.compactMap(\.dataDate).min() {270            Text("Results from the installed maps, data of \(date.formatted(date: .abbreviated, time: .omitted)).").font(.caption).foregroundStyle(.secondary)271        }272    }273274    private func subtitle(_ r: SearchResult) -> String? {275        var parts: [String] = []276        if r.kind == .poi, let c = r.category { parts.append(c.label(languageCode: language)) }277        if r.addressMatch == .streetOnly, let n = r.requestedHouseNumber { parts.append(String(localized: "Street only — number \(n) not found")) }278        if r.addressMatch == .interpolated { parts.append(String(localized: "Approximate position")) }279        if !r.secondaryLine.isEmpty { parts.append(r.secondaryLine) }280        return parts.isEmpty ? nil : parts.joined(separator: " · ")281    }282283    private func section<Content: View>(_ title: LocalizedStringKey, @ViewBuilder content: () -> Content) -> some View {284        VStack(alignment: .leading, spacing: ORIX.Spacing.xs) {285            Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary).accessibilityAddTraits(.isHeader)286            content()287        }288    }289290    private func row(symbol: String, title: String, subtitle: String?, trailing: String? = nil, action: @escaping () -> Void) -> some View {291        Button(action: action) {292            HStack(spacing: ORIX.Spacing.m) {293                Image(systemName: symbol).frame(width: 34, height: 34).foregroundStyle(ORIX.Palette.accent).background(ORIX.Palette.accent.opacity(0.12), in: .circle).accessibilityHidden(true)294                VStack(alignment: .leading, spacing: 1) {295                    Text(title).foregroundStyle(.primary).lineLimit(dynamicTypeSize.isAccessibilitySize ? 3 : 1)296                    if let subtitle, !subtitle.isEmpty { Text(subtitle).font(.footnote).foregroundStyle(.secondary).lineLimit(dynamicTypeSize.isAccessibilitySize ? 3 : 1) }297                }298                Spacer(minLength: 0)299                if let trailing { Text(trailing).font(.footnote.monospacedDigit()).foregroundStyle(.secondary) }300            }301            .frame(minHeight: ORIX.minimumTarget)302            .contentShape(.rect)303        }304        .buttonStyle(.plain)305    }306307    private func submit() {308        let text = query.trimmingCharacters(in: .whitespacesAndNewlines)309        guard !text.isEmpty else { return }310        searchFocused = false311        // Coordinates always work, even with no region installed.312        if let c = CoordinateText.parse(text) {313            detent = PanelDetent.half314            app.select(PlaceSelection(title: CoordinateText.format(c, style: app.settings.coordinateStyle), subtitle: nil, coordinate: c, origin: .coordinates), moveCamera: true)315            return316        }317        detent = PanelDetent.half318        app.search.update(text: text, full: true)319        Task { await app.library.record(search: text) }320    }321}322
Files main
Menu

Theme