SPB Git

Repository Public

ListingsMapView.swift 24.4 KB 530 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Features/Explore/ListingsMapView.swift10// Description      : carte MapKit des logements — pastilles de prix par verdict11//                    et regroupements, mises à jour par différence.12// Module           : LouKa13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-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 logements au-dessus117    var bottomInset: CGFloat118    var onRegion: (MapBounds, CGSize) -> Void119    var onSelect: (String?) -> Void120    /// la pastille 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.heritageOrange)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 Lou-Ka qui s'entrouvre.323final class PriceAnnotationView: MKAnnotationView {324    static let reuseID = "price"325    private let label = UILabel()326    private let shape = CAShapeLayer()327    // la porte de la sélection328    private let door = UIView()329    private let doorFrame = CAShapeLayer()330    private let doorPanel = CALayer()331    private let doorHinge = CATransformLayer()332    private let doorSill = CALayer()333    private var wasSelected = false334    private static let pointer: CGFloat = 5335336    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {337        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)338        collisionMode = .rectangle339        shape.lineWidth = 1340        shape.shadowColor = UIColor.black.cgColor341        shape.shadowOpacity = 0.14342        shape.shadowRadius = 2.5343        shape.shadowOffset = CGSize(width: 0, height: 1.5)344        layer.addSublayer(shape)345        label.textAlignment = .center346        addSubview(label)347        // porte : encadrement orange (deux montants, un linteau), battant sur charnières à gauche, seuil348        door.isHidden = true349        door.isUserInteractionEnabled = false350        doorFrame.fillColor = UIColor.clear.cgColor351        doorFrame.lineJoin = .round352        var persp = CATransform3DIdentity353        persp.m34 = -1 / 90354        doorHinge.sublayerTransform = persp355        doorPanel.anchorPoint = CGPoint(x: 0, y: 0.5)356        doorHinge.addSublayer(doorPanel)357        door.layer.addSublayer(doorHinge)358        door.layer.addSublayer(doorFrame)359        door.layer.addSublayer(doorSill)360        addSubview(door)361        isAccessibilityElement = true362        accessibilityTraits = .button363    }364365    @available(*, unavailable)366    required init?(coder: NSCoder) { fatalError("non pris en charge") }367368    override func prepareForReuse() {369        super.prepareForReuse()370        wasSelected = false371        doorPanel.removeAllAnimations()372    }373374    func apply(_ item: MapItem, selected: Bool, seen: Bool) {375        guard case .single(_, let price, let verdict) = item.kind else { return }376        label.text = Fmt.shortPrice(price)377        var bg = ui(Theme.surface), fg = ui(Theme.ink), border = ui(Theme.line2)378        var lineWidth: CGFloat = 1379        switch verdict {380        case .sous: bg = ui(Theme.brand); fg = ui(Theme.brandInk); border = bg381        case .sur: border = ui(Theme.high); fg = ui(Theme.high); lineWidth = 1.5382        default: break383        }384        if seen, !selected { bg = ui(Theme.surface3); fg = ui(Theme.ink3); border = ui(Theme.line); lineWidth = 1 }385        label.font = .monospacedDigitSystemFont(ofSize: 12.5, weight: .bold)386        label.textColor = selected ? ui(Theme.ink) : fg387        alpha = seen && !selected ? 0.78 : 1388389        let w = max(36, ceil(label.intrinsicContentSize.width) + 16), h: CGFloat = 24390        if selected {391            // la porte s'ouvre à la place de l'étiquette ; le prix reste lisible juste dessous392            let dw: CGFloat = 26, dh: CGFloat = 37.5, gap: CGFloat = 3393            let total = CGSize(width: max(w, dw + 8), height: dh + gap + h)394            bounds = CGRect(origin: .zero, size: total)395            door.isHidden = false396            door.frame = CGRect(x: (total.width - dw) / 2, y: 0, width: dw, height: dh)397            layoutDoor(in: door.bounds)398            let plate = CGRect(x: (total.width - w) / 2, y: dh + gap, width: w, height: h)399            shape.path = UIBezierPath(roundedRect: plate, cornerRadius: 3).cgPath400            shape.fillColor = ui(Theme.surface).cgColor401            shape.strokeColor = UIColor(Theme.heritageOrange).cgColor402            shape.lineWidth = 1.5403            label.frame = plate404            // le seuil de la porte repose sur le point ; le prix est juste dessous405            centerOffset = CGPoint(x: 0, y: total.height / 2 - dh)406            if !wasSelected { swingDoor() }407        } else {408            door.isHidden = true409            let p = PriceAnnotationView.pointer410            bounds = CGRect(x: 0, y: 0, width: w, height: h + p)411            let plate = CGRect(x: 0.5, y: 0.5, width: w - 1, height: h - 1)412            // rectangle à coins nets et petite pointe centrée vers le point413            let path = UIBezierPath(roundedRect: plate, cornerRadius: 3)414            let tip = UIBezierPath()415            tip.move(to: CGPoint(x: w / 2 - 5, y: h - 0.5))416            tip.addLine(to: CGPoint(x: w / 2, y: h + p - 0.5))417            tip.addLine(to: CGPoint(x: w / 2 + 5, y: h - 0.5))418            tip.close()419            path.append(tip)420            shape.path = path.cgPath421            shape.fillColor = bg.cgColor422            shape.strokeColor = border.cgColor423            shape.lineWidth = lineWidth424            label.frame = CGRect(x: 0, y: 0, width: w, height: h)425            centerOffset = CGPoint(x: 0, y: -(h + p) / 2)426        }427        wasSelected = selected428        displayPriority = selected ? .required : (verdict == .sous ? .defaultHigh : (seen ? .defaultLow : MKFeatureDisplayPriority(rawValue: 600)))429        zPriority = selected ? .max : (verdict == .sous ? .defaultUnselected : .min)430        accessibilityLabel = "Logement à \(price.map { Fmt.money($0) } ?? "prix sur demande")\(verdict.map { ", \($0.label)" } ?? "")\(selected ? ", sélectionné. Toucher de nouveau pour ouvrir la fiche." : "")"431    }432433    private func layoutDoor(in r: CGRect) {434        let t = r.width * DoorGeometry.frame435        let path = DoorFrameShape(radius: 2).path(in: CGRect(x: t / 2, y: t / 2, width: r.width - t, height: r.height - t / 2))436        doorFrame.path = path.cgPath437        doorFrame.strokeColor = UIColor(Theme.heritageOrange).cgColor438        doorFrame.lineWidth = t439        doorFrame.frame = r440        let inner = CGRect(x: t, y: t, width: r.width - 2 * t, height: r.height - t)441        doorHinge.frame = inner442        CATransaction.begin()443        CATransaction.setDisableActions(true)444        doorPanel.bounds = CGRect(origin: .zero, size: inner.size)445        doorPanel.position = CGPoint(x: 0, y: inner.height / 2)446        doorPanel.backgroundColor = ui(Theme.doorPanel).cgColor447        doorSill.backgroundColor = ui(Theme.doorPanel).cgColor448        doorSill.frame = CGRect(x: -r.width * 0.12, y: r.height - 1, width: r.width * 1.24, height: 2.5)449        doorSill.cornerRadius = 1.25450        CATransaction.commit()451    }452453    /// La porte s'entrouvre à 40° avec un léger dépassement (ressort) ; immobile si Réduire les animations.454    private func swingDoor() {455        let open = CATransform3DMakeRotation(40 * .pi / 180, 0, 1, 0)456        doorPanel.transform = open457        guard !UIAccessibility.isReduceMotionEnabled else { return }458        let spring = CASpringAnimation(keyPath: "transform")459        spring.fromValue = CATransform3DIdentity460        spring.toValue = open461        spring.damping = 11462        spring.stiffness = 170463        spring.mass = 1464        spring.duration = spring.settlingDuration465        doorPanel.add(spring, forKey: "swing")466    }467}468469/// Regroupement en « plaque civique » : rectangle à coins nets (charbon en thème clair, ivoire en thème sombre),470/// chiffres en New York, fin linteau orange, petite barre forêt = part de bons prix ; taille selon le nombre.471final class ClusterAnnotationView: MKAnnotationView {472    static let reuseID = "cluster"473    private let label = UILabel()474    private let plate = UIView()475    private let lintel = UIView()476    private let share = UIView()477478    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {479        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)480        collisionMode = .rectangle481        displayPriority = .required482        label.textAlignment = .center483        plate.layer.cornerRadius = 3484        plate.layer.cornerCurve = .continuous485        plate.layer.borderWidth = 1.5486        plate.layer.shadowColor = UIColor.black.cgColor487        plate.layer.shadowOpacity = 0.2488        plate.layer.shadowRadius = 3489        plate.layer.shadowOffset = CGSize(width: 0, height: 2)490        plate.isUserInteractionEnabled = false491        lintel.layer.cornerRadius = 1.5492        lintel.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]493        share.layer.cornerRadius = 1494        addSubview(plate)495        plate.addSubview(lintel)496        plate.addSubview(share)497        plate.addSubview(label)498        isAccessibilityElement = true499        accessibilityTraits = .button500    }501502    @available(*, unavailable)503    required init?(coder: NSCoder) { fatalError("non pris en charge") }504505    func apply(_ item: MapItem) {506        guard case .cluster(let count, let good, _) = item.kind else { return }507        // taille selon le nombre : cinq paliers508        let (fontSize, h): (CGFloat, CGFloat) = count < 10 ? (13, 26) : count < 100 ? (14.5, 29) : count < 1000 ? (16, 32) : count < 5000 ? (18, 36) : (20, 41)509        label.font = serifFont(fontSize, weight: .medium)510        label.text = count < 1000 ? String(count) : String(format: "%.1f k", Double(count) / 1000).replacingOccurrences(of: ".", with: ",")511        let fg = ui(Theme.bg), bg = ui(Theme.doorPanel)512        label.textColor = fg513        let w = max(h + 4, ceil(label.intrinsicContentSize.width) + fontSize * 1.15)514        bounds = CGRect(x: 0, y: 0, width: w, height: h)515        plate.frame = bounds516        plate.backgroundColor = bg517        plate.layer.borderColor = fg.cgColor518        plate.clipsToBounds = false519        lintel.frame = CGRect(x: 1.5, y: 1.5, width: w - 3, height: 3)520        lintel.backgroundColor = UIColor(Theme.heritageOrange)521        label.frame = CGRect(x: 0, y: 3, width: w, height: h - 5)522        // part de bons prix : petite barre en bas à gauche523        let ratio = count > 0 ? CGFloat(good) / CGFloat(count) : 0524        share.isHidden = good == 0525        share.backgroundColor = UIColor(Color(hex: 0x7DB69C))526        share.frame = CGRect(x: 6, y: h - 5.5, width: max(5, (w - 12) * min(1, ratio * 2.2)), height: 2)527        accessibilityLabel = "\(count) logements\(good > 0 ? ", dont \(good) bons prix" : ""). Toucher pour zoomer."528    }529}530
Files main
Menu

Theme