SPB Git

Repository Public

ListingsMapView.swift 23.8 KB 516 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKa/Features/Explore/ListingsMapView.swift10// Description      : carte MapKit des logements — pastilles de prix par verdict11//                    et regroupements, mises à jour par différence.12// Module           : ImmoKa13// Repository       : https://git.spboucher.ai/immo-ka-ios-v314// Project Website  : https://www.immo-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import MapKit91import SwiftUI9293/// Commande ponctuelle envoyée à la carte (recadrage, position de l'utilisateur).94struct MapCommand: Equatable {95    enum Kind: Equatable {96        case fit(MapBounds)97        case center(lat: Double, lng: Double, spanDegrees: Double)98        case zoom(factor: Double)99    }100    var kind: Kind101    var id = UUID()102}103104final class ItemAnnotation: NSObject, MKAnnotation {105    let item: MapItem106    var coordinate: CLLocationCoordinate2D { item.coordinate }107    init(_ item: MapItem) { self.item = item }108}109110struct ListingsMapView: UIViewRepresentable {111    var items: [MapItem]112    var selectedUID: String?113    var seen: Set<String>114    var command: MapCommand?115    var showsUser: Bool116    /// marge basse (tiroir de résultats) : le recadrage garde les propriétés au-dessus117    var bottomInset: CGFloat118    var onRegion: (MapBounds, CGSize) -> Void119    var onSelect: (String?) -> Void120    /// la maison déjà sélectionnée est touchée de nouveau : ouvrir la fiche depuis son cadre (coordonnées globales)121    var onOpen: (String, CGRect) -> Void = { _, _ in }122123    func makeCoordinator() -> Coordinator { Coordinator(self) }124125    func makeUIView(context: Context) -> MKMapView {126        let map = MKMapView()127        map.delegate = context.coordinator128        let cfg = MKStandardMapConfiguration(elevationStyle: .flat, emphasisStyle: .muted)129        // carte sobre : relief atténué, aucun point d'intérêt, pas de trafic — nos étiquettes portent l'information130        cfg.pointOfInterestFilter = .excludingAll131        cfg.showsTraffic = false132        map.preferredConfiguration = cfg133        map.showsCompass = false134        map.showsScale = false135        map.isPitchEnabled = true136        map.isRotateEnabled = true137        map.showsBuildings = false138        map.tintColor = UIColor(Theme.accent)139        map.register(PriceAnnotationView.self, forAnnotationViewWithReuseIdentifier: PriceAnnotationView.reuseID)140        map.register(ClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: ClusterAnnotationView.reuseID)141        // vue de départ : le corridor habité, de Gatineau à Québec142        map.setRegion(MKCoordinateRegion(center: .init(latitude: 46.1, longitude: -73.35),143                                         span: .init(latitudeDelta: 2.6, longitudeDelta: 5.2)), animated: false)144        let tap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.backgroundTap(_:)))145        tap.delegate = context.coordinator146        map.addGestureRecognizer(tap)147        return map148    }149150    func updateUIView(_ map: MKMapView, context: Context) {151        let co = context.coordinator152        co.parent = self153        map.showsUserLocation = showsUser154        map.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: bottomInset, right: 0)155156        // différence d'annotations : on ne retire/ajoute que ce qui change (pas de clignotement)157        let wanted = Dictionary(items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })158        var existing: [String: ItemAnnotation] = [:]159        var toRemove: [MKAnnotation] = []160        for case let a as ItemAnnotation in map.annotations {161            if let w = wanted[a.item.id], w == a.item { existing[a.item.id] = a } else { toRemove.append(a) }162        }163        if !toRemove.isEmpty { map.removeAnnotations(toRemove) }164        let toAdd = items.filter { existing[$0.id] == nil }.map(ItemAnnotation.init)165        if !toAdd.isEmpty { map.addAnnotations(toAdd) }166167        // état visuel (sélection, vu)168        if co.lastSelected != selectedUID || co.lastSeenCount != seen.count {169            co.lastSelected = selectedUID170            co.lastSeenCount = seen.count171            for case let a as ItemAnnotation in map.annotations {172                if let v = map.view(for: a) as? PriceAnnotationView { v.apply(a.item, selected: isSelected(a.item), seen: isSeen(a.item)) }173            }174        }175176        if let command, command.id != co.lastCommand {177            co.lastCommand = command.id178            // transitions de caméra douces (courbe d'aisance, 0,65 s), sauf si Réduire les animations est actif179            let move: (@escaping () -> Void) -> Void = { change in180                if UIAccessibility.isReduceMotionEnabled { change() }181                else { UIView.animate(withDuration: 0.65, delay: 0, options: [.curveEaseInOut, .allowUserInteraction], animations: change) }182            }183            switch command.kind {184            case .fit(let b):185                let rect = MKMapRect(bounds: b)186                move { map.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 130, left: 40, bottom: bottomInset + 40, right: 40), animated: false) }187            case .center(let lat, let lng, let span):188                move { map.setRegion(MKCoordinateRegion(center: .init(latitude: lat, longitude: lng),189                                                        span: .init(latitudeDelta: span, longitudeDelta: span)), animated: false) }190            case .zoom(let factor):191                var region = map.region192                region.span = MKCoordinateSpan(latitudeDelta: min(40, max(0.002, region.span.latitudeDelta * factor)),193                                               longitudeDelta: min(40, max(0.002, region.span.longitudeDelta * factor)))194                move { map.setRegion(region, animated: false) }195            }196        }197    }198199    fileprivate func isSelected(_ item: MapItem) -> Bool {200        if case .single(let uid, _, _) = item.kind { return uid == selectedUID }201        return false202    }203204    fileprivate func isSeen(_ item: MapItem) -> Bool {205        if case .single(let uid, _, _) = item.kind { return seen.contains(uid) }206        return false207    }208209    @MainActor210    final class Coordinator: NSObject, MKMapViewDelegate, UIGestureRecognizerDelegate {211        var parent: ListingsMapView212        var lastCommand: UUID?213        var lastSelected: String?214        var lastSeenCount = 0215216        init(_ parent: ListingsMapView) { self.parent = parent }217218        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {219            guard let a = annotation as? ItemAnnotation else { return nil }220            switch a.item.kind {221            case .single:222                let v = mapView.dequeueReusableAnnotationView(withIdentifier: PriceAnnotationView.reuseID, for: a) as! PriceAnnotationView223                v.apply(a.item, selected: parent.isSelected(a.item), seen: parent.isSeen(a.item))224                return v225            case .cluster:226                let v = mapView.dequeueReusableAnnotationView(withIdentifier: ClusterAnnotationView.reuseID, for: a) as! ClusterAnnotationView227                v.apply(a.item)228                return v229            }230        }231232        /// Apparition : les plaques et les étiquettes se posent avec un léger ressort (fusion et éclatement des regroupements).233        func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {234            guard !UIAccessibility.isReduceMotionEnabled else { return }235            for v in views where v is ClusterAnnotationView || v is PriceAnnotationView {236                v.alpha = 0237                v.transform = CGAffineTransform(scaleX: 0.72, y: 0.72)238                UIView.animate(withDuration: 0.42, delay: 0, usingSpringWithDamping: 0.68, initialSpringVelocity: 0.4, options: [.allowUserInteraction]) {239                    v.alpha = 1240                    v.transform = .identity241                }242            }243        }244245        func mapView(_ mapView: MKMapView, didSelect annotation: MKAnnotation) {246            guard let a = annotation as? ItemAnnotation else { return }247            mapView.deselectAnnotation(a, animated: false)248            switch a.item.kind {249            case .single(let uid, _, _):250                if uid == parent.selectedUID, let v = mapView.view(for: a) {251                    parent.onOpen(uid, v.convert(v.bounds, to: nil))252                } else {253                    Haptics.select()254                    parent.onSelect(uid)255                }256            case .cluster:257                // zoom sur le regroupement258                var region = mapView.region259                region.center = a.coordinate260                region.span = MKCoordinateSpan(latitudeDelta: max(region.span.latitudeDelta / 2.6, 0.0025),261                                               longitudeDelta: max(region.span.longitudeDelta / 2.6, 0.0025))262                mapView.setRegion(region, animated: true)263            }264        }265266        func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {267            report(mapView)268        }269270        func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {271            report(mapView)272        }273274        private func report(_ mapView: MKMapView) {275            guard mapView.bounds.width > 0 else { return }276            parent.onRegion(MapBounds(region: mapView.region), mapView.bounds.size)277        }278279        @objc func backgroundTap(_ g: UITapGestureRecognizer) {280            guard let map = g.view as? MKMapView else { return }281            let p = g.location(in: map)282            // un toucher sur une annotation est géré par didSelect283            if map.hitTest(p, with: nil) is MKAnnotationView { return }284            if map.hitTest(p, with: nil)?.superview is MKAnnotationView { return }285            parent.onSelect(nil)286        }287288        nonisolated func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }289    }290}291292extension MapBounds {293    init(region r: MKCoordinateRegion) {294        self.init(west: max(-180, r.center.longitude - r.span.longitudeDelta / 2),295                  south: max(-90, r.center.latitude - r.span.latitudeDelta / 2),296                  east: min(180, r.center.longitude + r.span.longitudeDelta / 2),297                  north: min(90, r.center.latitude + r.span.latitudeDelta / 2))298    }299}300301extension MKMapRect {302    init(bounds b: MapBounds) {303        let a = MKMapPoint(CLLocationCoordinate2D(latitude: b.north, longitude: b.west))304        let c = MKMapPoint(CLLocationCoordinate2D(latitude: b.south, longitude: b.east))305        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))306    }307}308309// MARK: - Vues d'annotation310311private extension UIView {312    /// Couleur du thème résolue pour l'apparence courante de la vue (les calques ne suivent pas les couleurs dynamiques).313    func ui(_ c: Color) -> UIColor { UIColor(c).resolvedColor(with: traitCollection) }314}315316private func serifFont(_ size: CGFloat, weight: UIFont.Weight) -> UIFont {317    let base = UIFont.systemFont(ofSize: size, weight: weight)318    return base.fontDescriptor.withDesign(.serif).map { UIFont(descriptor: $0, size: size) } ?? base319}320321/// Étiquette de prix maison : papier, coins nets, petite pointe vers le point. « Bon prix » en forêt, « élevé »322/// en liseré ocre, « vu » estompé. Sélectionnée, elle laisse place à la porte Immo-Ka qui s'entrouvre.323/// Étiquette de prix (système de marque, § 6) : papier, hauteur 26, rayon 6, pointe de 8. Bon prix : liseré vert ;324/// déjà vue : atténuée. Sélectionnée : fond charbon, échelle 1,08, la maison du symbole (18 pt) apparaît en325/// 220 ms et son battant s'ouvre en 500 ms.326final class PriceAnnotationView: MKAnnotationView {327    static let reuseID = "price"328    private let label = UILabel()329    private let shape = CAShapeLayer()330    private let house = UIView()331    private let houseBody = CAShapeLayer()332    private let housePanel = CAShapeLayer()333    private var wasSelected = false334    private static let height: CGFloat = 26335    private static let pointer: CGFloat = 5336    private static let houseSide: CGFloat = 18337338    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {339        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)340        collisionMode = .rectangle341        shape.lineWidth = 1342        shape.lineJoin = .round343        shape.shadowColor = UIColor.black.cgColor344        shape.shadowOpacity = 0.14345        shape.shadowRadius = 2.5346        shape.shadowOffset = CGSize(width: 0, height: 1.5)347        layer.addSublayer(shape)348        label.textAlignment = .center349        label.font = .monospacedDigitSystemFont(ofSize: 12.5, weight: .semibold)350        addSubview(label)351        house.isUserInteractionEnabled = false352        house.alpha = 0353        houseBody.fillRule = .evenOdd354        house.layer.addSublayer(houseBody)355        house.layer.addSublayer(housePanel)356        addSubview(house)357        isAccessibilityElement = true358        accessibilityTraits = .button359    }360361    @available(*, unavailable)362    required init?(coder: NSCoder) { fatalError("non pris en charge") }363364    override func prepareForReuse() {365        super.prepareForReuse()366        wasSelected = false367        house.alpha = 0368        transform = .identity369        housePanel.removeAllAnimations()370    }371372    func apply(_ item: MapItem, selected: Bool, seen: Bool) {373        guard case .single(_, let price, let verdict) = item.kind else { return }374        label.text = Fmt.shortPrice(price)375        var bg = ui(Theme.surface), fg = ui(Theme.ink), border = ui(Theme.line2)376        var lineWidth: CGFloat = 1377        switch verdict {378        case .sous: border = ui(Theme.good); fg = ui(Theme.good); lineWidth = 1.5379        case .sur: fg = ui(Theme.high)380        default: break381        }382        if seen { bg = ui(Theme.surface2); fg = ui(Theme.ink3); border = ui(Theme.line); lineWidth = 1 }383        if selected { bg = ui(Theme.ink); fg = ui(Theme.bg); border = bg; lineWidth = 1 }384        label.textColor = fg385        alpha = seen && !selected ? 0.82 : 1386387        let h = PriceAnnotationView.height, p = PriceAnnotationView.pointer, side = PriceAnnotationView.houseSide388        let text = ceil(label.intrinsicContentSize.width)389        // sélectionnée : la maison prend place à gauche du prix390        let slot: CGFloat = selected ? side + 6 - 2 : 0391        let w = max(40, text + 16 + slot)392        let animate = selected != wasSelected && !UIAccessibility.isReduceMotionEnabled && window != nil393        let layout = {394            self.bounds = CGRect(x: 0, y: 0, width: w, height: h + p)395            self.label.frame = CGRect(x: 8 + slot, y: 0, width: w - 16 - slot, height: h)396            self.house.frame = CGRect(x: 6, y: (h - side) / 2, width: side, height: side)397            self.house.alpha = selected ? 1 : 0398            self.transform = selected ? CGAffineTransform(scaleX: 1.08, y: 1.08) : .identity399        }400        // étiquette à coins de rayon 6 et pointe de 8 centrée vers le point401        let plate = CGRect(x: 0.5, y: 0.5, width: w - 1, height: h - 1)402        let path = UIBezierPath(roundedRect: plate, cornerRadius: 6)403        let tip = UIBezierPath()404        tip.move(to: CGPoint(x: w / 2 - 5, y: h - 0.5))405        tip.addLine(to: CGPoint(x: w / 2, y: h + p - 0.5))406        tip.addLine(to: CGPoint(x: w / 2 + 5, y: h - 0.5))407        tip.close()408        path.append(tip)409        CATransaction.begin()410        CATransaction.setDisableActions(true)411        shape.path = path.cgPath412        shape.fillColor = bg.cgColor413        shape.strokeColor = border.cgColor414        shape.lineWidth = lineWidth415        layoutHouse()416        CATransaction.commit()417        if animate { UIView.animate(withDuration: 0.22, delay: 0, options: [.curveEaseOut, .allowUserInteraction], animations: layout) } else { layout() }418        centerOffset = CGPoint(x: 0, y: -(h + p) / 2)419        if selected, !wasSelected { swingDoor() }420        wasSelected = selected421        displayPriority = selected ? .required : (verdict == .sous ? .defaultHigh : (seen ? .defaultLow : MKFeatureDisplayPriority(rawValue: 600)))422        zPriority = selected ? .max : (verdict == .sous ? .defaultUnselected : .min)423        accessibilityLabel = "Propriété à \(Listing.priceIsPlausible(price) ? Fmt.money(price) : "prix sur demande")\(verdict.map { ", \($0.label)" } ?? "")\(selected ? ", sélectionnée. Toucher de nouveau pour ouvrir la fiche." : "")"424    }425426    private func layoutHouse() {427        let r = CGRect(x: 0, y: 0, width: PriceAnnotationView.houseSide, height: PriceAnnotationView.houseSide)428        houseBody.frame = r429        housePanel.frame = r430        // variante micro du symbole : maison couleur du fond sur l'étiquette charbon, battant rouge431        houseBody.path = HouseBodyShape(micro: true).path(in: r).cgPath432        houseBody.fillColor = ui(Theme.bg).cgColor433        housePanel.fillColor = ui(Theme.accent).cgColor434    }435436    /// Le battant s'ouvre en 500 ms (après l'apparition de la maison), avec un léger dépassement ; immobile si437    /// Réduire les animations.438    private func swingDoor() {439        let r = CGRect(x: 0, y: 0, width: PriceAnnotationView.houseSide, height: PriceAnnotationView.houseSide)440        let closed = HousePanelShape(angle: 0, micro: true).path(in: r).cgPath441        let open = HousePanelShape(angle: 62, micro: true).path(in: r).cgPath442        housePanel.path = open443        guard !UIAccessibility.isReduceMotionEnabled else { return }444        let spring = CASpringAnimation(keyPath: "path")445        spring.fromValue = closed446        spring.toValue = open447        spring.damping = 12448        spring.stiffness = 150449        spring.mass = 1450        spring.beginTime = CACurrentMediaTime() + 0.12451        spring.fillMode = .backwards452        spring.duration = min(0.6, spring.settlingDuration)453        housePanel.add(spring, forKey: "swing")454    }455}456457final class ClusterAnnotationView: MKAnnotationView {458    static let reuseID = "cluster"459    private let label = UILabel()460    private let plate = UIView()461    private let lintel = UIView()462    private let share = UIView()463464    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {465        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)466        collisionMode = .rectangle467        displayPriority = .required468        label.textAlignment = .center469        plate.layer.cornerRadius = 3470        plate.layer.cornerCurve = .continuous471        plate.layer.borderWidth = 1.5472        plate.layer.shadowColor = UIColor.black.cgColor473        plate.layer.shadowOpacity = 0.2474        plate.layer.shadowRadius = 3475        plate.layer.shadowOffset = CGSize(width: 0, height: 2)476        plate.isUserInteractionEnabled = false477        lintel.layer.cornerRadius = 1.5478        lintel.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]479        share.layer.cornerRadius = 1480        addSubview(plate)481        plate.addSubview(lintel)482        plate.addSubview(share)483        plate.addSubview(label)484        isAccessibilityElement = true485        accessibilityTraits = .button486    }487488    @available(*, unavailable)489    required init?(coder: NSCoder) { fatalError("non pris en charge") }490491    func apply(_ item: MapItem) {492        guard case .cluster(let count, let good, _) = item.kind else { return }493        // taille selon le nombre : cinq paliers494        let (fontSize, h): (CGFloat, CGFloat) = count < 10 ? (13, 26) : count < 100 ? (14.5, 29) : count < 1000 ? (16, 32) : count < 5000 ? (18, 36) : (20, 41)495        label.font = serifFont(fontSize, weight: .medium)496        label.text = count < 1000 ? String(count) : (count < 9950 && (count + 50) / 100 % 10 != 0 ? String(format: "%.1f k", Double(count) / 1000).replacingOccurrences(of: ".", with: ",") : "\((count + 500) / 1000) k")497        let fg = ui(Theme.bg), bg = ui(Theme.house)498        label.textColor = fg499        let w = max(h + 4, ceil(label.intrinsicContentSize.width) + fontSize * 1.15)500        bounds = CGRect(x: 0, y: 0, width: w, height: h)501        plate.frame = bounds502        plate.backgroundColor = bg503        plate.layer.borderColor = fg.cgColor504        plate.clipsToBounds = false505        lintel.frame = CGRect(x: 1.5, y: 1.5, width: w - 3, height: 3)506        lintel.backgroundColor = ui(Theme.accent)507        label.frame = CGRect(x: 0, y: 3, width: w, height: h - 5)508        // part de bons prix : petite barre en bas à gauche509        let ratio = count > 0 ? CGFloat(good) / CGFloat(count) : 0510        share.isHidden = good == 0511        share.backgroundColor = UIColor(Color(hex: 0x8FC7A8))512        share.frame = CGRect(x: 6, y: h - 5.5, width: max(5, (w - 12) * min(1, ratio * 2.2)), height: 2)513        accessibilityLabel = "\(count) propriétés\(good > 0 ? ", dont \(good) sous le prix attendu" : ""). Toucher pour zoomer."514    }515}516
Files main
Menu

Theme