Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : sdk/web/src/dom.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// Structure DOM de la carte : canvas accessible, mention des sources toujours visible, commandes43// facultatives (zoom, nord, 2D/3D, échelle), message d'aide des gestes coopératifs, région d'annonces.44//45// Aucune feuille de style injectée, aucun attribut `style` écrit en HTML : tout passe par le CSSOM46// (compatible avec `style-src 'self'` sans 'unsafe-inline'). Les couleurs et les tailles lisent des47// variables CSS que le site peut poser sur le conteneur de la carte (ou plus haut) :48//49// --ka-maps-surface fond des commandes et de la mention des sources (#ffffff)50// --ka-maps-ink texte (#1f2328)51// --ka-maps-line filets entre les boutons (#d0d4d9)52// --ka-maps-focus anneau de focus du canvas et des mandataires (#1a73e8)53// --ka-maps-font police (système)54// --ka-maps-control-size côté des boutons (44px)55// --ka-maps-radius arrondi des commandes (8px)5657import type { KaMapStrings } from './types.js';5859let uid = 0;6061export const VAR = {62 surface: 'var(--ka-maps-surface, #ffffff)',63 ink: 'var(--ka-maps-ink, #1f2328)',64 line: 'var(--ka-maps-line, #d0d4d9)',65 focus: 'var(--ka-maps-focus, #1a73e8)',66 font: 'var(--ka-maps-font, system-ui, -apple-system, "Segoe UI", sans-serif)',67 size: 'var(--ka-maps-control-size, 44px)',68 radius: 'var(--ka-maps-radius, 8px)',69};7071export interface Scaffold {72 root: HTMLElement;73 canvas: HTMLCanvasElement;74 /** Vrai si le SDK a créé le canvas (il le retire à la destruction). */75 ownsCanvas: boolean;76 attribution: HTMLElement;77 live: HTMLElement;78 setAttribution(text: string): void;79 showHint(text: string): void;80 announce(text: string): void;81 addNavigation(position: string, actions: NavActions, strings: KaMapStrings, parts?: NavParts): NavControl;82 addScale(position: string): ScaleControl;83 /** Retrait des commandes (boutons, échelle) depuis les bords, pixels CSS. */84 setInsets(insets: { top?: number; right?: number; bottom?: number; left?: number }): void;85 /** Rectangles `[x0, y0, x1, y1]` des commandes visibles (boutons, échelle, mention des sources), pixels CSS du canvas. */86 controlRects(): [number, number, number, number][];87 destroy(): void;88}8990export interface NavActions {91 zoomIn(): void;92 zoomOut(): void;93 resetNorth(): void;94 toggleMode(): void;95}96export interface NavParts {97 zoom?: boolean;98 north?: boolean;99 mode?: boolean;100}101export interface NavControl {102 update(bearing: number, mode3d: boolean): void;103 remove(): void;104}105export interface ScaleControl {106 /** `metersPerPixel` au centre de la vue. */107 update(metersPerPixel: number): void;108 remove(): void;109}110111export interface ScaffoldOptions {112 attribution?: 'full' | 'compact';113}114115function hideVisually(el: HTMLElement): void {116 const s = el.style;117 s.position = 'absolute';118 s.width = '1px';119 s.height = '1px';120 s.margin = '-1px';121 s.padding = '0';122 s.overflow = 'hidden';123 s.clipPath = 'inset(50%)';124 s.whiteSpace = 'nowrap';125 s.border = '0';126}127128/** Longueur ronde (1, 2 ou 5 × 10ⁿ mètres) la plus proche par défaut de `max` mètres. */129export function niceDistance(max: number): number {130 if (!(max > 0)) return 0;131 const pow = Math.pow(10, Math.floor(Math.log10(max)));132 const n = max / pow;133 return (n >= 5 ? 5 : n >= 2 ? 2 : 1) * pow;134}135136export function formatDistance(m: number): string {137 if (m >= 1000) return `${(m / 1000).toLocaleString('fr-CA', { maximumFractionDigits: 1 })} km`;138 return `${m.toLocaleString('fr-CA', { maximumFractionDigits: m < 1 ? 2 : 0 })} m`;139}140141export function buildScaffold(target: HTMLElement | HTMLCanvasElement, strings: KaMapStrings, options: ScaffoldOptions = {}): Scaffold {142 const id = ++uid;143 const created: HTMLElement[] = [];144 let canvas: HTMLCanvasElement;145 let root: HTMLElement;146 let ownsCanvas = false;147 const restore: (() => void)[] = [];148149 if (target instanceof HTMLCanvasElement) {150 canvas = target;151 root = target.parentElement ?? target;152 } else {153 root = target;154 canvas = document.createElement('canvas');155 ownsCanvas = true;156 const cs = canvas.style;157 cs.position = 'absolute';158 cs.left = '0';159 cs.top = '0';160 cs.width = '100%';161 cs.height = '100%';162 cs.display = 'block';163 root.appendChild(canvas);164 }165 const rootPosition = root !== canvas ? getComputedStyle(root).position : 'absolute';166 if (!rootPosition || rootPosition === 'static') {167 const prev = root.style.position;168 root.style.position = 'relative';169 restore.push(() => (root.style.position = prev));170 }171 // Classes stables pour le style du site.172 for (const [el, cls] of [173 [root, 'ka-maps-root'],174 [canvas, 'ka-maps-canvas'],175 ] as const) {176 if (!el.classList.contains(cls)) {177 el.classList.add(cls);178 restore.push(() => el.classList.remove(cls));179 }180 }181182 // Canvas : rôle, nom, mode d'emploi, focus clavier visible.183 const help = document.createElement('div');184 help.id = `ka-maps-help-${id}`;185 help.textContent = strings.keyboardHelp;186 hideVisually(help);187 const prevAttrs = ['role', 'aria-label', 'aria-roledescription', 'aria-describedby', 'tabindex'].map((a) => [a, canvas.getAttribute(a)] as const);188 canvas.setAttribute('role', 'application');189 canvas.setAttribute('aria-label', strings.mapLabel);190 canvas.setAttribute('aria-roledescription', strings.mapRole);191 canvas.setAttribute('aria-describedby', help.id);192 canvas.tabIndex = 0;193 canvas.style.outline = 'none';194 canvas.style.userSelect = 'none';195 (canvas.style as CSSStyleDeclaration & { webkitUserSelect?: string }).webkitUserSelect = 'none';196 (canvas.style as CSSStyleDeclaration & { webkitTapHighlightColor?: string }).webkitTapHighlightColor = 'transparent';197 canvas.textContent = strings.mapLabel;198 restore.push(() => {199 for (const [a, v] of prevAttrs) {200 if (v === null) canvas.removeAttribute(a);201 else canvas.setAttribute(a, v);202 }203 });204 // Anneau de focus : seulement au clavier (pas au clic).205 let viaKeyboard = false;206 const onKeyNav = () => (viaKeyboard = true);207 const onPointer = () => (viaKeyboard = false);208 const onFocus = () => {209 if (viaKeyboard || canvas.matches(':focus-visible')) {210 canvas.style.outline = `3px solid ${VAR.focus}`;211 canvas.style.outlineOffset = '-3px';212 }213 };214 const onBlur = () => (canvas.style.outline = 'none');215 document.addEventListener('keydown', onKeyNav, true);216 document.addEventListener('pointerdown', onPointer, true);217 canvas.addEventListener('focus', onFocus);218 canvas.addEventListener('blur', onBlur);219 restore.push(() => {220 document.removeEventListener('keydown', onKeyNav, true);221 document.removeEventListener('pointerdown', onPointer, true);222 canvas.removeEventListener('focus', onFocus);223 canvas.removeEventListener('blur', onBlur);224 });225226 const host = root === canvas ? null : root;227228 // Mention des sources : toujours présente, jamais masquable par une option.229 const attribution = document.createElement('div');230 attribution.className = 'ka-maps-attribution';231 // « note » et non « contentinfo » : la carte vit le plus souvent dans un <main> (un pied de page y serait fautif).232 attribution.setAttribute('role', 'note');233 attribution.setAttribute('aria-label', strings.attributionLabel);234 const compact = options.attribution === 'compact';235 {236 const s = attribution.style;237 s.position = 'absolute';238 s.right = '0';239 s.bottom = '0';240 s.maxWidth = '100%';241 s.boxSizing = 'border-box';242 s.padding = '2px 6px';243 s.font = `11px/1.35 ${VAR.font}`;244 s.color = VAR.ink;245 s.backgroundColor = VAR.surface;246 s.opacity = '0.92';247 s.borderTopLeftRadius = '4px';248 s.pointerEvents = 'auto';249 s.zIndex = '2';250 }251 if (compact) {252 // Une ligne ; le texte entier reste dans le DOM (lecteurs d'écran) et se déplie au survol, au focus et à l'appui.253 attribution.classList.add('ka-maps-attribution-compact');254 attribution.tabIndex = 0;255 const s = attribution.style;256 const fold = (on: boolean) => {257 s.whiteSpace = on ? 'nowrap' : 'normal';258 s.overflow = on ? 'hidden' : 'visible';259 s.textOverflow = on ? 'ellipsis' : 'clip';260 s.maxWidth = on ? 'min(100%, 22em)' : '100%';261 s.cursor = on ? 'pointer' : 'auto';262 attribution.dataset.kaOpen = on ? '0' : '1';263 };264 fold(true);265 let pinned = false;266 attribution.addEventListener('mouseenter', () => fold(false));267 attribution.addEventListener('mouseleave', () => !pinned && fold(true));268 attribution.addEventListener('focus', () => fold(false));269 attribution.addEventListener('blur', () => !pinned && fold(true));270 attribution.addEventListener('click', () => {271 pinned = !pinned;272 fold(!pinned);273 });274 }275276 const live = document.createElement('div');277 live.setAttribute('aria-live', 'polite');278 live.setAttribute('role', 'status');279 hideVisually(live);280281 const hint = document.createElement('div');282 hint.className = 'ka-maps-hint';283 hint.setAttribute('aria-hidden', 'true');284 {285 const s = hint.style;286 s.position = 'absolute';287 s.left = '0';288 s.top = '0';289 s.width = '100%';290 s.height = '100%';291 s.display = 'none';292 s.alignItems = 'center';293 s.justifyContent = 'center';294 s.textAlign = 'center';295 s.padding = '16px';296 s.boxSizing = 'border-box';297 s.font = `600 16px/1.4 ${VAR.font}`;298 s.color = '#ffffff';299 s.background = 'rgba(0, 0, 0, 0.55)';300 s.pointerEvents = 'none';301 s.zIndex = '3';302 }303304 if (host) {305 for (const el of [help, attribution, live, hint]) {306 host.appendChild(el);307 created.push(el);308 }309 }310311 let hintTimer: ReturnType<typeof setTimeout> | undefined;312 let liveTimer: ReturnType<typeof setTimeout> | undefined;313314 const place = (s: CSSStyleDeclaration, position: string, bottomGap: string) => {315 const [v, h] = position.split('-');316 if (v === 'bottom') s.bottom = bottomGap;317 else s.top = '0';318 if (h === 'left') s.left = '0';319 else s.right = '0';320 };321322 const controlBoxes = (): HTMLElement[] => created.filter((el) => el.classList.contains('ka-maps-nav') || el.classList.contains('ka-maps-scale'));323 return {324 root,325 canvas,326 ownsCanvas,327 attribution,328 live,329 setInsets(insets) {330 const px = (n: number | undefined) => `${10 + Math.max(0, n ?? 0)}px`;331 for (const el of controlBoxes()) el.style.margin = `${px(insets.top)} ${px(insets.right)} ${px(insets.bottom)} ${px(insets.left)}`;332 },333 controlRects() {334 const c = canvas.getBoundingClientRect();335 const out: [number, number, number, number][] = [];336 for (const el of [...controlBoxes(), attribution]) {337 if (!el.isConnected) continue;338 const r = el.getBoundingClientRect();339 if (r.width <= 0 || r.height <= 0 || el.style.display === 'none') continue;340 out.push([r.left - c.left, r.top - c.top, r.right - c.left, r.bottom - c.top]);341 }342 return out;343 },344 setAttribution(text) {345 attribution.textContent = text;346 },347 showHint(text) {348 if (!host) return;349 hint.textContent = text;350 hint.style.display = 'flex';351 clearTimeout(hintTimer);352 hintTimer = setTimeout(() => (hint.style.display = 'none'), 1400);353 },354 announce(text) {355 // Regroupe les annonces rapprochées (une seule par demi-seconde).356 clearTimeout(liveTimer);357 liveTimer = setTimeout(() => (live.textContent = text), 500);358 },359 addNavigation(position, actions, str, parts = {}) {360 const box = document.createElement('div');361 box.className = 'ka-maps-nav';362 box.setAttribute('role', 'group');363 box.setAttribute('aria-label', str.mapLabel);364 const s = box.style;365 s.position = 'absolute';366 s.display = 'flex';367 s.flexDirection = 'column';368 s.gap = '1px';369 s.margin = '10px';370 s.borderRadius = VAR.radius;371 s.overflow = 'hidden';372 s.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';373 s.backgroundColor = VAR.line;374 s.zIndex = '2';375 place(s, position, '24px');376 const mk = (cls: string, label: string, text: string, fn: () => void) => {377 const b = document.createElement('button');378 b.type = 'button';379 b.className = `ka-maps-btn ${cls}`;380 b.setAttribute('aria-label', label);381 b.title = label;382 b.textContent = text;383 const bs = b.style;384 bs.width = VAR.size;385 bs.height = VAR.size;386 bs.border = '0';387 bs.margin = '0';388 bs.padding = '0';389 bs.backgroundColor = VAR.surface;390 bs.color = VAR.ink;391 bs.font = `600 16px/1 ${VAR.font}`;392 bs.cursor = 'pointer';393 b.addEventListener('click', fn);394 box.appendChild(b);395 return b;396 };397 if (parts.zoom !== false) {398 mk('ka-maps-zoom-in', str.zoomIn, '+', actions.zoomIn);399 mk('ka-maps-zoom-out', str.zoomOut, '−', actions.zoomOut);400 }401 // Nord : une aiguille de boussole dessinée (SVG), pas un caractère — le « ▲ » dépendait de la police de repli402 // du poste et se lisait comme un défaut de rendu. La moitié nord est pleine, la moitié sud au trait ; l'aiguille403 // tourne avec le cap. Couleur : celle du bouton (`currentColor`, donc `--ka-maps-ink`).404 const north = parts.north !== false ? mk('ka-maps-north', str.resetNorth, '', actions.resetNorth) : null;405 let needle: SVGSVGElement | null = null;406 if (north) {407 const NS = 'http://www.w3.org/2000/svg';408 needle = document.createElementNS(NS, 'svg');409 needle.setAttribute('viewBox', '0 0 24 24');410 needle.setAttribute('width', '22');411 needle.setAttribute('height', '22');412 needle.setAttribute('aria-hidden', 'true');413 needle.setAttribute('focusable', 'false');414 needle.setAttribute('class', 'ka-maps-north-needle');415 const n = document.createElementNS(NS, 'path');416 n.setAttribute('d', 'M12 2.5 L16.5 12 H7.5 Z');417 n.setAttribute('fill', 'currentColor');418 const sth = document.createElementNS(NS, 'path');419 sth.setAttribute('d', 'M7.5 12 H16.5 L12 21.5 Z');420 sth.setAttribute('fill', 'none');421 sth.setAttribute('stroke', 'currentColor');422 sth.setAttribute('stroke-width', '1.5');423 sth.setAttribute('stroke-linejoin', 'round');424 needle.append(n, sth);425 needle.style.display = 'block';426 needle.style.margin = 'auto';427 needle.style.pointerEvents = 'none';428 north.appendChild(needle);429 }430 const mode = parts.mode !== false ? mk('ka-maps-mode', str.mode3d, '3D', actions.toggleMode) : null;431 if (mode) mode.style.fontSize = '12px';432 (host ?? root).appendChild(box);433 created.push(box);434 return {435 update(bearing, mode3d) {436 if (needle) needle.style.transform = `rotate(${(-bearing).toFixed(1)}deg)`;437 if (mode) {438 mode.textContent = mode3d ? '2D' : '3D';439 mode.setAttribute('aria-label', mode3d ? str.mode2d : str.mode3d);440 mode.title = mode3d ? str.mode2d : str.mode3d;441 mode.setAttribute('aria-pressed', String(mode3d));442 }443 },444 remove() {445 box.remove();446 },447 };448 },449 addScale(position) {450 // Échelle graphique : un trait d'une longueur ronde et sa valeur. Décorative pour les lecteurs d'écran.451 const box = document.createElement('div');452 box.className = 'ka-maps-scale';453 box.setAttribute('aria-hidden', 'true');454 const s = box.style;455 s.position = 'absolute';456 s.margin = '10px';457 s.padding = '1px 5px 2px';458 s.boxSizing = 'border-box';459 s.font = `11px/1.3 ${VAR.font}`;460 s.color = VAR.ink;461 s.backgroundColor = VAR.surface;462 s.opacity = '0.92';463 s.borderStyle = 'solid';464 s.borderColor = VAR.ink;465 s.borderWidth = '0 2px 2px 2px';466 s.whiteSpace = 'nowrap';467 s.pointerEvents = 'none';468 s.zIndex = '2';469 place(s, position, '24px');470 (host ?? root).appendChild(box);471 created.push(box);472 let last = '';473 return {474 update(metersPerPixel) {475 if (!(metersPerPixel > 0) || !Number.isFinite(metersPerPixel)) {476 s.display = 'none';477 return;478 }479 const meters = niceDistance(metersPerPixel * 110);480 const key = `${meters}|${(meters / metersPerPixel).toFixed(0)}`;481 if (key === last) return;482 last = key;483 s.display = 'block';484 s.width = `${(meters / metersPerPixel).toFixed(1)}px`;485 box.textContent = formatDistance(meters);486 box.dataset.kaMeters = String(meters);487 },488 remove() {489 box.remove();490 },491 };492 },493 destroy() {494 clearTimeout(hintTimer);495 clearTimeout(liveTimer);496 for (const el of created) el.remove();497 for (const r of restore) r();498 if (ownsCanvas) canvas.remove();499 },500 };501}502