SPB Git

Repository Public BSD-3-Clause

CollectionsScreen.swift 19.2 KB 385 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Places/CollectionsScreen.swift10// Module           : Places11// 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 ORIXGeoExchange91import ORIXMapStyle92import ORIXPlaces93import SwiftUI94import UniformTypeIdentifiers9596/// Symbols and colours offered for collections and pins.97enum PinStyle {98    static let symbols = ["star.fill", "bookmark.fill", "heart.fill", "house.fill", "briefcase.fill", "fork.knife", "cup.and.saucer.fill", "bed.double.fill", "cart.fill", "leaf.fill",99                          "mountain.2.fill", "figure.hiking", "bicycle", "car.fill", "tram.fill", "airplane", "camera.fill", "binoculars.fill", "tent.fill", "flag.fill", "mappin", "p.circle.fill"]100    static let colors = ["#F5A623", "#00A896", "#3D5AFE", "#E5484D", "#8E5BB5", "#3E8A4F", "#C9661E", "#3F6FB5", "#B0527A", "#55606E"]101102    /// Spoken name of a pin symbol (VoiceOver), in the interface language.103    static func name(of symbol: String) -> String {104        switch symbol {105        case "star.fill": String(localized: "Star")106        case "bookmark.fill": String(localized: "Bookmark")107        case "heart.fill": String(localized: "Heart")108        case "house.fill": String(localized: "Home")109        case "briefcase.fill": String(localized: "Work")110        case "fork.knife": String(localized: "Restaurant")111        case "cup.and.saucer.fill": String(localized: "Café")112        case "bed.double.fill": String(localized: "Lodging")113        case "cart.fill": String(localized: "Shopping")114        case "leaf.fill": String(localized: "Nature")115        case "mountain.2.fill": String(localized: "Mountain")116        case "figure.hiking": String(localized: "Hiking")117        case "bicycle": String(localized: "Bicycle")118        case "car.fill": String(localized: "Car")119        case "tram.fill": String(localized: "Transit")120        case "airplane": String(localized: "Airport")121        case "camera.fill": String(localized: "Photo spot")122        case "binoculars.fill": String(localized: "Viewpoint")123        case "tent.fill": String(localized: "Camping")124        case "flag.fill": String(localized: "Flag")125        case "mappin": String(localized: "Pin")126        case "p.circle.fill": String(localized: "Parking")127        default: String(localized: "Symbol")128        }129    }130}131132struct CollectionsScreen: View {133    @Environment(AppModel.self) private var app134    @State private var newCollection = false135    @State private var importing: PlaceCollection?136    @State private var message: String?137    @State private var shared: URL?138139    private var library: LibraryModel { app.library }140141    var body: some View {142        List {143            if !library.isAvailable {144                NoticeView("Saved places could not be opened on this device's storage.", kind: .error)145            }146            Section {147                ForEach(library.collections) { c in148                    NavigationLink { CollectionDetailScreen(collectionID: c.id) } label: {149                        HStack(spacing: ORIX.Spacing.m) {150                            Image(systemName: c.symbol).foregroundStyle(.white).frame(width: 34, height: 34).background(Color(HexColor(c.colorHex) ?? HexColor("#00A896")!), in: .circle)151                                .dynamicTypeSize(...DynamicTypeSize.xxxLarge).accessibilityHidden(true)152                            Text(c.name)153                            Spacer()154                            Text(library.places(in: c.id).count, format: .number).foregroundStyle(.secondary).monospacedDigit()155                        }156                    }157                    .accessibilityIdentifier("collections.row.\(c.name)")158                }159                .onMove { from, to in Task { await library.moveCollections(from: from, to: to) } }160            } footer: { Text("Saved places, notes and collections stay on this device. Export them to keep a copy.") }161            Section {162                Button { newCollection = true } label: { Label("New collection", systemImage: "folder.badge.plus") }.accessibilityIdentifier("collections.new")163                Button { Task { shared = await library.backupFile(); if shared == nil { message = String(localized: "There is nothing to back up yet.") } } } label: { Label("Back up everything to a file", systemImage: "externaldrive") }164                if let shared { ShareLink(item: shared) { Label("Share the backup file", systemImage: "square.and.arrow.up") } }165            }166        }167        .navigationTitle("Collections")168        .navigationBarTitleDisplayMode(.inline)169        .toolbar { ToolbarItem(placement: .topBarLeading) { EditButton() } }170        .sheet(isPresented: $newCollection) { CollectionEditor(collection: nil) }171        .alert("Collections", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { Button("OK") {} } message: { Text(message ?? "") }172        .task { await library.reload() }173    }174}175176struct CollectionDetailScreen: View {177    @Environment(AppModel.self) private var app178    @Environment(\.dismiss) private var dismiss179    let collectionID: UUID180    @State private var editing = false181    @State private var importing = false182    @State private var message: String?183    @State private var exported: URL?184    @State private var confirmDelete = false185186    private var library: LibraryModel { app.library }187188    var body: some View {189        let places = library.places(in: collectionID)190        List {191            if places.isEmpty {192                EmptyStateView("No place saved here", message: "Touch and hold the map to drop a pin, or open a search result, then choose Save.", systemImage: "mappin.and.ellipse")193                    .frame(maxWidth: .infinity).listRowBackground(Color.clear)194            }195            ForEach(places) { p in196                Button {197                    app.modal = nil198                    app.select(PlaceSelection(title: p.name, subtitle: p.address, coordinate: p.coordinate, origin: .saved(p.id.uuidString), category: p.category), moveCamera: true)199                } label: {200                    VStack(alignment: .leading, spacing: 2) {201                        // Explicit colours: inside a list button, `.primary` and `.secondary` are shades of the tint.202                        Text(p.name).foregroundStyle(Color.primary)203                        if !p.note.isEmpty { Text(p.note).font(.footnote).foregroundStyle(Color.secondary).lineLimit(2) }204                        else if let a = p.address { Text(a).font(.footnote).foregroundStyle(Color.secondary).lineLimit(1) }205                    }206                }207                .swipeActions { Button("Delete", role: .destructive) { Task { await library.delete(p) } } }208            }209            Section {210                Toggle("Show on the map", isOn: Binding(get: { !library.hiddenCollections.contains(collectionID) }, set: { on in211                    if on { library.hiddenCollections.remove(collectionID) } else { library.hiddenCollections.insert(collectionID) }212                }))213                Menu {214                    ForEach(ExchangeFormat.allCases, id: \.self) { f in215                        Button(f.rawValue.uppercased()) { Task { exported = await library.exportFile(collection: collectionID, format: f); if exported == nil { message = String(localized: "This collection is empty.") } } }216                    }217                } label: { Label("Export", systemImage: "square.and.arrow.up").frame(maxWidth: .infinity, alignment: .leading).contentShape(.rect) }218                .accessibilityIdentifier("collection.export")219                if let exported { ShareLink(item: exported) { Label("Share \(exported.lastPathComponent)", systemImage: "paperplane") } }220                Button { importing = true } label: { Label("Import GPX, GeoJSON or KML", systemImage: "square.and.arrow.down") }221                Button { editing = true } label: { Label("Rename or restyle", systemImage: "pencil") }222                Button(role: .destructive) { confirmDelete = true } label: { Label("Delete collection", systemImage: "trash") }.disabled(library.collections.count < 2)223                    .confirmationDialog("Delete this collection and the places in it?", isPresented: $confirmDelete, titleVisibility: .visible) {224                        Button("Delete", role: .destructive) { Task { if await library.deleteCollection(collectionID) { dismiss() } } }225                    }226            }227        }228        .navigationTitle(library.collection(collectionID)?.name ?? "")229        .navigationBarTitleDisplayMode(.inline)230        .sheet(isPresented: $editing) { CollectionEditor(collection: library.collection(collectionID)) }231        .fileImporter(isPresented: $importing, allowedContentTypes: [.json, .xml, .data]) { result in232            guard let url = try? result.get() else { return }233            Task {234                switch await library.importFile(url, into: collectionID) {235                case .places(let n): message = String(localized: "\(n) places added.")236                case .restored(let n): message = String(localized: "Backup restored: \(n) places.")237                case .failed(let why): message = why238                }239            }240        }241        .alert("Collection", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { Button("OK") {} } message: { Text(message ?? "") }242    }243}244245/// Creates or edits a collection: name, symbol, colour.246struct CollectionEditor: View {247    @Environment(AppModel.self) private var app248    @Environment(\.dismiss) private var dismiss249    let collection: PlaceCollection?250    @State private var name = ""251    @State private var symbol = "bookmark.fill"252    @State private var color = "#00A896"253254    var body: some View {255        NavigationStack {256            Form {257                TextField("Name", text: $name).accessibilityIdentifier("collection.name")258                Section("Symbol") { SymbolGrid(selection: $symbol, color: color) }259                Section("Colour") { ColorGrid(selection: $color) }260            }261            // A short title: it sits between Cancel and Save.262            .navigationTitle("Collection")263            .navigationBarTitleDisplayMode(.inline)264            .toolbar {265                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }266                ToolbarItem(placement: .confirmationAction) {267                    Button("Save") {268                        Task {269                            if var c = collection { c.name = name; c.symbol = symbol; c.colorHex = color; await app.library.update(c) }270                            else { await app.library.createCollection(name: name, symbol: symbol, colorHex: color) }271                            dismiss()272                        }273                    }274                    .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)275                    .accessibilityIdentifier("collection.save")276                }277            }278            .onAppear { if let c = collection { name = c.name; symbol = c.symbol; color = c.colorHex } }279        }280    }281}282283struct SymbolGrid: View {284    @Binding var selection: String285    let color: String286    var body: some View {287        LazyVGrid(columns: [GridItem(.adaptive(minimum: 44), spacing: 8)], spacing: 8) {288            ForEach(PinStyle.symbols, id: \.self) { s in289                Button { selection = s } label: {290                    Image(systemName: s).frame(width: 44, height: 44)291                        .foregroundStyle(selection == s ? Color.white : Color.primary)292                        .background(selection == s ? AnyShapeStyle(Color(HexColor(color) ?? HexColor("#00A896")!)) : AnyShapeStyle(.quaternary), in: .circle)293                }294                .buttonStyle(.plain)295                .accessibilityLabel(Text(PinStyle.name(of: s)))296                .accessibilityAddTraits(selection == s ? .isSelected : [])297            }298        }299    }300}301302struct ColorGrid: View {303    @Binding var selection: String304    var body: some View {305        LazyVGrid(columns: [GridItem(.adaptive(minimum: 44), spacing: 8)], spacing: 8) {306            ForEach(Array(PinStyle.colors.enumerated()), id: \.element) { i, c in307                Button { selection = c } label: {308                    Circle().fill(Color(HexColor(c)!)).frame(width: 36, height: 36)309                        .overlay(Circle().strokeBorder(.primary, lineWidth: selection == c ? 3 : 0).padding(-4))310                        .frame(width: 44, height: 44)311                }312                .buttonStyle(.plain)313                .accessibilityLabel(Text("Colour \(i + 1)"))314                .accessibilityAddTraits(selection == c ? .isSelected : [])315            }316        }317    }318}319320/// Saves or edits a place: name, private note, collection, pin style.321struct SavePlaceSheet: View {322    @Environment(AppModel.self) private var app323    @Environment(\.dismiss) private var dismiss324    let selection: PlaceSelection325    let existing: SavedPlace?326    @State private var name = ""327    @State private var note = ""328    @State private var collectionID: UUID?329    @State private var symbol: String?330    @State private var color: String?331332    var body: some View {333        NavigationStack {334            Form {335                TextField("Name", text: $name).accessibilityIdentifier("save.name")336                Section("Private note") {337                    TextField("Visible only on this device", text: $note, axis: .vertical).lineLimit(3...8).accessibilityIdentifier("save.note")338                }339                Picker("Collection", selection: $collectionID) {340                    ForEach(app.library.collections) { c in Label(c.name, systemImage: c.symbol).tag(Optional(c.id)) }341                }342                Section("Pin") {343                    Toggle("Use the collection's symbol and colour", isOn: Binding(get: { symbol == nil && color == nil }, set: { on in344                        if on { symbol = nil; color = nil } else { symbol = "mappin"; color = PinStyle.colors[3] }345                    }))346                    if symbol != nil || color != nil {347                        SymbolGrid(selection: Binding(get: { symbol ?? "mappin" }, set: { symbol = $0 }), color: color ?? PinStyle.colors[3])348                        ColorGrid(selection: Binding(get: { color ?? PinStyle.colors[3] }, set: { color = $0 }))349                    }350                }351                if existing != nil {352                    Button("Remove from saved places", role: .destructive) {353                        Task { if let existing { await app.library.delete(existing) }; dismiss() }354                    }355                    .accessibilityIdentifier("save.remove")356                }357            }358            .navigationTitle(existing == nil ? "Save place" : "Edit saved place")359            .navigationBarTitleDisplayMode(.inline)360            .toolbar {361                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }362                ToolbarItem(placement: .confirmationAction) {363                    Button("Save") {364                        guard let collectionID else { return }365                        Task {366                            var p = existing ?? SavedPlace(collectionID: collectionID, name: name, coordinate: selection.coordinate, address: selection.subtitle, category: selection.category)367                            p.name = name; p.note = note; p.collectionID = collectionID; p.symbol = symbol; p.colorHex = color368                            await app.library.save(p)369                            dismiss()370                        }371                    }372                    .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || collectionID == nil)373                    .accessibilityIdentifier("save.confirm")374                }375            }376            .onAppear {377                name = existing?.name ?? selection.title378                note = existing?.note ?? ""379                collectionID = existing?.collectionID ?? app.library.collections.first?.id380                symbol = existing?.symbol; color = existing?.colorHex381            }382        }383    }384}385
Files main
Menu

Theme