SPB Git

Repository Public

Scenarios4.swift 27.2 KB 464 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : sdk/ios/Example/App/Scenarios4.swift10// Module           : sdk11// Repository       : https://git.spboucher.ai/ka-maps-engine12// Created          : 2026-12-0113// Last Modified    : 2026-12-0114//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          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreLocation88import KAMaps89import SwiftUI90import UIKit9192/// SDK 0.3.0 : plaques de grappe et interface de l'hôte, mention des sources en zone d'office, échelle du texte93/// (fixe et Dynamic Type), marges comptées une fois par `fitBounds`, sélection sans liaison, grappe à la même94/// adresse, et les ajouts du moteur des phases 9 et 10 (agrégat et membres des bâtiments, bilan final,95/// `clearHighlight`, points couchés et sans contact, couleurs de grappe, `projectMany`).96extension ScenarioRunner {97    static var round4: [String] { ["zones", "textscale", "engine10", "selection"] }9899    private var mapView4: KAMapView {100        get throws {101            guard let v = map.mapView else { throw ScenarioFailure("vue absente") }102            return v103        }104    }105106    private func errors4(since m: Int) -> [String] {107        model.log[m...].compactMap { e -> String? in if case .error(let s) = e.event { return s } else { return nil } }108    }109110    /// Zones à l'image de l'écran d'exploration de Lou-Ka iOS : barre d'état, barre de recherche et bouton des111    /// filtres, rangée de puces, bandeau du compte, deux groupes de commandes. Dessinées par-dessus la carte112    /// (cadres translucides) pour que la capture montre ce qui passerait dessous.113    private func loukaZones(_ v: KAMapView) -> [CGRect] {114        let (w, top) = (v.bounds.width, v.safeAreaInsets.top)115        return [116            CGRect(x: 0, y: 0, width: w, height: top),117            CGRect(x: 12, y: top + 6, width: w - 80, height: 46),118            CGRect(x: w - 58, y: top + 6, width: 46, height: 46),119            CGRect(x: 0, y: top + 60, width: w, height: 38),120            CGRect(x: w / 2 - 125, y: top + 106, width: 250, height: 32),121            CGRect(x: w - 58, y: top + 120, width: 46, height: 92),122            CGRect(x: w - 58, y: top + 222, width: 46, height: 92),123            CGRect(x: w - 58, y: top + 324, width: 46, height: 92),124        ]125    }126127    func zones() async throws {128        try await reset(.montreal, zoom: 13.4)129        let v = try mapView4130        let c = DemoPlace.montreal.coordinate131        var pts = DemoData.markers(around: c, count: 420, brand: .louka, spread: 0.05, seed: 21)132        for i in pts.indices { pts[i].kind = i % 3 == 0 ? "good" : "high" }133        let cluster = KAClusterOptions(radius: 46, maxZoom: 17, aggregate: .median, label: .value, labelTemplate: "{value}\n{count} logements", shares: ["good"])134        var m = mark135        try await settle { map.addLayer(.markers(id: "grappes", pts, cluster: cluster)) }136        try check(errors4(since: m).isEmpty, "couche refusée : \(errors4(since: m))")137138        let rects = loukaZones(v)139        let frames: [UIView] = rects.map { r in140            let f = UIView(frame: r)141            f.backgroundColor = UIColor.white.withAlphaComponent(0.55)142            f.layer.borderColor = UIColor.black.withAlphaComponent(0.7).cgColor143            f.layer.borderWidth = 1144            f.isUserInteractionEnabled = false145            v.addSubview(f)146            return f147        }148        defer { frames.forEach { $0.removeFromSuperview() } }149        func clusters() throws -> [KARenderedMarker] { try map.renderedMarkers(layer: "grappes").filter { $0.feature.kind == .cluster } }150        func under(_ zones: [CGRect]) throws -> Int { try clusters().filter { k in zones.contains { $0.intersects(k.rect) } }.count }151152        // Sans zone déclarée : des plaques passent sous l'interface (c'est le défaut vu sur Lou-Ka 3.2.0).153        v.attributionIsObstacle = false154        try await settle { map.setObstacles([]) }155        await sleep(0.4)156        let before = try under(rects)157        let beforeAttribution = try under([v.attributionFrame])158        fact("plaques.sousInterface.avant", .number(Double(before)))159        try check(before >= 3, "le jeu d'essai doit mettre des plaques sous l'interface : \(before)")160        await checkpoint("zones-avant")161162        // Zones déclarées + mention des sources d'office.163        v.attributionIsObstacle = true164        m = mark165        try await settle { map.setObstacles(rects) }166        await sleep(0.5)167        var worst = 0168        // Tenu pendant un déplacement : trois positions de caméra.169        for (k, dx) in [0.0, 0.004, -0.006].enumerated() {170            if k > 0 { try await settle { map.jumpTo(KACamera(center: CLLocationCoordinate2D(latitude: c.latitude + dx * 0.6, longitude: c.longitude + dx), zoom: 13.4 + Double(k) * 0.3)) } }171            await sleep(0.4)172            let all = try clusters()173            let bad = all.filter { k in (rects + [v.attributionFrame]).contains { $0.intersects(k.rect) } }174            worst = max(worst, bad.count)175            try check(bad.isEmpty, "position \(k) : \(bad.count) grappes sous l'interface, dont \(bad.first.map { "\($0.rect) pastille=\($0.isPill)" } ?? "")")176            try check(all.filter(\.isPill).count >= 4, "position \(k) : il doit rester des plaques hors des zones (\(all.filter(\.isPill).count))")177            for d in all where !d.isPill {178                // Un point de grappe est petit, sur son ancre, et rend la grappe au toucher.179                try check(d.rect.width <= 24, "point de grappe trop large : \(d.rect)")180                let hit = try map.queryRendered(at: d.center, layers: ["grappes"]).first181                try check(hit?.kind == .cluster && hit?.clusterCount == d.feature.clusterCount, "point de grappe non interrogeable en \(d.center)")182            }183            fact("position\(k)", ["plaques": .number(Double(all.filter(\.isPill).count)), "points": .number(Double(all.filter { !$0.isPill }.count))])184            if k == 0 { await checkpoint("zones-apres") }185        }186        fact("plaques.sousInterface.apres", .number(Double(worst)))187        fact("plaques.sousMention.avant", .number(Double(beforeAttribution)))188        try check(map.obstacles == rects, "le contrôleur garde les zones de l'application, sans la mention : \(map.obstacles.count)")189190        // La mention des sources seule (aucune zone de l'application) : aucune pastille dessous.191        map.removeLayer("grappes")192        frames.forEach { $0.isHidden = true }193        let att = v.attributionFrame194        guard let anchor = map.unproject(CGPoint(x: att.midX, y: att.midY)) else { throw ScenarioFailure("mention hors de la carte") }195        var pills: [KAMarker] = []196        for i in 0..<24 {197            let p = CGPoint(x: att.minX + CGFloat(i % 8) * att.width / 7, y: att.minY - 20 + CGFloat(i / 8) * 26)198            if let ll = map.unproject(p) { pills.append(KAMarker(id: "a\(i)", coordinate: ll, label: "1 \(100 + i) $")) }199        }200        _ = anchor201        func pillsUnder() throws -> Int { try map.renderedMarkers(layer: "sous-mention").filter { $0.feature.kind == .marker && $0.isPill && $0.rect.intersects(v.attributionFrame) }.count }202        v.attributionIsObstacle = false203        try await settle { map.setObstacles([]); map.addLayer(.markers(id: "sous-mention", pills, cluster: nil, density: .off)) }204        await sleep(0.4)205        let pBefore = try pillsUnder()206        v.attributionIsObstacle = true207        map.mapView?.renderNow()208        await sleep(0.6)209        let pAfter = try pillsUnder()210        fact("mention.pastilles", [.number(Double(pBefore)), .number(Double(pAfter))])211        try check(pBefore > 0 && pAfter == 0, "pastilles sous la mention des sources : \(pBefore) sans la zone d'office, \(pAfter) avec")212        await checkpoint("zones-mention")213        map.removeLayer("sous-mention")214    }215216    func textScale() async throws {217        try await reset(.montreal, zoom: 14.2)218        let v = try mapView4219        let c = DemoPlace.montreal.coordinate220        let pills = DemoData.markers(around: c, count: 40, brand: .louka, spread: 0.012, seed: 9)221        try await settle { map.addLayer(.markers(id: "echelle", pills, cluster: nil, density: .off)) }222        func height() throws -> Double {223            let r = try map.renderedMarkers(layer: "echelle").filter { $0.feature.kind == .marker && $0.isPill }224            try check(!r.isEmpty, "aucune pastille dessinée")225            return Double(r.map(\.rect.height).reduce(0, +)) / Double(r.count)226        }227        await sleep(0.3)228        let h1 = try height()229        await checkpoint("textscale-1")230        try await settle { map.setTextScale(.fixed(markers: 1.5, labels: 1.2)) }231        await sleep(0.4)232        let h15 = try height()233        try check(map.appliedTextScale.markers == 1.5 && abs(map.appliedTextScale.labels - 1.2) < 0.001, "échelle rendue par le moteur : \(map.appliedTextScale)")234        try check(h15 > h1 * 1.35 && h15 < h1 * 1.65, "pastilles à 1,5 : \(h1) → \(h15)")235        await checkpoint("textscale-1-5")236        // L'échelle tient à travers un changement de thème et une reprise du rendu, sans rien rejouer.237        let theme = map.theme238        try await settle { map.setTheme(theme == .midnight ? .signature : .midnight) }239        await sleep(0.3)240        let hTheme = try height()241        try check(abs(hTheme - h15) < 1.5, "échelle perdue au changement de thème : \(h15) → \(hTheme)")242        // La carte s'arrête à la troisième perte en une minute (garde du SDK) : dans une série, `deviceloss` et243        // `engine8` en ont provoqué deux juste avant — attendre que la minute soit passée.244        await sleep(62)245        var m = mark246        v.simulateDeviceLoss()247        _ = try await wait("renderer:restarted", since: m, timeout: 15) { if case .rendererRestarted = $0 { return true } else { return false } }248        try await waitIdle(since: m, timeout: 40)249        await sleep(0.5)250        let hLost = try height()251        try check(abs(hLost - h15) < 1.5, "échelle perdue après la reprise du rendu : \(h15) → \(hLost)")252        try await settle { map.setTheme(theme) }253254        // Dynamic Type : la catégorie du système fait foi, plafonnée.255        guard let window = v.window else { throw ScenarioFailure("fenêtre absente") }256        map.setTextScale(.dynamicType(markersMaximum: 1.6, labelsMaximum: 1.3))257        await sleep(0.4)258        let hDefault = try height()259        var seen: [KAJSON] = []260        for cat in [UIContentSizeCategory.extraExtraLarge, .accessibilityMedium, .accessibilityExtraExtraExtraLarge] {261            m = mark262            window.traitOverrides.preferredContentSizeCategory = cat263            await sleep(0.8)264            let a = map.appliedTextScale265            seen.append(["category": .string(cat.rawValue), "markers": .number((a.markers * 100).rounded() / 100), "labels": .number((a.labels * 100).rounded() / 100), "height": .number((try height() * 10).rounded() / 10)])266            try check(a.markers > 1.05 && a.markers <= 1.6001 && a.labels <= 1.3001, "\(cat.rawValue) : échelle \(a)")267            if cat == .accessibilityExtraExtraExtraLarge {268                try check(abs(a.markers - 1.6) < 0.001 && abs(a.labels - 1.3) < 0.001, "plafonds attendus à la plus grande taille : \(a)")269                await checkpoint("textscale-dynamic-ax5")270            }271        }272        fact("dynamicType", .array(seen))273        fact("heights", [.number((h1 * 10).rounded() / 10), .number((h15 * 10).rounded() / 10), .number((hDefault * 10).rounded() / 10)])274        window.traitOverrides.remove(UITraitPreferredContentSizeCategory.self)275        await sleep(0.6)276        fact("dynamicType.system", .number((map.appliedTextScale.markers * 100).rounded() / 100))277        map.setTextScale(.fixed())278        await sleep(0.4)279        try check(map.appliedTextScale.markers == 1 && abs(try height() - h1) < 1.5, "retour à l'échelle 1")280        map.removeLayer("echelle")281    }282283    func engine10() async throws {284        try await reset(.montreal, zoom: 12)285        let v = try mapView4286        let c = DemoPlace.montreal.coordinate287288        // 1. Marges de contenu comptées une seule fois par fitBounds (retour n° 13).289        let box = KABounds(west: c.longitude - 0.006, south: c.latitude - 0.006, east: c.longitude + 0.006, north: c.latitude + 0.006)290        v.contentInsets = KAEdgeInsets(top: 74, leading: 0, bottom: 156, trailing: 0)291        v.cameraPaddingFollowsContentInsets = false292        try await settle { map.fitBounds(box) }293        let zPlain = map.camera.zoom294        try await settle { map.jumpTo(KACamera(center: c, zoom: 10)) }295        v.cameraPaddingFollowsContentInsets = true296        try await settle { map.fitBounds(box) }297        let zFollow = map.camera.zoom298        fact("fitBounds.zoom", [.number((zPlain * 100).rounded() / 100), .number((zFollow * 100).rounded() / 100)])299        try check(abs(zPlain - zFollow) < 0.05, "fitBounds : zoom \(zPlain) sans marge permanente, \(zFollow) avec (les marges ne doivent être comptées qu'une fois)")300        v.cameraPaddingFollowsContentInsets = false301        v.contentInsets = .zero302303        // 2. Grappe à la même adresse : le toucher s'approche au-delà du zoom des grappes (retour n° 20).304        try await settle { map.jumpTo(KACamera(center: c, zoom: 12.5)) }305        let same = (0..<5).map { KAMarker(id: "m\($0)", coordinate: c, label: "1 \(200 + $0) $") }306        try await settle { map.addLayer(.markers(id: "adresse", same, cluster: KAClusterOptions(maxZoom: 15))) }307        await sleep(0.3)308        guard let k = try map.renderedMarkers(layer: "adresse").first(where: { $0.feature.kind == .cluster }) else { throw ScenarioFailure("grappe à la même adresse absente") }309        try check(!k.feature.isExpandable, "la grappe à la même adresse ne doit pas être éclatable")310        var m = mark311        v.simulateTap(at: k.center)312        _ = try await wait("cluster:click", since: m, timeout: 5) { if case .clusterClick = $0 { return true } else { return false } }313        try await waitIdle(since: m, timeout: 30)314        fact("sameAddress.zoom", .number((map.camera.zoom * 100).rounded() / 100))315        try check(abs(map.camera.zoom - 15.6) < 0.05, "approche attendue à 15,6 : \(map.camera.zoom)")316        map.removeLayer("adresse")317318        // 3. Couleurs de grappe par couche et projection en lot.319        try await settle { map.jumpTo(KACamera(center: c, zoom: 12.2)) }320        let pts = DemoData.markers(around: c, count: 260, brand: .louka)321        m = mark322        try await settle { map.addLayer(.markers(id: "vertes", pts, cluster: KAClusterOptions(color: "#1f7a45", textColor: "#ffffff", strokeColor: "#0f3d22"))) }323        try check(errors4(since: m).isEmpty, "couleurs de grappe refusées : \(errors4(since: m))")324        await checkpoint("engine10-grappes-couleur")325        let sample = Array(pts.prefix(40)).map(\.coordinate)326        let many = try map.projectMany(sample)327        try check(many.count == sample.count, "projectMany : \(many.count) résultats pour \(sample.count) positions")328        var worst = 0.0329        for (i, p) in many.enumerated() {330            guard let p, let one = map.project(sample[i]) else { continue }331            worst = max(worst, Double(hypot(p.point.x - one.x, p.point.y - one.y)))332            try check(p.isVisible == v.bounds.contains(p.point), "projectMany.isVisible incohérent en \(p.point)")333        }334        fact("projectMany.worstPx", .number((worst * 100).rounded() / 100))335        try check(worst < 0.5, "projectMany s'écarte de project : \(worst) points")336        map.removeLayer("vertes")337338        // 4. Couche buildings : agrégat, membres, bilan final ; clearHighlight.339        try await settle { map.jumpTo(KACamera(center: c, zoom: 16.4)) }340        await sleep(0.5)341        var site: CLLocationCoordinate2D?342        search: for dy in stride(from: -120.0, through: 120.0, by: 40) {343            for dx in stride(from: -120.0, through: 120.0, by: 40) {344                let p = CGPoint(x: v.bounds.midX + dx, y: v.bounds.midY + dy)345                if let f = try map.queryRendered(at: p, layers: ["base:building"]).first, f.building != nil, let ll = map.unproject(p) {346                    site = ll347                    break search348                }349            }350        }351        guard let site else { throw ScenarioFailure("aucun bâtiment sous la vue pour l'essai") }352        let data = [KAPoint(id: "u1", coordinate: site, value: 1), KAPoint(id: "u2", coordinate: site, value: 5), KAPoint(id: "u3", coordinate: site, value: 9)]353        m = mark354        map.addLayer(.buildings(id: "plex", data, scale: KAScale(.linear, stops: [(0, "#2f6f8f"), (10, "#b5452c")]), toleranceMeters: 8, aggregate: .median))355        guard case .buildingsMatch(let match) = try await wait("buildings:match", since: m, timeout: 30, { if case .buildingsMatch(let b) = $0 { return b.layer == "plex" && b.isFinal } else { return false } }) else { throw ScenarioFailure("bilan absent") }356        fact("match", ["inside": .number(Double(match.inside)), "near": .number(Double(match.near)), "buildings": .number(Double(match.buildings)), "shared": .number(Double(match.shared)), "outOfView": .number(Double(match.outOfView)), "pending": .number(Double(match.pending))])357        try check(match.inside + match.near == 3 && match.buildings == 1 && match.shared == 3 && match.pending == 0 && match.outOfView == 0, "bilan inattendu : \(match)")358        try await waitIdle(since: m, timeout: 20)359        guard let p = map.project(site), let f = try map.queryRendered(at: p, layers: ["plex"]).first else { throw ScenarioFailure("donnée du bâtiment non rendue au toucher") }360        try check(f.kind == .building && Set(f.buildingMembers) == ["u1", "u2", "u3"] && f.buildingMemberCount == 3, "membres : \(f.buildingMembers) (\(String(describing: f.buildingMemberCount)))")361        try check(f.buildingAggregate?.rule == .median && f.buildingAggregate?.value == 5, "agrégat : \(String(describing: f.buildingAggregate))")362        await checkpoint("engine10-batiment-median")363        try await settle { map.highlightBuilding(at: site, pulse: false) }364        try check(map.clearHighlight(), "clearHighlight doit rendre vrai après highlightBuilding")365        try check(!map.clearHighlight(), "clearHighlight doit rendre faux quand il n'y a plus rien")366        map.removeLayer("plex")367368        // 5. Points couchés sur le sol et sans contact.369        try await settle { map.jumpTo(KACamera(center: c, zoom: 12.6)) }370        var dots = DemoData.points(around: c, count: 500, spread: 0.05, seed: 3)371        for i in dots.indices { dots[i].radius = 5 + Double(i % 5) * 3 }372        m = mark373        try await settle { map.addLayer(.points(id: "cercles", dots, scale: DemoData.valueScale, strokeColor: "#ffffff", strokeWidth: 1, density: .collide(gap: 2))) }374        try check(errors4(since: m).isEmpty, "density collide refusée : \(errors4(since: m))")375        // Deux cercles réellement montrés ne se touchent pas : sonde par interrogation à la position de chaque donnée.376        var shown: [(CGPoint, Double)] = []377        for d in dots {378            guard let p = map.project(d.coordinate), v.bounds.contains(p), let f = try map.queryRendered(at: p, layers: ["cercles"]).first, f.id == d.id, f.isPoint else { continue }379            shown.append((p, d.radius ?? 5))380        }381        var touching = 0382        for i in shown.indices { for j in shown.indices where j > i && Double(hypot(shown[i].0.x - shown[j].0.x, shown[i].0.y - shown[j].0.y)) < shown[i].1 + shown[j].1 { touching += 1 } }383        fact("collide", ["shown": .number(Double(shown.count)), "of": .number(Double(dots.count)), "touching": .number(Double(touching))])384        try check(shown.count >= 10 && shown.count < dots.count && touching == 0, "sans contact : \(shown.count) montrés sur \(dots.count), \(touching) paires se touchent")385        await checkpoint("engine10-points-sans-contact")386        m = mark387        try await settle { model.mode = .volumes }388        try await settle { map.addLayer(.points(id: "cercles", dots, scale: DemoData.valueScale, strokeColor: "#ffffff", strokeWidth: 1, pitchAlignment: .map, density: .collide(gap: 2))) }389        try check(errors4(since: m).isEmpty, "pitchAlignment refusé : \(errors4(since: m))")390        await checkpoint("engine10-points-couches-3d")391        map.removeLayer("cercles")392        try await settle { model.mode = .flat }393    }394395    /// Retour n° 14 : sans liaison `selection:`, une sélection posée par le contrôleur survit aux mises à jour SwiftUI.396    func selection() async throws {397        try await reset(.montreal, zoom: 13)398        let v = try mapView4399        let c = DemoPlace.montreal.coordinate400        let pills = DemoData.markers(around: c, count: 12, brand: .louka, spread: 0.01, seed: 4)401        // Deux cas : aucune liaison (le défaut), puis une liaison constante passée explicitement.402        for constant in [false, true] {403        let ctl = KAMapController()404        let probe = SelectionProbe()405        let host = UIHostingController(rootView: SelectionProbeView(probe: probe, controller: ctl, markers: pills, center: c, constantBinding: constant))406        host.view.frame = CGRect(x: 16, y: constant ? 460 : 140, width: v.bounds.width - 32, height: 300)407        v.superview?.addSubview(host.view)408        defer { host.view.removeFromSuperview() }409        var idle = false410        let token = ctl.addEventHandler { if case .idle = $0 { idle = true } }411        let end = Date().addingTimeInterval(30)412        while !idle, Date() < end { await sleep(0.05) }413        ctl.removeEventHandler(token)414        try check(idle, "la carte sans liaison n'atteint pas le repos")415        var selects = 0416        let t2 = ctl.addEventHandler { if case .select = $0 { selects += 1 } }417        guard let target = try ctl.renderedMarkers(layer: "s").first(where: { $0.feature.kind == .marker && $0.isPill })?.feature.id else { throw ScenarioFailure("aucune pastille dessinée dans la carte d'essai") }418        ctl.select(layer: "s", id: target)419        await sleep(0.5)420        try check(selects >= 1, "l'événement select n'est pas arrivé (c'est lui qui déclenchait l'effacement)")421        for _ in 0..<3 {422            probe.tick += 1423            await sleep(0.3)424        }425        ctl.removeEventHandler(t2)426        // Preuve que `updateUIView` a bien tourné : la valeur posée par la dernière passe est dans la vue.427        try check(ctl.mapView?.maximumLiveAnnotationViews == 50 + probe.tick, "updateUIView n'a pas tourné : \(String(describing: ctl.mapView?.maximumLiveAnnotationViews)) pour \(probe.tick)")428        try check(probe.updates >= 3, "SwiftUI n'a pas remis la carte à jour (\(probe.updates))")429        try check(ctl.selection == KASelection(layer: "s", id: target), "liaison constante \(constant) : sélection du contrôleur effacée par une mise à jour SwiftUI : \(String(describing: ctl.selection))")430        let state = try ctl.renderedMarkers(layer: "s").first { $0.feature.id == target }?.feature.raw["state"]?.stringValue431        try check(state == "selected", "liaison constante \(constant) : la pastille doit rester à l'état selected dans le moteur : \(String(describing: state))")432        fact(constant ? "constante" : "sansLiaison", ["updates": .number(Double(probe.updates)), "selects": .number(Double(selects))])433        if constant { await checkpoint("selection-sans-liaison") }434        }435    }436}437438@MainActor439@Observable440final class SelectionProbe {441    var tick = 0442    @ObservationIgnored var updates = 0443}444445private struct SelectionProbeView: View {446    let probe: SelectionProbe447    let controller: KAMapController448    let markers: [KAMarker]449    let center: CLLocationCoordinate2D450    let constantBinding: Bool451452    var body: some View {453        // `tick` lu ici : chaque incrément relance `updateUIView` de la carte.454        let n = probe.tick455        let _ = (probe.updates += 1)456        return KAMap(initialCamera: KACamera(center: center, zoom: 13.5), brand: .louka, layers: [.markers(id: "s", markers, cluster: nil, density: .off)], selection: constantBinding ? .constant(nil) : nil, controller: controller)457            .mapAttributionPosition(.bottomLeading)458            // Valeur qui change à chaque passe, sans toucher aux couches (remplacer les données d'une couche remet459            // les états des marqueurs à ceux des données).460            .mapCameraAnimation(duration: 0.35 + Double(n) * 0.001)461            .mapMaximumLiveAnnotations(50 + n)462    }463}464
Files main
Menu

Theme