SPB Git

Repository Public

VehiclesMapView.swift 16.5 KB 360 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/Features/Search/VehiclesMapView.swift4//  Description: carte MapKit des véhicules — étiquettes de prix au pan coupé (le montant de la portière),5//               positions à plusieurs véhicules, regroupements ; annotations mises à jour par différence.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import MapKit12import SwiftUI1314/// Commande ponctuelle envoyée à la carte (recadrage, position de l'utilisateur).15struct MapCommand: Equatable {16    enum Kind: Equatable {17        case fit(MapBounds)18        case center(lat: Double, lng: Double, spanDegrees: Double)19    }20    var kind: Kind21    var id = UUID()22}2324final class ItemAnnotation: NSObject, MKAnnotation {25    let item: MapItem26    var coordinate: CLLocationCoordinate2D { item.coordinate }27    init(_ item: MapItem) { self.item = item }28}2930struct VehiclesMapView: UIViewRepresentable {31    var items: [MapItem]32    var selectedUID: String?33    var command: MapCommand?34    var showsUser: Bool35    /// marge basse (carte du véhicule sélectionné) : le recadrage garde les étiquettes au-dessus36    var bottomInset: CGFloat = 037    /// `byUser` : la zone a changé par un geste, pas par une commande38    var onRegion: (MapBounds, CGSize, _ byUser: Bool) -> Void39    var onSelect: (String?) -> Void40    /// l'étiquette déjà sélectionnée est touchée de nouveau : ouvrir la fiche41    var onOpen: (String) -> Void = { _ in }42    /// une position à plusieurs véhicules est touchée43    var onLot: (MapItem) -> Void = { _ in }4445    func makeCoordinator() -> Coordinator { Coordinator(self) }4647    func makeUIView(context: Context) -> MKMapView {48        let map = MKMapView()49        map.delegate = context.coordinator50        // carte sobre : relief atténué, aucun point d'intérêt, pas de trafic ; nos étiquettes portent l'information51        let cfg = MKStandardMapConfiguration(elevationStyle: .flat, emphasisStyle: .muted)52        cfg.pointOfInterestFilter = .excludingAll53        cfg.showsTraffic = false54        map.preferredConfiguration = cfg55        map.showsCompass = false56        map.showsScale = false57        map.isPitchEnabled = false58        map.showsBuildings = false59        map.tintColor = UIColor(Theme.brand)60        map.register(TagAnnotationView.self, forAnnotationViewWithReuseIdentifier: TagAnnotationView.reuseID)61        map.register(ClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: ClusterAnnotationView.reuseID)62        // vue de départ : le corridor habité, de Gatineau à Québec63        map.setRegion(MKCoordinateRegion(center: .init(latitude: 46.1, longitude: -73.0), span: .init(latitudeDelta: 3.0, longitudeDelta: 5.6)), animated: false)64        let tap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.backgroundTap(_:)))65        tap.delegate = context.coordinator66        map.addGestureRecognizer(tap)67        return map68    }6970    func updateUIView(_ map: MKMapView, context: Context) {71        context.coordinator.parent = self72        updateUIView(map, coordinator: context.coordinator)73    }7475    fileprivate func updateUIView(_ map: MKMapView, coordinator co: Coordinator) {76        map.showsUserLocation = showsUser77        map.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: bottomInset, right: 0)7879        // différence d'annotations : on ne retire et n'ajoute que ce qui change (pas de clignotement)80        let wanted = Dictionary(items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })81        var existing: Set<String> = []82        var toRemove: [MKAnnotation] = []83        for case let a as ItemAnnotation in map.annotations {84            if let w = wanted[a.item.id], w == a.item { existing.insert(a.item.id) } else { toRemove.append(a) }85        }86        if !toRemove.isEmpty { map.removeAnnotations(toRemove) }87        let toAdd = items.filter { !existing.contains($0.id) }.map(ItemAnnotation.init)88        if !toAdd.isEmpty { map.addAnnotations(toAdd) }8990        if co.lastSelected != selectedUID {91            co.lastSelected = selectedUID92            for case let a as ItemAnnotation in map.annotations {93                if let v = map.view(for: a) as? TagAnnotationView { v.apply(a.item, selected: isSelected(a.item)) }94            }95        }9697        if let command, command.id != co.lastCommand, map.bounds.width > 10 {98            co.lastCommand = command.id99            co.programmatic = true100            let move: (@escaping () -> Void) -> Void = { change in101                if UIAccessibility.isReduceMotionEnabled || map.window == nil { change() }102                else { UIView.animate(withDuration: 0.6, delay: 0, options: [.curveEaseInOut, .allowUserInteraction], animations: change) }103            }104            switch command.kind {105            case .fit(let b):106                let rect = MKMapRect(bounds: b)107                move { map.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 70, left: 36, bottom: bottomInset + 40, right: 36), animated: false) }108            case .center(let lat, let lng, let span):109                move { map.setRegion(MKCoordinateRegion(center: .init(latitude: lat, longitude: lng), span: .init(latitudeDelta: span, longitudeDelta: span)), animated: false) }110            }111        }112    }113114    fileprivate func isSelected(_ item: MapItem) -> Bool {115        if case .vehicle(let uid, _) = item.kind { return uid == selectedUID }116        return false117    }118119    @MainActor120    final class Coordinator: NSObject, MKMapViewDelegate, UIGestureRecognizerDelegate {121        var parent: VehiclesMapView122        var lastCommand: UUID?123        var lastSelected: String?124        /// le prochain changement de zone vient d'une commande, pas d'un geste125        var programmatic = true126127        init(_ parent: VehiclesMapView) { self.parent = parent }128129        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {130            guard let a = annotation as? ItemAnnotation else { return nil }131            switch a.item.kind {132            case .vehicle, .lot:133                let v = mapView.dequeueReusableAnnotationView(withIdentifier: TagAnnotationView.reuseID, for: a) as! TagAnnotationView134                v.apply(a.item, selected: parent.isSelected(a.item))135                return v136            case .cluster:137                let v = mapView.dequeueReusableAnnotationView(withIdentifier: ClusterAnnotationView.reuseID, for: a) as! ClusterAnnotationView138                v.apply(a.item)139                return v140            }141        }142143        /// Apparition : les étiquettes se posent avec un léger ressort.144        func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {145            guard !UIAccessibility.isReduceMotionEnabled else { return }146            for v in views where v is ClusterAnnotationView || v is TagAnnotationView {147                let end = v.transform148                v.alpha = 0149                v.transform = end.scaledBy(x: 0.78, y: 0.78)150                UIView.animate(withDuration: 0.36, delay: 0, usingSpringWithDamping: 0.74, initialSpringVelocity: 0.3, options: [.allowUserInteraction]) {151                    v.alpha = 1152                    v.transform = end153                }154            }155        }156157        func mapView(_ mapView: MKMapView, didSelect annotation: MKAnnotation) {158            guard let a = annotation as? ItemAnnotation else { return }159            mapView.deselectAnnotation(a, animated: false)160            switch a.item.kind {161            case .vehicle(let uid, _):162                if uid == parent.selectedUID {163                    parent.onOpen(uid)164                } else {165                    Haptics.select()166                    parent.onSelect(uid)167                }168            case .lot:169                Haptics.select()170                parent.onLot(a.item)171            case .cluster:172                var region = mapView.region173                region.center = a.coordinate174                region.span = MKCoordinateSpan(latitudeDelta: max(region.span.latitudeDelta / 2.6, 0.004), longitudeDelta: max(region.span.longitudeDelta / 2.6, 0.004))175                programmatic = false176                mapView.setRegion(region, animated: true)177            }178        }179180        func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {181            // un geste de l'utilisateur sur la carte : la liste suivra la zone182            if let v = mapView.subviews.first, v.gestureRecognizers?.contains(where: { $0.state == .began || $0.state == .changed || $0.state == .ended }) == true {183                programmatic = false184            }185        }186187        func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {188            guard mapView.bounds.width > 0 else { return }189            let byUser = !programmatic190            programmatic = true191            parent.onRegion(MapBounds(region: mapView.region), mapView.bounds.size, byUser)192        }193194        func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {195            guard mapView.bounds.width > 0 else { return }196            // une commande reçue avant la mise en page est appliquée maintenant197            if let c = parent.command, c.id != lastCommand { parent.updateUIView(mapView, coordinator: self) }198            parent.onRegion(MapBounds(region: mapView.region), mapView.bounds.size, false)199        }200201        @objc func backgroundTap(_ g: UITapGestureRecognizer) {202            guard let map = g.view as? MKMapView else { return }203            let p = g.location(in: map)204            // un toucher sur une annotation est géré par didSelect205            if map.hitTest(p, with: nil) is MKAnnotationView { return }206            if map.hitTest(p, with: nil)?.superview is MKAnnotationView { return }207            parent.onSelect(nil)208        }209210        nonisolated func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }211    }212}213214extension MapBounds {215    init(region r: MKCoordinateRegion) {216        self.init(west: max(-180, r.center.longitude - r.span.longitudeDelta / 2),217                  south: max(-90, r.center.latitude - r.span.latitudeDelta / 2),218                  east: min(180, r.center.longitude + r.span.longitudeDelta / 2),219                  north: min(90, r.center.latitude + r.span.latitudeDelta / 2))220    }221}222223extension MKMapRect {224    init(bounds b: MapBounds) {225        let a = MKMapPoint(CLLocationCoordinate2D(latitude: b.north, longitude: b.west))226        let c = MKMapPoint(CLLocationCoordinate2D(latitude: b.south, longitude: b.east))227        self.init(x: min(a.x, c.x), y: min(a.y, c.y), width: max(abs(c.x - a.x), 600), height: max(abs(c.y - a.y), 600))228    }229}230231// MARK: - Vues d'annotation232233private extension UIView {234    /// Couleur du thème résolue pour l'apparence courante (les calques ne suivent pas les couleurs dynamiques).235    func ui(_ c: Color) -> UIColor { UIColor(c).resolvedColor(with: traitCollection) }236}237238/// Étiquette de prix (système de marque) : papier, hauteur 26, rayon 6, pan coupé en haut à gauche (la pente du239/// montant), pointe en bas au centre. Sélectionnée : fond pétrole, prix complet, échelle 1,08.240/// Une position à plusieurs véhicules porte leur nombre.241final class TagAnnotationView: MKAnnotationView {242    static let reuseID = "tag"243    private let label = UILabel()244    private let shape = CAShapeLayer()245    private static let height: CGFloat = 26246    private static let pointer: CGFloat = 6247248    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {249        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)250        collisionMode = .rectangle251        shape.lineWidth = 1252        shape.lineJoin = .round253        shape.shadowColor = UIColor.black.cgColor254        shape.shadowOpacity = 0.12255        shape.shadowRadius = 2256        shape.shadowOffset = CGSize(width: 0, height: 1)257        layer.addSublayer(shape)258        label.textAlignment = .center259        label.font = .monospacedDigitSystemFont(ofSize: 12.5, weight: .semibold)260        addSubview(label)261        isAccessibilityElement = true262        accessibilityTraits = .button263    }264265    @available(*, unavailable)266    required init?(coder: NSCoder) { fatalError("non pris en charge") }267268    override func prepareForReuse() {269        super.prepareForReuse()270        transform = .identity271    }272273    func apply(_ item: MapItem, selected: Bool) {274        var bg = ui(Theme.surface), fg = ui(Theme.ink), border = ui(Theme.line2)275        switch item.kind {276        case .vehicle(_, let price):277            label.text = selected ? Fmt.money(price) : Fmt.kPrice(price)278            if selected { bg = ui(Theme.brand); fg = ui(Theme.brandInk); border = bg }279            accessibilityLabel = "Véhicule à \(Fmt.money(price))\(selected ? ", sélectionné. Toucher de nouveau pour ouvrir la fiche." : "")"280            displayPriority = selected ? .required : .defaultHigh281            zPriority = selected ? .max : .defaultUnselected282        case .lot(let count, let minPrice, let city, _):283            // plusieurs véhicules au même endroit : un commerce, ou le centre d'une ville284            label.text = "\(Fmt.int(count)) véh."285            bg = ui(Theme.ink); fg = ui(Theme.bg); border = bg286            accessibilityLabel = "\(Fmt.int(count)) véhicules\(city.map { " à \($0)" } ?? "")\(minPrice.map { ", à partir de \(Fmt.money($0))" } ?? ""). Toucher pour les voir."287            displayPriority = .required288            zPriority = .defaultSelected289        case .cluster:290            return291        }292        label.textColor = fg293        let h = TagAnnotationView.height, p = TagAnnotationView.pointer294        let w = max(44, ceil(label.intrinsicContentSize.width) + 18)295        bounds = CGRect(x: 0, y: 0, width: w, height: h + p)296        label.frame = CGRect(x: 3, y: 0, width: w - 3, height: h)297        let path = PriceTagShape(pointer: p).path(in: CGRect(x: 0.5, y: 0.5, width: w - 1, height: h + p - 1))298        CATransaction.begin()299        CATransaction.setDisableActions(true)300        shape.path = path.cgPath301        shape.fillColor = bg.cgColor302        shape.strokeColor = border.cgColor303        CATransaction.commit()304        centerOffset = CGPoint(x: 0, y: -(h + p) / 2)305        let scale = { self.transform = selected ? CGAffineTransform(scaleX: 1.08, y: 1.08) : .identity }306        if window != nil, !UIAccessibility.isReduceMotionEnabled { UIView.animate(withDuration: 0.22, delay: 0, options: [.curveEaseOut, .allowUserInteraction], animations: scale) } else { scale() }307    }308}309310/// Regroupement de positions : plaque asphalte aux coins de 6, nombre de véhicules, cinq paliers de taille.311final class ClusterAnnotationView: MKAnnotationView {312    static let reuseID = "cluster"313    private let label = UILabel()314    private let plate = UIView()315316    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {317        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)318        collisionMode = .rectangle319        displayPriority = .required320        label.textAlignment = .center321        plate.layer.cornerRadius = 6322        plate.layer.cornerCurve = .continuous323        plate.layer.borderWidth = 1.5324        plate.layer.shadowColor = UIColor.black.cgColor325        plate.layer.shadowOpacity = 0.16326        plate.layer.shadowRadius = 2.5327        plate.layer.shadowOffset = CGSize(width: 0, height: 1.5)328        plate.isUserInteractionEnabled = false329        addSubview(plate)330        plate.addSubview(label)331        isAccessibilityElement = true332        accessibilityTraits = .button333    }334335    @available(*, unavailable)336    required init?(coder: NSCoder) { fatalError("non pris en charge") }337338    static func short(_ count: Int) -> String {339        if count < 1000 { return String(count) }340        if count < 9950 { return String(format: "%.1f k", Double(count) / 1000).replacingOccurrences(of: ".", with: ",").replacingOccurrences(of: ",0 k", with: " k") }341        return "\((count + 500) / 1000) k"342    }343344    func apply(_ item: MapItem) {345        guard case .cluster(let count, _) = item.kind else { return }346        let (fontSize, h): (CGFloat, CGFloat) = count < 10 ? (12.5, 26) : count < 100 ? (13.5, 29) : count < 1000 ? (15, 32) : count < 5000 ? (16.5, 36) : (18, 40)347        label.font = .monospacedDigitSystemFont(ofSize: fontSize, weight: .semibold)348        label.text = ClusterAnnotationView.short(count)349        let fg = ui(Theme.bg), bg = ui(Theme.ink)350        label.textColor = fg351        let w = max(h + 6, ceil(label.intrinsicContentSize.width) + fontSize * 1.2)352        bounds = CGRect(x: 0, y: 0, width: w, height: h)353        plate.frame = bounds354        plate.backgroundColor = bg355        plate.layer.borderColor = fg.cgColor356        label.frame = bounds357        accessibilityLabel = "\(Fmt.int(count)) véhicules. Toucher pour zoomer."358    }359}360
Files main
Menu

Theme