Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : sdk/web/src/overlay.ts9 * Module : sdk10 * Repository : https://git.spboucher.ai/ka-maps-engine11 * Created : 2026-12-0112 * Last Modified : 2026-12-0113 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Calque DOM : positionne des éléments fournis par le site à une coordonnée, à chaque trame où la43// caméra bouge. Sert aux marqueurs DOM, aux infobulles (« popups ») et aux boutons mandataires qui44// rendent chaque marqueur du canvas accessible au clavier et aux lecteurs d'écran.45//46// Tout le style passe par le CSSOM (`element.style.x = …`) : compatible avec une CSP sans47// `style-src 'unsafe-inline'`.4849import type { LngLat, MarkerProxyHandle, MarkerProxyItem, MarkerProxyOptions, OverlayAnchor, OverlayHandle, OverlayOptions } from './types.js';5051export interface OverlayHost {52 /** `[lon, lat, …]` → `[x, y, …]` en pixels CSS (NaN hors champ). */53 projectMany(lngLats: Float64Array): Float64Array;54 size(): [number, number];55 requestFrame(): void;56 /** Survol au point de la coordonnée (même logique que la souris : une pastille sélectionnée le reste) ; `null` : plus de survol. */57 hoverAt(lngLat: LngLat | null): void;58 centerOn(lngLat: LngLat): void;59 hintText(): string;60}6162const ANCHOR: Record<OverlayAnchor, [number, number]> = {63 center: [-50, -50],64 top: [-50, 0],65 bottom: [-50, -100],66 left: [0, -50],67 right: [-100, -50],68 'top-left': [0, 0],69 'top-right': [-100, 0],70 'bottom-left': [0, -100],71 'bottom-right': [-100, -100],72};7374interface Entry {75 el: HTMLElement;76 lngLat: LngLat;77 anchor: [number, number];78 offset: [number, number];79 hideOutside: boolean;80 shown: boolean;81 /** Mandataire : reste dans l'ordre de tabulation même hors de la vue. */82 proxy: boolean;83 interactive: boolean;84 /** Zone de l'hôte pour le moteur (voir `OverlayOptions.obstacle`). */85 obstacle: boolean;86 x: number;87 y: number;88}8990export class OverlayLayer {91 readonly root: HTMLDivElement;92 private entries: Entry[] = [];93 private coords = new Float64Array(0);94 private dirty = true;95 private suspended = false;9697 constructor(98 parent: HTMLElement,99 private host: OverlayHost,100 ) {101 const d = document.createElement('div');102 d.className = 'ka-maps-overlay';103 const s = d.style;104 s.position = 'absolute';105 s.left = '0';106 s.top = '0';107 s.width = '100%';108 s.height = '100%';109 s.overflow = 'hidden';110 s.pointerEvents = 'none';111 parent.appendChild(d);112 this.root = d;113 }114115 get count(): number {116 return this.entries.length;117 }118119 add(el: HTMLElement, lngLat: LngLat, options: OverlayOptions = {}, proxy = false): OverlayHandle {120 const entry: Entry = { el, lngLat: [lngLat[0], lngLat[1]], anchor: ANCHOR.bottom, offset: [0, 0], hideOutside: true, shown: false, proxy, interactive: !proxy, obstacle: false, x: 0, y: 0 };121 const apply = (o: OverlayOptions) => {122 if (o.interactive !== undefined && !proxy) {123 entry.interactive = o.interactive;124 el.style.pointerEvents = entry.interactive && !this.suspended ? 'auto' : 'none';125 }126 if (o.obstacle !== undefined) entry.obstacle = o.obstacle && !proxy;127 if (o.anchor) entry.anchor = ANCHOR[o.anchor] ?? ANCHOR.bottom;128 if (o.offset) entry.offset = [o.offset[0], o.offset[1]];129 if (o.hideWhenOutside !== undefined) entry.hideOutside = o.hideWhenOutside;130 if (o.zIndex !== undefined) el.style.zIndex = String(o.zIndex);131 };132 apply(options);133 const s = el.style;134 s.position = 'absolute';135 s.left = '0';136 s.top = '0';137 // Mandataires : la souris et le toucher traversent vers le canvas (un seul chemin pour les gestes).138 s.pointerEvents = entry.interactive && !this.suspended ? 'auto' : 'none';139 s.willChange = 'transform';140 s.visibility = 'hidden';141 this.root.appendChild(el);142 this.entries.push(entry);143 this.invalidate();144 return {145 element: el,146 setLngLat: (ll) => {147 entry.lngLat = [ll[0], ll[1]];148 this.invalidate();149 },150 getLngLat: () => [entry.lngLat[0], entry.lngLat[1]],151 setOptions: (o) => {152 apply(o);153 this.invalidate();154 },155 remove: () => {156 const i = this.entries.indexOf(entry);157 if (i >= 0) this.entries.splice(i, 1);158 el.remove();159 this.invalidate();160 },161 };162 }163164 /** Faux : tout le calque laisse passer le pointeur (pendant un tracé, un choix de point) ; vrai : retour à l'état de chaque élément. */165 setInteractive(on: boolean): void {166 this.suspended = !on;167 for (const e of this.entries) e.el.style.pointerEvents = e.interactive && on ? 'auto' : 'none';168 }169170 invalidate(): void {171 this.dirty = true;172 this.host.requestFrame();173 }174175 /** Repositionne les éléments. `cameraChanged` : la caméra a bougé depuis le dernier appel. */176 update(cameraChanged: boolean): void {177 if (!this.dirty && !cameraChanged) return;178 this.dirty = false;179 const n = this.entries.length;180 if (n === 0) return;181 if (this.coords.length !== n * 2) this.coords = new Float64Array(n * 2);182 for (let i = 0; i < n; i++) {183 this.coords[i * 2] = this.entries[i].lngLat[0];184 this.coords[i * 2 + 1] = this.entries[i].lngLat[1];185 }186 const px = this.host.projectMany(this.coords);187 const [w, h] = this.host.size();188 for (let i = 0; i < n; i++) {189 const e = this.entries[i];190 const x = px[i * 2];191 const y = px[i * 2 + 1];192 const valid = Number.isFinite(x) && Number.isFinite(y);193 const inside = valid && x >= -64 && y >= -64 && x <= w + 64 && y <= h + 64;194 const s = e.el.style;195 if (e.proxy) {196 // Un mandataire hors champ reste focalisable : il est rangé dans un coin, invisible.197 const cx = inside ? x : 0;198 const cy = inside ? y : 0;199 s.transform = `translate(${cx.toFixed(1)}px, ${cy.toFixed(1)}px) translate(${e.anchor[0]}%, ${e.anchor[1]}%)`;200 s.visibility = 'visible';201 e.el.dataset.kaInside = inside ? '1' : '0';202 continue;203 }204 const show = valid && (inside || !e.hideOutside);205 e.x = x;206 e.y = y;207 if (show) {208 s.transform = `translate(${(x + e.offset[0]).toFixed(1)}px, ${(y + e.offset[1]).toFixed(1)}px) translate(${e.anchor[0]}%, ${e.anchor[1]}%)`;209 if (!e.shown) s.visibility = 'visible';210 } else if (e.shown || s.visibility !== 'hidden') {211 s.visibility = 'hidden';212 }213 e.shown = show;214 }215 }216217 /** Vrai si au moins un élément est déclaré zone de l'hôte. */218 get hasObstacles(): boolean {219 return this.entries.some((e) => e.obstacle);220 }221222 /** Rectangles `[x0, y0, x1, y1]` (pixels CSS du canvas) des éléments visibles déclarés zones de l'hôte. */223 obstacleRects(): [number, number, number, number][] {224 const out: [number, number, number, number][] = [];225 const [w, h] = this.host.size();226 for (const e of this.entries) {227 if (!e.obstacle || !e.shown) continue;228 const ew = e.el.offsetWidth;229 const eh = e.el.offsetHeight;230 if (ew <= 0 || eh <= 0) continue;231 const x0 = e.x + e.offset[0] + (e.anchor[0] / 100) * ew;232 const y0 = e.y + e.offset[1] + (e.anchor[1] / 100) * eh;233 if (x0 > w || y0 > h || x0 + ew < 0 || y0 + eh < 0) continue;234 out.push([x0, y0, x0 + ew, y0 + eh]);235 }236 return out;237 }238239 /** Boutons mandataires : un vrai `<button>` par marqueur, superposé à sa pastille. */240 createProxies(options: MarkerProxyOptions): MarkerProxyHandle {241 const group = document.createElement('div');242 group.setAttribute('role', 'group');243 group.className = 'ka-maps-proxies';244 this.root.appendChild(group);245 const [bw, bh] = options.size ?? [44, 32];246 let handles: { item: MarkerProxyItem; btn: HTMLButtonElement; handle: OverlayHandle }[] = [];247 const byId = new Map<string | number, HTMLButtonElement>();248249 const build = (items: MarkerProxyItem[]) => {250 for (const h of handles) h.handle.remove();251 handles = [];252 byId.clear();253 for (const item of items) {254 const btn = document.createElement('button');255 btn.type = 'button';256 btn.className = 'ka-maps-proxy';257 btn.setAttribute('aria-label', item.label);258 btn.dataset.kaId = String(item.id);259 const s = btn.style;260 s.width = `${bw}px`;261 s.height = `${bh}px`;262 s.padding = '0';263 s.margin = '0';264 s.border = '0';265 s.borderRadius = '10px';266 s.background = 'transparent';267 s.color = 'transparent';268 s.cursor = 'pointer';269 s.outlineOffset = '2px';270 // Le bouton sert au clavier et aux technologies d'assistance (pointer-events: none pour la souris).271 btn.addEventListener('focus', () => {272 s.outline = '3px solid var(--ka-maps-focus, #1a73e8)';273 const ll: LngLat = [item.lon, item.lat];274 if (btn.dataset.kaInside !== '1' && options.panOnFocus !== false) {275 this.host.centerOn(ll);276 // Le survol se pose une fois la carte arrivée, si le bouton a encore le focus.277 setTimeout(() => {278 if (document.activeElement === btn) this.host.hoverAt(ll);279 }, 320);280 } else {281 this.host.hoverAt(ll);282 }283 options.onFocus?.(item);284 });285 btn.addEventListener('blur', () => {286 s.outline = 'none';287 this.host.hoverAt(null);288 });289 btn.addEventListener('click', (ev) => options.onActivate?.(item, ev));290 const handle = this.add(btn, [item.lon, item.lat], { anchor: 'center', hideWhenOutside: false }, true);291 group.appendChild(btn);292 handles.push({ item, btn, handle });293 byId.set(item.id, btn);294 }295 this.invalidate();296 };297 build(options.items);298 return {299 setItems: build,300 elementFor: (id) => byId.get(id),301 remove: () => {302 for (const h of handles) h.handle.remove();303 handles = [];304 byId.clear();305 group.remove();306 },307 };308 }309310 destroy(): void {311 this.entries.length = 0;312 this.root.remove();313 }314}315