SPB Git

Repository Public

map.ts 62.7 KB 1,510 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : sdk/web/src/map.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// KaMap : l'API de docs/SDK_API.md pour le Web.43//44// Cette classe ne dessine rien et ne décide rien de cartographique : elle branche un canvas sur le45// moteur (wasm), transmet les gestes, fait le réseau, répartit les constructions de tuiles sur des46// workers, tient le stock persistant et livre les événements.4748import { buildScaffold, type NavControl, type ScaleControl, type Scaffold } from './dom.js';49import { Emitter } from './events.js';50import { FetchBridge, type FetchKind } from './fetcher.js';51import { createGeo } from './geo.js';52import { resolveStrings } from './i18n.js';53import { InputController } from './input.js';54import { loadEngine, resolveAssetsUrl, type Engine } from './loader.js';55import { OverlayLayer } from './overlay.js';56import { openTileCache, MemoryTileCache, type StoreOp, type TileCache } from './tile-cache.js';57import {58  KaMapError,59  type AppId,60  type Backend,61  type Bounds,62  type Camera,63  type CameraOptions,64  type DrawPayload,65  type Endpoints,66  type Feature,67  type InteractiveOptions,68  type KaMapEvent,69  type KaMapEventMap,70  type KaMapEventType,71  type KaMapOptions,72  type KaMapStrings,73  type LayerDataByType,74  type LayerInfo,75  type LayerOptionsByType,76  type LayerSpec,77  type LayerType,78  type LngLat,79  type MarkerProxyHandle,80  type MarkerProxyOptions,81  type MarkerState,82  type Mode,83  type OfflinePackIndex,84  type OfflineRegion,85  type OfflineUsage,86  type OverlayHandle,87  type OverlayOptions,88  type Padding,89  type PerfSample,90  type Point,91  type Quality,92  type RenderedMarker,93  type ProjectedPoint,94  type ControlInsets,95  type ViewState,96} from './types.js';97import { VERSION } from './version.js';9899/** Clé du stock persistant qui retient la version des données de tuiles vue à la dernière session. */100const DATA_VERSION_KEY = '_sdk.dataVersion';101102interface TileJson {103  attribution?: string;104  data_version?: string;105}106import { defaultWorkerCount, WorkerPool, type BuildJob } from './worker-pool.js';107import type { KmMap } from './wasm/km_wasm.js';108109export const DEFAULT_ENDPOINTS: Endpoints = {110  tiles: 'https://tiles.spboucher.ai',111  terrain: 'https://terrain.spboucher.ai',112  geo: 'https://geo.spboucher.ai',113  maps: 'https://maps.spboucher.ai',114};115116const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;117118export type KaMapTarget = HTMLElement | HTMLCanvasElement | OffscreenCanvas | string;119120export interface SdkStats {121  backend: Backend;122  framesRendered: number;123  /** Trames par seconde mesurées par le SDK sur la dernière seconde de rendu continu (0 au repos). */124  fps: number;125  /** Temps processeur moyen d'une trame dessinée (mise à jour + construction + soumission au GPU), ms. Le temps GPU n'y est pas. */126  frameCpuMs: number;127  /** Taille de la mémoire linéaire du moteur (fil principal). Elle ne rétrécit jamais. */128  wasmMemoryBytes: number;129  /** Octets réellement alloués et vivants dans le moteur, et leur plus haut niveau : la mesure qui révèle une fuite. */130  wasmLiveBytes: number;131  wasmPeakBytes: number;132  jsHeapBytes: number | null;133  fetch: FetchBridge['stats'];134  workers: WorkerPool['stats'] | null;135  engineLoadMs: number;136  createMs: number;137  overlays: number;138}139140function isOffscreen(v: unknown): v is OffscreenCanvas {141  return typeof OffscreenCanvas !== 'undefined' && v instanceof OffscreenCanvas;142}143144function trimSlash(s: string): string {145  return s.replace(/\/+$/, '');146}147148/** Vrai si le navigateur peut afficher la carte (WebGPU ou WebGL 2). Faux côté serveur. */149export function isSupported(): boolean {150  if (typeof window === 'undefined' || typeof document === 'undefined') return false;151  if (typeof WebAssembly !== 'object') return false;152  if ('gpu' in navigator && (navigator as Navigator & { gpu?: unknown }).gpu) return true;153  try {154    const c = document.createElement('canvas');155    const gl = c.getContext('webgl2');156    const ok = !!gl;157    (gl?.getExtension('WEBGL_lose_context') as { loseContext(): void } | null)?.loseContext();158    return ok;159  } catch {160    return false;161  }162}163164function signalUnsupported(target: unknown, message: string): void {165  if (target instanceof Element) {166    target.dispatchEvent(new CustomEvent('kamaps:unsupported', { bubbles: true, detail: { message } }));167  }168}169170export class KaMap {171  /** Version du SDK. */172  static readonly version = VERSION;173  static isSupported = isSupported;174175  /**176   * Crée une carte dans `target` (élément conteneur, `<canvas>`, sélecteur CSS ou `OffscreenCanvas`).177   *178   * Rejette avec `KaMapError` ; `code === "unsupported"` signifie que ni WebGPU ni WebGL 2 ne sont179   * disponibles (un événement DOM `kamaps:unsupported` est aussi émis sur la cible) : l'application180   * affiche alors sa liste de repli.181   */182  static async create(target: KaMapTarget, options: KaMapOptions = {}): Promise<KaMap> {183    if (typeof window === 'undefined' || typeof document === 'undefined') {184      throw new KaMapError('unsupported', 'KaMap.create ne s’exécute que dans un navigateur (appeler dans un effet client)');185    }186    const t0 = performance.now();187    let el: HTMLElement | HTMLCanvasElement | OffscreenCanvas;188    if (typeof target === 'string') {189      const found = document.querySelector<HTMLElement>(target);190      if (!found) throw new KaMapError('options', `cible introuvable : ${target}`);191      el = found;192    } else {193      el = target;194    }195    const strings = resolveStrings(options.strings);196    if (!isSupported()) {197      signalUnsupported(el, strings.unsupported);198      throw new KaMapError('unsupported', strings.unsupported);199    }200201    const endpoints: Endpoints = {202      tiles: trimSlash(options.endpoints?.tiles ?? DEFAULT_ENDPOINTS.tiles),203      terrain: trimSlash(options.endpoints?.terrain ?? DEFAULT_ENDPOINTS.terrain),204      geo: trimSlash(options.endpoints?.geo ?? DEFAULT_ENDPOINTS.geo),205      maps: trimSlash(options.endpoints?.maps ?? DEFAULT_ENDPOINTS.maps),206    };207    const cacheOpt = options.cache === false ? { persistent: false } : (options.cache ?? {});208    const persistent = cacheOpt.persistent !== false;209210    // TileJSON demandé en même temps que le moteur : la version des données est en général connue avant la211    // première tuile (elle entre dans l'adresse des tuiles, voir FetchBridge.setTileVersion).212    const tileJson: Promise<TileJson | null> = fetch(`${endpoints.tiles}/v1/base.json`, { credentials: 'omit' })213      .then((res) => (res.ok ? (res.json() as Promise<TileJson>) : null))214      .catch(() => null);215    const [engine, cache] = await Promise.all([loadEngine(options.assetsUrl), persistent ? openTileCache(cacheOpt.name) : Promise.resolve<TileCache>(new MemoryTileCache())]);216    const stored = await cache.load().catch(() => ({ index: [], meta: [] }));217    // Un stock existe déjà (visite précédente) : la version des données est attendue un court instant (0,4 s au218    // plus), pour qu'une bascule de données vide le stock périmé avant la première tuile, pas après.219    let tileJsonNow: TileJson | null | undefined;220    void tileJson.then((t) => (tileJsonNow = t));221    const storedVersionBytes = (stored.meta as [string, Uint8Array][]).find(([k]) => k === DATA_VERSION_KEY)?.[1];222    const storedVersion = storedVersionBytes ? new TextDecoder().decode(storedVersionBytes) : undefined;223    if (storedVersion !== undefined) await Promise.race([tileJson, new Promise((res) => setTimeout(res, 400))]);224225    // Thème non embarqué dans le moteur : son document vient du manifeste public.226    const info = JSON.parse(engine.glue.engine_version()) as { themes: string[]; themeNames: string[] };227    const theme = options.theme ?? 'signature';228    let themeDocument: string | undefined = options.themeDocument === undefined ? undefined : typeof options.themeDocument === 'string' ? options.themeDocument : JSON.stringify(options.themeDocument);229    if (themeDocument === undefined && !info.themes.includes(theme)) {230      themeDocument = await fetchThemeDocument(endpoints.maps, theme);231    }232233    const reduced = resolveReducedMotion(options.reducedMotion);234    const maxPr = options.maxPixelRatio ?? 2;235    const dpr = Math.min(window.devicePixelRatio || 1, maxPr);236237    let scaffold: Scaffold | null = null;238    let surface: HTMLCanvasElement | OffscreenCanvas;239    let width: number;240    let height: number;241    if (isOffscreen(el)) {242      surface = el;243      width = el.width / dpr;244      height = el.height / dpr;245    } else {246      scaffold = buildScaffold(el, strings, { attribution: options.attribution });247      surface = scaffold.canvas;248      width = scaffold.canvas.clientWidth || 300;249      height = scaffold.canvas.clientHeight || 150;250    }251252    const engineOptions: Record<string, unknown> = {253      app: options.app,254      theme: themeDocument !== undefined && !info.themes.includes(theme) ? 'signature' : theme,255      themeDocument,256      center: options.center,257      zoom: options.zoom,258      bearing: options.bearing,259      pitch: options.pitch ?? (options.mode === '3d' ? 55 : undefined),260      endpoints: { tiles: endpoints.tiles, terrain: endpoints.terrain },261      quality: options.quality ?? 'auto',262      reducedMotion: reduced,263      width,264      height,265      pixelRatio: dpr,266      renderer: options.renderer ?? 'auto',267      cacheBytes: cacheOpt.maxBytes ?? DEFAULT_CACHE_BYTES,268      cachePersistent: cache.persistent,269    };270    for (const k of Object.keys(engineOptions)) if (engineOptions[k] === undefined) delete engineOptions[k];271272    const make = (canvas: HTMLCanvasElement | OffscreenCanvas, renderer: unknown) =>273      engine.glue.KmMap.create(canvas, JSON.stringify({ ...engineOptions, renderer }), stored.index, stored.meta);274275    let km: KmMap;276    try {277      try {278        km = await make(surface, engineOptions.renderer);279      } catch (first) {280        // WebGPU annoncé mais inutilisable (pilote, liste de blocage) : le contexte « webgpu » est déjà281        // pris sur ce canvas, on repart d'un canvas neuf en WebGL 2.282        if ((options.renderer ?? 'auto') === 'auto' && scaffold?.ownsCanvas) {283          scaffold.destroy();284          scaffold = buildScaffold(el as HTMLElement, strings, { attribution: options.attribution });285          surface = scaffold.canvas;286          km = await make(surface, 'webgl2');287        } else {288          throw first;289        }290      }291    } catch (e) {292      scaffold?.destroy();293      cache.close();294      const msg = String((e as Error)?.message ?? e);295      if (msg.startsWith('no-gpu')) {296        signalUnsupported(el, strings.unsupported);297        throw new KaMapError('unsupported', `${strings.unsupported} (${msg.replace(/^no-gpu:\s*/, '')})`, { cause: e });298      }299      throw new KaMapError(/^(app inconnue|thème|qualité|options|caméra|renderer)/.test(msg) ? 'options' : 'engine', msg, { cause: e });300    }301302    const map = new KaMap(km, engine, cache, scaffold, isOffscreen(el) ? el : null, endpoints, options, strings, reduced, tileJson, tileJsonNow, storedVersion);303    map.createMs = performance.now() - t0;304    return map;305  }306307  // ------------------------------------------------------------------ état308309  private emitter = new Emitter<KaMapEventMap>();310  private raf = 0;311  private destroyed = false;312  private fatalError: KaMapError | null = null;313  private fetcher: FetchBridge;314  private pool: WorkerPool | null = null;315  private input: InputController | null = null;316  private overlay: OverlayLayer | null = null;317  private nav: NavControl | null = null;318  private scale: ScaleControl | null = null;319  /** Vrai entre un geste de la personne et le `moveend` qui le termine. */320  private userMoving = false;321  private interactiveState: Required<InteractiveOptions> = { pan: true, zoom: true, rotate: true, pitch: true, cooperative: false };322  private keyboard: boolean;323  private drawing = false;324  private loaded = false;325  private idleNow = false;326  private reducedMotionAuto: boolean;327  private reduced: boolean;328  private maxPixelRatio: number;329  private appliedSize: [number, number, number] = [0, 0, 0];330  private lastCamera = new Float64Array(5);331  private styleDocs = new Map<number, string>();332  private localStyleRev = -1;333  private disposers: (() => void)[] = [];334  private attributionText = '';335  private uploadBoost = false;336  private hostObstacles: [number, number, number, number][] = [];337  private controlObstacles = true;338  private controlRectsCache: [number, number, number, number][] | null = null;339  private obstaclesSig = '';340  private obstaclesAt = 0;341  private obstaclesLate = false;342  /** Le calque DOM portait des zones à la trame précédente (pour retirer la dernière). */343  private overlayObstacles = false;344  private dataVersionText: string | undefined;345  private expandClusters: boolean;346  private createMs = 0;347  private fpsFrames = 0;348  private fpsT0 = 0;349  private fpsValue = 0;350  private lastFrameAt = 0;351  private cpuMs = 0;352  private cacheCap: number;353354  /** Recherche et géocodage inverse sur le service configuré (`endpoints.geo`). */355  readonly geo: ReturnType<typeof createGeo>;356  readonly endpoints: Readonly<Endpoints>;357  readonly backend: Backend;358  readonly strings: KaMapStrings;359360  private constructor(361    private km: KmMap,362    private engine: Engine,363    private cache: TileCache,364    private scaffold: Scaffold | null,365    private offscreen: OffscreenCanvas | null,366    endpoints: Endpoints,367    options: KaMapOptions,368    strings: KaMapStrings,369    reduced: boolean,370    tileJson: Promise<TileJson | null>,371    tileJsonNow: TileJson | null | undefined,372    private storedDataVersion: string | undefined,373  ) {374    this.endpoints = endpoints;375    this.strings = strings;376    this.geo = createGeo(endpoints.geo);377    this.backend = km.backend() as Backend;378    this.reduced = reduced;379    this.reducedMotionAuto = options.reducedMotion === undefined || options.reducedMotion === 'auto';380    this.maxPixelRatio = options.maxPixelRatio ?? 2;381    this.keyboard = options.keyboard !== false;382    this.expandClusters = options.expandClustersOnClick !== false;383    this.cacheCap = (options.cache === false ? undefined : options.cache?.maxBytes) ?? DEFAULT_CACHE_BYTES;384385    if (options.initialUpload !== 'spread') {386      this.uploadBoost = true;387      this.km.set_upload_budget(256 * 1024 * 1024);388    }389    this.fetcher = new FetchBridge(390      {391        fetchDone: (id, status, body, error, key) => {392          if (this.destroyed || this.fatalError) return;393          this.guard(() => this.km.fetch_done(id, status, body, error, key));394          this.requestFrame();395        },396      },397      cache,398      { holdTilesForVersion: true },399    );400    // TileJSON déjà reçu : la version entre dans les adresses dès la première demande ; si elle a changé depuis la401    // dernière session, le stock est périmé (réseau d'abord) — décidé avant toute trame, donc avant toute lecture.402    if (tileJsonNow !== undefined) {403      this.fetcher.setTileVersion(tileJsonNow?.data_version);404      if (tileJsonNow?.data_version && storedDataVersion !== undefined && storedDataVersion !== tileJsonNow.data_version) this.fetcher.setNetworkFirst(true);405    }406    // Sans réponse du TileJSON après 2 s (réseau lent, hors ligne), les tuiles partent sans version.407    const versionTimer = setTimeout(() => this.fetcher.setTileVersion(undefined), 2000);408    this.disposers.push(() => clearTimeout(versionTimer));409410    // Constructions de tuiles : workers, repli sur le fil principal.411    const workers = options.workers ?? defaultWorkerCount();412    if (workers > 0 && typeof Worker !== 'undefined') {413      this.km.set_external_build(true);414      this.pool = new WorkerPool(415        {416          buildDone: (job, bytes) => {417            if (this.destroyed || this.fatalError) return;418            this.guard(() => this.km.build_done(job, bytes));419            this.requestFrame();420          },421          buildFailed: (job, message) => {422            if (this.destroyed || this.fatalError) return;423            this.guard(() => this.km.build_failed(job, message));424            this.requestFrame();425          },426          styleDocument: (rev) => this.styleDocument(rev),427          buildLocal: (job) => this.buildLocal(job),428        },429        this.engine.module,430        `${this.engine.assetsUrl}ka-maps-worker.js`,431        workers,432      );433    }434435    if (options.minZoom !== undefined || options.maxZoom !== undefined) this.cmdQuiet('setZoomRange', { min: options.minZoom ?? 0, max: options.maxZoom ?? 20 });436    if (options.maxBounds) this.cmdQuiet('setMaxBounds', { bounds: options.maxBounds });437    if (options.baseLabels) this.cmdQuiet('setBaseLabels', { ...options.baseLabels });438    if (options.padding !== undefined) this.cmdQuiet('setPadding', { padding: options.padding });439    // WebGL 2 : préréglage OpenGL ES du moteur (une seule cascade d'ombre, carte d'ombre ≤ 1024, 64 tuiles au plus).440    if (this.backend === 'webgl2') this.cmdQuiet('setQuality', { backend: 'webgl2' });441    if (typeof navigator !== 'undefined' && navigator.onLine === false) this.cmdQuiet('setNetworkOnline', { online: false });442    if (options.interactive === false) this.setInteractive({ pan: false, zoom: false, rotate: false, pitch: false });443    else if (typeof options.interactive === 'object') this.setInteractive(options.interactive);444445    if (this.scaffold) this.attachDom(options);446    this.attributionText = this.cmd<string>('getAttribution');447    this.scaffold?.setAttribution(this.attributionText);448    // TileJSON déjà reçu : version appliquée (et stock périmé vidé) avant la première trame ; sinon à son arrivée.449    if (tileJsonNow !== undefined) this.applyTileJson(tileJsonNow);450    else void tileJson.then((tj) => this.applyTileJson(tj));451    if (options.mode && options.mode !== this.getMode()) this.cmd('setMode', { mode: options.mode });452    this.requestFrame();453  }454455  private attachDom(options: KaMapOptions): void {456    const sc = this.scaffold!;457    const canvas = sc.canvas;458    this.overlay = new OverlayLayer(sc.root === canvas ? (canvas.parentElement ?? document.body) : sc.root, {459      projectMany: (ll) => this.km.project_many(ll),460      size: () => [canvas.clientWidth, canvas.clientHeight],461      requestFrame: () => this.requestFrame(),462      hoverAt: (ll) => {463        if (this.destroyed || this.fatalError || this.drawing) return;464        const p = ll ? this.project(ll) : null;465        // Un peu au-dessus du point d'ancrage : le corps de la pastille.466        this.guard(() => this.km.pointer_move(p ? p[0] : -1e6, p ? p[1] - 10 : -1e6));467        this.requestFrame();468      },469      centerOn: (ll) => this.easeTo({ center: ll }, { duration: 250 }),470      hintText: () => this.strings.markerProxyHint,471    });472473    this.input = new InputController({474      canvas,475      panBy: (dx, dy) => this.byUser(() => this.km.pan_by(dx, dy)),476      zoomBy: (d, x, y) => this.byUser(() => this.km.zoom_by(d, x, y)),477      rotateBy: (d) => this.byUser(() => this.km.rotate_by(d)),478      pitchBy: (d) => this.byUser(() => this.km.pitch_by(d)),479      fling: (vx, vy, zv, bv) => this.byUser(() => this.km.fling(vx, vy, zv, bv)),480      tap: (x, y) => this.guard(() => this.km.tap(x, y)),481      doubleTap: (x, y, out) => this.byUser(() => this.km.double_tap(x, y, out)),482      pointerMove: (x, y) => this.guard(() => this.km.pointer_move(x, y)),483      getCamera: () => this.getCamera(),484      easeTo: (c, d) => this.userEase(c, d),485      unproject: (x, y) => this.unproject([x, y]),486      interactive: () => this.interactiveState,487      reducedMotion: () => this.reduced,488      keyboardEnabled: () => this.keyboard,489      isDrawing: () => this.drawing,490      finishDraw: () => void this.finishDraw(),491      cancelDraw: () => void this.stopDraw(),492      undoDraw: () => void this.undoDraw(),493      hint: (kind) => sc.showHint(kind === 'wheel' ? this.strings.cooperativeWheel : this.strings.cooperativeTouch),494      requestFrame: () => this.requestFrame(),495      announce: () => sc.announce(this.strings.announceZoom.replace('{zoom}', String(Math.round(this.km.camera()[2])))),496    });497498    const ctl = options.controls === true ? {} : options.controls && typeof options.controls === 'object' ? options.controls : null;499    if (ctl && ctl.navigation !== false && (ctl.zoom !== false || ctl.north !== false || ctl.mode !== false)) {500      this.nav = sc.addNavigation(501        ctl.position ?? 'top-right',502        {503          zoomIn: () => this.userEase({ zoom: Math.min(20, this.getCamera().zoom + 1) }, 250),504          zoomOut: () => this.userEase({ zoom: Math.max(0, this.getCamera().zoom - 1) }, 250),505          resetNorth: () => this.userEase({ bearing: 0 }, 300),506          toggleMode: () => {507            this.setMode(this.getMode() === '3d' ? '2d' : '3d');508            this.userMoving = true;509          },510        },511        this.strings,512        { zoom: ctl.zoom, north: ctl.north, mode: ctl.mode },513      );514      this.nav.update(this.getCamera().bearing, this.getMode() === '3d');515    }516    if (ctl?.scale) this.scale = sc.addScale('bottom-left');517    this.controlObstacles = ctl?.obstacles !== false;518    if (ctl?.insets) sc.setInsets(ctl.insets);519520    // Taille et densité de pixels.521    if (typeof ResizeObserver !== 'undefined') {522      const ro = new ResizeObserver(() => this.resize());523      ro.observe(canvas);524      this.disposers.push(() => ro.disconnect());525    }526    const onWin = () => this.resize();527    window.addEventListener('resize', onWin);528    this.disposers.push(() => window.removeEventListener('resize', onWin));529    this.resize();530531    // Mouvement réduit suivi en direct.532    if (this.reducedMotionAuto && typeof matchMedia === 'function') {533      const mq = matchMedia('(prefers-reduced-motion: reduce)');534      const on = () => this.applyReducedMotion(mq.matches);535      mq.addEventListener?.('change', on);536      this.disposers.push(() => mq.removeEventListener?.('change', on));537    }538539    const onVisible = () => {540      if (document.visibilityState === 'visible' && !this.destroyed && !this.fatalError) {541        this.guard(() => this.km.request_redraw());542        this.requestFrame();543      }544    };545    document.addEventListener('visibilitychange', onVisible);546    this.disposers.push(() => document.removeEventListener('visibilitychange', onVisible));547548    // État du réseau : hors ligne, le moteur cesse de demander ; au retour, ce qui manquait repart.549    const onNet = () => {550      if (this.destroyed || this.fatalError) return;551      try {552        this.setNetworkOnline(navigator.onLine !== false);553        if (navigator.onLine !== false) this.retryFailed();554      } catch {555        /* moteur arrêté */556      }557    };558    window.addEventListener('online', onNet);559    window.addEventListener('offline', onNet);560    this.disposers.push(() => {561      window.removeEventListener('online', onNet);562      window.removeEventListener('offline', onNet);563    });564565    const onLost = (e: Event) => {566      e.preventDefault();567      this.fail(new KaMapError('engine', 'contexte graphique perdu'), 'context-lost');568    };569    canvas.addEventListener('webglcontextlost', onLost);570    this.disposers.push(() => canvas.removeEventListener('webglcontextlost', onLost));571  }572573  private applyTileJson(tj: TileJson | null): void {574    if (this.destroyed || this.fatalError) return;575    this.fetcher.setTileVersion(tj?.data_version);576    if (!tj) return; // hors ligne : la mention du moteur reste affichée, les tuiles partent sans version577    this.dataVersionText = tj.data_version;578    if (tj.attribution) {579      this.attributionText = tj.attribution;580      this.scaffold?.setAttribution(tj.attribution);581      this.controlRectsCache = null;582      this.syncObstacles(true);583    }584    // Nouvelle version des données : les tuiles gardées (hors régions épinglées) sont périmées.585    if (tj.data_version && this.cache.persistent && this.storedDataVersion !== tj.data_version) {586      try {587        if (this.storedDataVersion !== undefined) {588          // Le moteur écarte ce qu'il tient encore dans son index (hors régions épinglées) ; les tuiles qu'il a589          // déjà demandées pour la première vue sont, elles, redemandées au réseau par le pont (réseau d'abord).590          this.fetcher.setNetworkFirst(true);591          this.cmd('offline.setCap', { bytes: 0 });592          this.cmd('offline.setCap', { bytes: this.cacheCap });593          this.pumpStore();594        }595        this.cache.apply([['put', DATA_VERSION_KEY, new TextEncoder().encode(tj.data_version)]]);596        this.storedDataVersion = tj.data_version;597      } catch {598        /* moteur arrêté */599      }600    }601  }602603  // ------------------------------------------------------------------ boucle604605  private requestFrame(): void {606    if (this.raf || this.destroyed || this.fatalError) return;607    this.raf = requestAnimationFrame(this.onFrame);608  }609610  private onFrame = (t: number): void => {611    this.raf = 0;612    if (this.destroyed || this.fatalError) return;613    let busy = false;614    try {615      const inputBusy = this.input?.tick(t) ?? false;616      const before = this.km.frames_rendered();617      const c0 = performance.now();618      busy = this.km.frame(t) || inputBusy;619      if (this.km.frames_rendered() !== before) {620        const ms = performance.now() - c0;621        this.cpuMs = this.cpuMs === 0 ? ms : this.cpuMs * 0.95 + ms * 0.05;622        this.km.set_cpu_ms(ms);623        this.countFrame(t);624      }625    } catch (e) {626      this.fail(e);627      return;628    }629    if (this.km.device_lost()) {630      this.fail(new KaMapError('engine', 'périphérique graphique perdu'), 'context-lost');631      return;632    }633    this.afterFrame();634    if (busy) this.requestFrame();635    else this.fpsT0 = 0;636  };637638  private countFrame(t: number): void {639    // Cadence mesurée seulement sur des trames qui s'enchaînent.640    if (this.fpsT0 === 0 || t - this.lastFrameAt > 250) {641      this.fpsT0 = t;642      this.fpsFrames = 0;643    } else {644      this.fpsFrames++;645      if (t - this.fpsT0 >= 500) {646        this.fpsValue = (this.fpsFrames * 1000) / (t - this.fpsT0);647        this.fpsT0 = t;648        this.fpsFrames = 0;649      }650    }651    this.lastFrameAt = t;652  }653654  private afterFrame(): void {655    try {656      this.pumpEvents();657      this.pumpNetwork();658      this.pumpBuilds();659      this.pumpStore();660      const cam = this.km.camera();661      let changed = false;662      for (let i = 0; i < 5; i++) {663        if (cam[i] !== this.lastCamera[i]) {664          this.lastCamera[i] = cam[i];665          changed = true;666        }667      }668      this.overlay?.update(changed);669      // Éléments du calque DOM déclarés zones de l'hôte : rectangles redonnés au moteur pendant le mouvement670      // (8 fois par seconde au plus), puis une dernière fois quand la caméra s'arrête.671      if (this.overlay?.hasObstacles || this.overlayObstacles) {672        this.overlayObstacles = this.overlay?.hasObstacles === true;673        if (changed) this.syncObstacles(false, true);674        else this.syncObstacles(true);675      }676      if (changed && this.nav) this.nav.update(cam[3], this.cmdQuiet<Mode>('getMode') === '3d');677      if (changed && this.scale) this.scale.update(this.metersPerPixel());678    } catch (e) {679      this.fail(e);680    }681  }682683  private pumpEvents(): void {684    const raw = this.km.take_events();685    if (!raw) return;686    const events = JSON.parse(raw) as ({ type: string } & Record<string, unknown>)[];687    for (const ev of events) {688      const { type, ...payload } = ev;689      switch (type) {690        case 'load':691          this.loaded = true;692          // La première vue est à l'écran : le téléversement étalé du moteur reprend (trames courtes en mouvement).693          if (this.uploadBoost) {694            this.uploadBoost = false;695            this.km.set_upload_budget(0);696          }697          (payload as Record<string, unknown>).backend = this.backend;698          if (this.attributionText) (payload as Record<string, unknown>).attribution = this.attributionText;699          break;700        case 'idle':701          this.idleNow = true;702          break;703        case 'move':704          this.idleNow = false;705          // Le moteur marque ses propres gestes ; le SDK y ajoute le clavier, les boutons intégrés et le clic sur une grappe.706          (payload as Record<string, unknown>).byUser = this.userMoving || payload.byUser === true;707          break;708        case 'moveend':709          (payload as Record<string, unknown>).byUser = this.userMoving || payload.byUser === true;710          this.userMoving = false;711          break;712        case 'hover':713          if (this.scaffold) this.scaffold.canvas.style.cursor = payload.id !== null && payload.id !== undefined ? 'pointer' : '';714          break;715        case 'draw:done':716        case 'draw:cancel':717          this.drawing = false;718          if (this.scaffold) this.scaffold.canvas.style.cursor = '';719          break;720        case 'cluster:click': {721          // Une grappe d'annonces à la même adresse ne se défait à aucun zoom : ses marqueurs sont joints.722          const c = payload as unknown as KaMapEventMap['cluster:click'];723          if (typeof c.expandable !== 'boolean') c.expandable = Number.isFinite(c.expansionZoom) && c.expansionZoom <= 20 && c.expansionZoom > this.km.camera()[2] + 0.01;724          if (!c.expandable) {725            try {726              c.leaves = this.clusterLeaves(c.layer, c.clusterId, { limit: 100 }).ids;727            } catch {728              /* grappe déjà disparue */729            }730          } else if (this.expandClusters) {731            this.userEase({ center: c.lngLat, zoom: Math.min(20, c.expansionZoom) }, 450);732          }733          break;734        }735        case 'error':736          (payload as Record<string, unknown>).code ??= 'engine';737          break;738      }739      this.emitter.emit(type as KaMapEventType, payload as never);740    }741  }742743  private pumpNetwork(): void {744    const cancelled = this.km.take_cancelled();745    for (let i = 0; i < cancelled.length; i++) this.fetcher.cancel(cancelled[i]);746    const reqs = this.km.take_fetches() as unknown as [number, string, FetchKind, number][];747    for (const r of reqs) this.fetcher.enqueue(r[0], r[1], r[2], r[3]);748  }749750  private pumpBuilds(): void {751    if (!this.pool) return;752    const dropped = this.km.take_cancelled_builds();753    for (let i = 0; i < dropped.length; i++) this.pool.cancel(dropped[i]);754    const builds = this.km.take_builds() as unknown as [number, number, number, number, number, Uint8Array][];755    for (const b of builds) this.pool.submit({ job: b[0], z: b[1], x: b[2], y: b[3], rev: b[4], bytes: b[5] });756  }757758  private pumpStore(): void {759    if (!this.km.has_store_ops()) return;760    const ops = this.km.take_store_ops() as unknown as StoreOp[];761    this.cache.apply(ops);762  }763764  private styleDocument(rev: number): string | undefined {765    if (this.destroyed || rev !== this.km.style_rev()) return undefined;766    let doc = this.styleDocs.get(rev);767    if (doc === undefined) {768      doc = this.km.style_document();769      this.styleDocs.clear();770      this.styleDocs.set(rev, doc);771    }772    return doc;773  }774775  private buildLocal(job: BuildJob): void {776    if (this.destroyed || this.fatalError) return;777    try {778      const doc = this.styleDocument(job.rev);779      if (doc === undefined) {780        this.km.build_failed(job.job, 'style périmé');781      } else {782        if (this.localStyleRev !== job.rev) {783          this.engine.glue.worker_set_style(job.rev, doc);784          this.localStyleRev = job.rev;785        }786        const out = this.engine.glue.worker_build(job.rev, job.z, job.x, job.y, job.bytes);787        this.km.build_done(job.job, out);788      }789    } catch (e) {790      try {791        this.km.build_failed(job.job, String((e as Error)?.message ?? e));792      } catch (e2) {793        this.fail(e2);794      }795    }796    this.requestFrame();797  }798799  /** Appel du moteur né d'un geste : le mouvement qui suit porte `byUser: true`. */800  private byUser(fn: () => void): void {801    this.userMoving = true;802    this.guard(fn);803  }804805  /** Animation de caméra déclenchée par la personne (clavier, bouton intégré, clic sur une grappe). */806  private userEase(camera: CameraOptions, duration: number): void {807    this.cmd('easeTo', { ...camera, duration });808    this.userMoving = true;809  }810811  /** Mètres par pixel CSS au centre de la vue (échelle graphique). */812  private metersPerPixel(): number {813    const c = this.scaffold?.canvas;814    if (!c) return 0;815    const w = c.clientWidth;816    const h = c.clientHeight;817    const a = this.cmdQuiet<LngLat | null>('unproject', { point: [w / 2 - 50, h / 2] });818    const b = this.cmdQuiet<LngLat | null>('unproject', { point: [w / 2 + 50, h / 2] });819    if (!a || !b) return 0;820    const rad = Math.PI / 180;821    const dLat = (b[1] - a[1]) * rad;822    const dLon = (b[0] - a[0]) * rad;823    const s = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * rad) * Math.cos(b[1] * rad) * Math.sin(dLon / 2) ** 2;824    return (2 * 6371008.8 * Math.asin(Math.sqrt(s))) / 100;825  }826827  private guard(fn: () => void): void {828    if (this.destroyed || this.fatalError) return;829    try {830      fn();831    } catch (e) {832      this.fail(e);833    }834  }835836  /** Erreur irrécupérable du moteur (panique wasm, contexte perdu) : la carte s'arrête, l'application est prévenue. */837  private fail(e: unknown, code = 'engine'): void {838    if (this.fatalError) return;839    const err = e instanceof KaMapError ? e : new KaMapError('engine', `moteur arrêté : ${String((e as Error)?.message ?? e)}`, { cause: e });840    this.fatalError = err;841    cancelAnimationFrame(this.raf);842    this.raf = 0;843    this.fetcher.destroy();844    this.pool?.destroy();845    this.emitter.emit('error', { message: err.message, code, fatal: true });846  }847848  private alive(): void {849    if (this.destroyed) throw new KaMapError('destroyed', 'carte détruite');850    if (this.fatalError) throw this.fatalError;851  }852853  private cmdQuiet<T = void>(op: string, args?: Record<string, unknown>): T {854    this.alive();855    let raw: string;856    try {857      raw = this.km.command(JSON.stringify(args ? { ...args, op } : { op }));858    } catch (e) {859      this.fail(e);860      throw this.fatalError!;861    }862    const out = JSON.parse(raw) as { ok: boolean; result?: T; error?: string };863    if (!out.ok) throw new KaMapError('engine', `${op} : ${out.error}`);864    return out.result as T;865  }866867  private cmd<T = void>(op: string, args?: Record<string, unknown>): T {868    const r = this.cmdQuiet<T>(op, args);869    this.requestFrame();870    return r;871  }872873  // ------------------------------------------------------------------ événements874875  on<K extends KaMapEventType>(type: K, listener: (event: KaMapEvent<K>) => void): () => void {876    return this.emitter.on(type, listener as never);877  }878  once<K extends KaMapEventType>(type: K, listener: (event: KaMapEvent<K>) => void): () => void {879    return this.emitter.once(type, listener as never);880  }881  off<K extends KaMapEventType>(type: K, listener: (event: KaMapEvent<K>) => void): void {882    this.emitter.off(type, listener as never);883  }884885  /** Résolue quand la première vue est entièrement chargée (tout de suite si c'est déjà fait). */886  whenLoaded(): Promise<void> {887    if (this.loaded) return Promise.resolve();888    return new Promise((resolve) => this.once('load', () => resolve()));889  }890  /** Résolue au prochain repos (plus rien à charger ni à animer). */891  whenIdle(): Promise<void> {892    if (this.idleNow && !this.raf) return Promise.resolve();893    return new Promise((resolve) => this.once('idle', () => resolve()));894  }895  /** Vrai si la carte est au repos : plus rien à charger, à animer ni à dessiner. Depuis 0.4.0. */896  get isIdle(): boolean {897    return !this.destroyed && this.idleNow && !this.raf;898  }899  get isLoaded(): boolean {900    return this.loaded;901  }902903  // ------------------------------------------------------------------ caméra904905  getCamera(): Camera {906    this.alive();907    const c = this.km.camera();908    return { center: [c[0], c[1]], zoom: c[2], bearing: c[3], pitch: c[4] };909  }910  jumpTo(camera: CameraOptions): void {911    this.userMoving = false;912    this.cmd('jumpTo', { ...camera });913  }914  easeTo(camera: CameraOptions, options: { duration?: number; easing?: string; padding?: Padding } = {}): void {915    this.userMoving = false;916    this.cmd('easeTo', { ...camera, ...options });917  }918  flyTo(camera: CameraOptions, options: { duration?: number; padding?: Padding } = {}): void {919    this.userMoving = false;920    this.cmd('flyTo', { ...camera, ...options });921  }922  /** `padding` : marge en pixels CSS, uniforme ou par côté (panneau latéral, fiche en bas d'écran). */923  fitBounds(bounds: Bounds, options: { padding?: Padding; maxZoom?: number; duration?: number } = {}): void {924    this.userMoving = false;925    this.cmd('fitBounds', { bounds, ...options });926  }927  /** Survol circulaire d'un quartier. */928  orbit(options: { center?: LngLat; zoom?: number; pitch?: number; turns?: number; duration?: number } = {}): void {929    this.userMoving = false;930    this.cmd('orbit', { ...options });931  }932  /** Transition cinématique entre plusieurs caméras. */933  tour(stops: { camera: CameraOptions; hold?: number }[], options: { loop?: boolean; legDuration?: number } = {}): void {934    this.userMoving = false;935    this.cmd('tour', { stops, ...options });936  }937  /** Arrête l'animation de caméra en cours. */938  stop(): void {939    this.cmd('stop');940  }941  setMode(mode: Mode): void {942    this.userMoving = false;943    this.cmd('setMode', { mode });944    this.nav?.update(this.km.camera()[3], mode === '3d');945    this.emitter.emit('mode', { mode });946  }947  getMode(): Mode {948    return this.cmdQuiet<Mode>('getMode');949  }950  /** Pixels CSS de la coordonnée, ou `null` si elle est derrière la caméra. */951  project(lngLat: LngLat): Point | null {952    return this.cmdQuiet<Point | null>('project', { lngLat });953  }954  unproject(point: Point): LngLat | null {955    return this.cmdQuiet<LngLat | null>('unproject', { point });956  }957  getBounds(): Bounds {958    return this.cmdQuiet<Bounds>('getBounds');959  }960961  // ------------------------------------------------------------------ thème962963  /** Change de thème à chaud. Un thème non embarqué est d'abord téléchargé depuis `endpoints.maps`. */964  async setTheme(name: string): Promise<void> {965    this.alive();966    const info = JSON.parse(this.engine.glue.engine_version()) as { themes: string[] };967    if (info.themes.includes(name)) {968      this.cmd('setTheme', { name });969    } else {970      const document = await fetchThemeDocument(this.endpoints.maps, name);971      this.alive();972      this.cmd('setThemeDocument', { document });973    }974    this.emitTheme();975  }976  /** Thème fourni en document `kastyle/1` (Studio, prévisualisation). Rend les avertissements du validateur. */977  setThemeDocument(document: string | object): { warnings: string[] } {978    const r = this.cmd<{ warnings: string[] }>('setThemeDocument', { document });979    this.emitTheme();980    return r;981  }982  setBrand(app: AppId | null): void {983    this.cmd('setBrand', { app });984    this.emitTheme();985  }986  getTheme(): { name: string; brand: AppId | null } {987    const t = this.cmdQuiet<{ name: string; brand: AppId | null }>('getTheme');988    return { name: t.name, brand: t.brand ?? null };989  }990  private emitTheme(): void {991    this.emitter.emit('theme', this.getTheme());992  }993  /** Thèmes livrés dans le moteur (utilisables hors ligne) et noms de tous les thèmes du produit. */994  listThemes(): { embedded: string[]; all: string[] } {995    const info = JSON.parse(this.engine.glue.engine_version()) as { themes: string[]; themeNames: string[] };996    return { embedded: info.themes, all: info.themeNames };997  }998999  // ------------------------------------------------------------------ couches d'application10001001  addLayer<T extends LayerType>(spec: LayerSpec<T>): { count: number } {1002    const { id, type, options } = spec;1003    const data = spec.data as unknown;1004    if (data instanceof Float64Array) {1005      this.cmd('addLayer', { id, type, options });1006      return { count: this.setLayerData(id, data).count };1007    }1008    return this.cmd<{ count: number }>('addLayer', { id, type, options, data });1009  }1010  /**1011   * Remplace les données d'une couche. Pour de gros nuages de points (`points`, `heat`), un1012   * `Float64Array` de triplets `lon, lat, valeur` évite le passage par JSON.1013   */1014  setLayerData<T extends LayerType>(id: string, data: LayerDataByType[T] | Float64Array): { count: number } {1015    this.alive();1016    if (data instanceof Float64Array) {1017      try {1018        const count = this.km.set_layer_data_binary(id, data);1019        this.requestFrame();1020        return { count };1021      } catch (e) {1022        throw new KaMapError('engine', `setLayerData : ${String((e as Error)?.message ?? e)}`);1023      }1024    }1025    return this.cmd<{ count: number }>('setLayerData', { id, data });1026  }1027  setLayerOptions<T extends LayerType>(id: string, options: LayerOptionsByType[T]): void {1028    this.cmd('setLayerOptions', { id, options });1029  }1030  setLayerVisible(id: string, visible: boolean): void {1031    this.cmd('setLayerOptions', { id, options: { visible } });1032  }1033  removeLayer(id: string): boolean {1034    return this.cmd<boolean>('removeLayer', { id });1035  }1036  hasLayer(id: string): boolean {1037    return this.listLayers().some((l) => l.id === id);1038  }1039  listLayers(): LayerInfo[] {1040    return this.cmdQuiet<LayerInfo[]>('listLayers');1041  }1042  setMarkerState(layer: string, id: string | number, state: MarkerState): boolean {1043    return this.cmd<boolean>('setMarkerState', { layer, id, state });1044  }1045  /** Marqueurs d'une grappe et zoom auquel elle se défait. */1046  clusterLeaves(layer: string, clusterId: number, options: { limit?: number; offset?: number } = {}): { ids: (string | number)[]; expansionZoom: number } {1047    return this.cmdQuiet('clusterLeaves', { layer, clusterId, ...options });1048  }10491050  // ------------------------------------------------------------------ sélection, interaction10511052  select(target: { layer: string; id: string | number }): void {1053    this.cmd('select', { ...target });1054  }1055  clearSelection(): void {1056    this.cmd('clearSelection');1057  }1058  /** Met en évidence l'empreinte réelle sous le point (et la parcelle si la couche existe). */1059  /**1060   * Projection en lot avec, sur demande, l'occultation par les volumes (étiquettes et vues ancrées du site en 3D).1061   * `null` pour un point derrière la caméra. Depuis 0.3.0.1062   */1063  projectMany(points: (LngLat | { lngLat: LngLat; altitude?: number; occlude?: boolean })[], options: { occlude?: boolean } = {}): (ProjectedPoint | null)[] {1064    const out = this.cmd<([number, number, boolean, boolean] | null)[]>('projectMany', { points, occlude: options.occlude === true });1065    return out.map((r) => (r ? { x: r[0], y: r[1], visible: r[2], occluded: r[3] } : null));1066  }1067  /**1068   * Échelle du texte, de 0,5 à 2 : `markers` (pastilles, grappes, étiquettes des outils) et `labels` (étiquettes du1069   * fond). Aucune tuile n'est reconstruite ; l'échelle tient à travers `setTheme` et `setBrand`. Depuis 0.3.0.1070   */1071  setTextScale(scale: { markers?: number; labels?: number }): { markers: number; labels: number } {1072    return this.cmd<{ markers: number; labels: number }>('setTextScale', { ...scale });1073  }1074  /**1075   * Retire la mise en évidence posée par `highlightBuilding`, `reveal` ou `select` (cerne, teinte, pulsation, contour1076   * de parcelle) sans toucher aux états des marqueurs. Rend vrai si quelque chose a été retiré.1077   */1078  clearHighlight(): boolean {1079    return this.cmd<boolean>('clearHighlight') === true;1080  }1081  /**1082   * Met un bâtiment en évidence : celui sous `lngLat`, ou — depuis 0.4.0 — celui qu'une couche `buildings` a rattaché1083   * à l'une de ses données (`{ layer, id }` : le bâtiment qu'elle teinte, rattachement par proximité compris).1084   */1085  highlightBuilding(target: LngLat | { layer: string; id: string | number }, options: { color?: string; pulse?: boolean } = {}): void {1086    if (Array.isArray(target)) this.cmd('highlightBuilding', { lngLat: target, ...options });1087    else this.cmd('highlightBuilding', { layer: target.layer, id: target.id, ...options });1088  }1089  /**1090   * État de chargement de la vue ; avec `point` (pixels CSS), la tuile source sous ce point : arrivée, en échec,1091   * dessinée, couches présentes. Lecture sûre d'un lot : `await map.whenIdle()`, `queryRendered(point)`, et si rien1092   * n'est rendu, `viewState({ point }).at` dit pourquoi. Depuis 0.4.0.1093   */1094  viewState(options: { point?: Point } = {}): ViewState {1095    return this.cmd<ViewState>('viewState', options.point ? { point: options.point } : {});1096  }1097  /**1098   * Lots (parcelles) : `"base"` (défaut : la couche `parcel` des tuiles de fond seulement) ou `"auto"` (le jeu séparé1099   * `/v1/parcel` est lu à la demande là où la tuile de fond n'a pas de lots). Depuis 0.4.0.1100   */1101  setParcelSource(mode: 'base' | 'auto'): { mode: string } {1102    return this.cmd<{ mode: string }>('setParcelSource', { mode });1103  }1104  /** Entités sous le point, du dessus vers le dessous (fond et couches d'application). */1105  queryRendered(point: Point, options: { layers?: string[] } = {}): Feature[] {1106    return this.cmdQuiet<Feature[]>('queryRendered', { point, ...options });1107  }1108  /**1109   * Pastilles et grappes réellement dessinées (après désencombrement), avec leur rectangle à l'écran :1110   * la source des boutons mandataires et des listes synchronisées avec la vue.1111   */1112  queryLayer(layer?: string): RenderedMarker[] {1113    return this.cmdQuiet<RenderedMarker[]>('queryLayer', layer ? { layer } : undefined);1114  }1115  setInteractive(options: InteractiveOptions): Required<InteractiveOptions> {1116    const r = this.cmdQuiet<Required<InteractiveOptions>>('setInteractive', { ...options });1117    this.interactiveState = r;1118    this.input?.applyTouchAction();1119    return r;1120  }1121  /** Animation signature : approche, mise en évidence du bâtiment, puis événement `reveal:open`. Sans effet si mouvement réduit. */1122  reveal(options: { target: LngLat; style?: 'door'; zoom?: number; duration?: number }): { skipped?: string } | null {1123    this.userMoving = false;1124    return this.cmd<{ skipped?: string } | null>('reveal', { ...options });1125  }11261127  // ------------------------------------------------------------------ outils11281129  /** Démarre un tracé : chaque clic ajoute un sommet ; double-clic ou Entrée termine, Échap annule. */1130  startDraw(mode: 'polygon' | 'line'): void {1131    this.cmd('startDraw', { mode });1132    this.drawing = true;1133    if (this.scaffold) this.scaffold.canvas.style.cursor = 'crosshair';1134  }1135  /** Ajoute un sommet par programme. */1136  addDrawPoint(lngLat: LngLat): void {1137    this.cmd('drawAddPoint', { lngLat });1138  }1139  undoDraw(): boolean {1140    return this.cmd<boolean>('drawUndo');1141  }1142  /** Termine le tracé : événement `draw:done` (ou `draw:cancel` s'il manque des sommets). */1143  finishDraw(): DrawPayload | null {1144    return this.cmd<DrawPayload | null>('drawFinish');1145  }1146  /** Abandonne le tracé (événement `draw:cancel`). */1147  stopDraw(): DrawPayload | null {1148    const r = this.cmd<DrawPayload | null>('stopDraw');1149    this.drawing = false;1150    if (this.scaffold) this.scaffold.canvas.style.cursor = '';1151    return r;1152  }1153  get isDrawing(): boolean {1154    return this.drawing;1155  }1156  /** Mesures géodésiques (mètres, mètres carrés). */1157  readonly measure = {1158    distance: (points: LngLat[]): number => this.cmdQuiet<number>('measure.distance', { points }),1159    area: (polygon: LngLat[] | { type: 'Polygon'; coordinates: LngLat[][] }): { area: number; perimeter: number } => this.cmdQuiet('measure.area', { polygon }),1160  };11611162  // ------------------------------------------------------------------ hors ligne / stock persistant11631164  readonly offline = {1165    listRegions: (): OfflineRegion[] => this.cmdQuiet<OfflineRegion[]>('offline.listRegions'),1166    /** Télécharge les tuiles d'une région dans le stock persistant (épinglées : hors plafond). Progression : `offline:progress`. */1167    download: (region: { id: string; name?: string; bounds: Bounds; minZoom?: number; maxZoom?: number }): OfflineRegion => {1168      if (typeof navigator !== 'undefined') void navigator.storage?.persist?.().catch(() => false);1169      return this.cmd<OfflineRegion>('offline.download', { ...region });1170    },1171    remove: (id: string): boolean => {1172      const r = this.cmd<boolean>('offline.remove', { id });1173      this.pumpStore();1174      return r;1175    },1176    usage: (): OfflineUsage => {1177      const u = this.cmdQuiet<Omit<OfflineUsage, 'persistent'>>('offline.usage');1178      return { bytes: u.bytes, tiles: u.tiles, pinnedBytes: u.pinnedBytes, capBytes: u.capBytes, regions: u.regions, persistent: this.cache.persistent };1179    },1180    /** Plafond du stock (LRU), octets. */1181    setCap: (bytes: number): void => {1182      this.cacheCap = Math.max(0, bytes);1183      this.cmd('offline.setCap', { bytes: this.cacheCap });1184      this.pumpStore();1185    },1186    /** Vide le stock, sauf les régions hors ligne épinglées. */1187    clear: (): void => {1188      this.cmd('offline.setCap', { bytes: 0 });1189      this.cmd('offline.setCap', { bytes: this.cacheCap });1190      this.pumpStore();1191    },1192    /**1193     * Archives de région publiées par le service de tuiles et archives installées. Une archive est un1194     * fichier PMTiles entier (des dizaines de Mo) : téléchargée d'un bloc, gardée en mémoire et dans le stock.1195     */1196    listPacks: (): Promise<{ index: OfflinePackIndex; installed: string[] }> =>1197      new Promise((resolve, reject) => {1198        const timer = setTimeout(() => {1199          off();1200          reject(new KaMapError('network', 'index des archives hors ligne injoignable'));1201        }, 20000);1202        const off = this.once('offline:packs', (e) => {1203          clearTimeout(timer);1204          resolve({ index: e.index, installed: e.installed });1205        });1206        try {1207          this.cmd('offline.listPacks');1208        } catch (e) {1209          clearTimeout(timer);1210          off();1211          reject(e);1212        }1213      }),1214    /** Télécharge et installe une archive. Événements : `offline:progress {pack}`, `offline:done {pack, id}`, `offline:error`. */1215    downloadPack: (id: string, url?: string): void => {1216      if (typeof navigator !== 'undefined') void navigator.storage?.persist?.().catch(() => false);1217      this.cmd('offline.downloadPack', url ? { id, url } : { id });1218    },1219    removePack: (id: string): boolean => {1220      const r = this.cmd<boolean>('offline.removePack', { id });1221      this.pumpStore();1222      return r;1223    },1224    /** Attend la fin des écritures en cours dans IndexedDB. */1225    flush: (): Promise<void> => {1226      this.pumpStore();1227      return this.cache.flush();1228    },1229  };12301231  // ------------------------------------------------------------------ calque DOM, accessibilité12321233  /** Positionne un élément du site à une coordonnée (marqueur DOM, infobulle), mis à jour à chaque mouvement. */1234  addOverlay(element: HTMLElement, lngLat: LngLat, options?: OverlayOptions): OverlayHandle {1235    this.alive();1236    if (!this.overlay) throw new KaMapError('options', 'addOverlay : indisponible sur un OffscreenCanvas');1237    return this.overlay.add(element, lngLat, options);1238  }1239  /**1240   * Faux : tout le calque DOM laisse passer le pointeur vers la carte (pendant un tracé, un choix de point) ;1241   * vrai : chaque élément retrouve son état (`OverlayOptions.interactive`).1242   */1243  setOverlaysInteractive(on: boolean): void {1244    this.overlay?.setInteractive(on);1245  }1246  /** Crée un vrai `<button>` par marqueur, superposé à sa pastille (clavier, lecteurs d'écran). */1247  createMarkerProxies(options: MarkerProxyOptions): MarkerProxyHandle {1248    this.alive();1249    if (!this.overlay) throw new KaMapError('options', 'createMarkerProxies : indisponible sur un OffscreenCanvas');1250    return this.overlay.createProxies(options);1251  }12521253  // ------------------------------------------------------------------ divers12541255  /** Budgets mémoire du moteur, octets : tuiles prêtes à dessiner (GPU) et octets sources gardés en mémoire. */1256  setMemoryBudget(budget: { tiles?: number; sources?: number }): { tiles: number; sources: number } {1257    return this.cmd('setMemoryBudget', { ...budget });1258  }1259  /** Bornes de zoom de cette carte (0 à 20 par défaut). */1260  setZoomRange(min: number, max: number): { min: number; max: number } {1261    return this.cmd('setZoomRange', { min, max });1262  }1263  /** Tient le **centre** de la carte dans des bornes (`null` : libre). Le bord de la vue peut dépasser d'une demi-vue. */1264  setMaxBounds(bounds: Bounds | null): Bounds | null {1265    return this.cmd<Bounds | null>('setMaxBounds', { bounds });1266  }1267  /**1268   * Masque ou rétablit des familles d'étiquettes et de pictogrammes du fond, par couche source1269   * (`poi`, `transit`, `place`, `road`, `housenum`, `water`, `landuse`…). Gardé au changement de thème.1270   */1271  setBaseLabels(visibility: Record<string, boolean | string[]>): { hidden: string[]; /** Genres masqués, `"couche:genre"` (`"place:suburb"`). */ hiddenKinds?: string[] } {1272    return this.cmd('setBaseLabels', { ...visibility });1273  }1274  /**1275   * Rectangles de l'interface du site posés sur la carte (`[x0, y0, x1, y1]` en pixels CSS du canvas) : aucune1276   * pastille n'y est posée, les plaques de grappe s'en écartent, les étiquettes du fond les évitent.1277   */1278  setObstacles(rects: [number, number, number, number][]): { count: number } {1279    this.alive();1280    this.hostObstacles = rects.map((r) => [r[0], r[1], r[2], r[3]]);1281    this.syncObstacles(true);1282    return { count: this.hostObstacles.length };1283  }1284  /**1285   * Retrait des commandes du SDK (boutons, échelle) depuis les bords de la carte, en pixels CSS : à appeler quand une1286   * feuille ou une barre du site recouvre un bord (`setControlInsets({ bottom: 320 })` feuille ouverte, `{}` fermée).1287   * Ne touche ni la caméra ni la marge permanente. Depuis 0.4.0.1288   */1289  setControlInsets(insets: ControlInsets): void {1290    this.alive();1291    this.scaffold?.setInsets(insets);1292    this.controlRectsCache = null;1293    this.syncObstacles(true);1294  }1295  /**1296   * Zones données au moteur : celles du site (`setObstacles`), puis les commandes du SDK, puis les éléments du calque1297   * DOM déclarés `obstacle` — 32 au plus (limite du moteur). `moving` : pendant un mouvement, 8 envois par seconde au plus.1298   */1299  private syncObstacles(force = false, moving = false): void {1300    if (this.destroyed || this.fatalError) return;1301    const now = performance.now();1302    if (!force && moving && now - this.obstaclesAt < 125) {1303      this.obstaclesLate = true;1304      return;1305    }1306    const rects: [number, number, number, number][] = [...this.hostObstacles];1307    if (this.scaffold && this.controlObstacles) {1308      this.controlRectsCache ??= this.scaffold.controlRects();1309      rects.push(...this.controlRectsCache);1310    }1311    if (this.overlay?.hasObstacles) rects.push(...this.overlay.obstacleRects());1312    if (rects.length > 32) rects.length = 32;1313    const sig = rects.map((r) => r.map((v) => Math.round(v)).join(',')).join(';');1314    this.obstaclesLate = false;1315    if (sig === this.obstaclesSig) return;1316    this.obstaclesSig = sig;1317    this.obstaclesAt = now;1318    this.cmdQuiet('setObstacles', { rects });1319    this.requestFrame();1320  }1321  /**1322   * Indique au moteur l'état du réseau (suivi seul d'après les événements `online` / `offline` du navigateur) :1323   * hors réseau, plus aucune demande de tuile ne part et la carte se met au repos ; au retour, tout ce qui1324   * manquait est redemandé.1325   */1326  setNetworkOnline(online: boolean): void {1327    this.cmd('setNetworkOnline', { online });1328  }1329  /** Marge permanente de la caméra (panneau latéral fixe) : le centre visuel de la carte est décalé d'autant. */1330  setPadding(padding: Padding): unknown {1331    return this.cmd('setPadding', { padding });1332  }1333  /** Relance les tuiles abandonnées après leurs essais (retour du réseau), sans recharger la vue. */1334  retryFailed(): number {1335    return this.cmd<number>('retryFailed');1336  }1337  /** Pastille de position de l'utilisateur, dessinée par le moteur (précision en mètres, cap en degrés). `null` la retire. */1338  setLocation(location: { lngLat: LngLat; accuracy?: number; heading?: number } | null): void {1339    if (location) this.cmd('location.set', { ...location });1340    else this.cmd('location.clear');1341  }1342  /** Libère de la mémoire sous pression (1 : budgets divisés par deux ; 2 : minimum). */1343  trimMemory(level: 1 | 2 = 1): void {1344    this.cmd('trimMemory', { level });1345  }1346  setQuality(quality: Quality): void {1347    this.cmd('setQuality', this.backend === 'webgl2' ? { quality, backend: 'webgl2' } : { quality });1348  }1349  /** Impose ou lève le mouvement réduit (désactive alors le suivi de `prefers-reduced-motion`). */1350  setReducedMotion(on: boolean): void {1351    this.reducedMotionAuto = false;1352    this.applyReducedMotion(on);1353  }1354  private applyReducedMotion(on: boolean): void {1355    if (this.destroyed || this.fatalError) return;1356    this.reduced = on;1357    this.cmd('setReducedMotion', { on });1358  }1359  get reducedMotion(): boolean {1360    return this.reduced;1361  }1362  setKeyboard(enabled: boolean): void {1363    this.keyboard = enabled;1364  }13651366  /** Recalcule la taille (appelé seul par ResizeObserver ; à appeler pour un OffscreenCanvas). */1367  resize(size?: { width: number; height: number; pixelRatio?: number }): void {1368    if (this.destroyed || this.fatalError) return;1369    let w: number;1370    let h: number;1371    let pr: number;1372    if (size) {1373      w = size.width;1374      h = size.height;1375      pr = size.pixelRatio ?? Math.min(globalThis.devicePixelRatio || 1, this.maxPixelRatio);1376    } else if (this.scaffold) {1377      const c = this.scaffold.canvas;1378      w = c.clientWidth;1379      h = c.clientHeight;1380      pr = Math.min(window.devicePixelRatio || 1, this.maxPixelRatio);1381    } else {1382      return;1383    }1384    if (w <= 0 || h <= 0) return;1385    if (w === this.appliedSize[0] && h === this.appliedSize[1] && pr === this.appliedSize[2]) return;1386    this.appliedSize = [w, h, pr];1387    let applied = pr;1388    this.guard(() => {1389      applied = this.km.resize(w, h, pr);1390      // Trame immédiate : pas d'image étirée entre le changement de taille et la trame suivante.1391      this.km.request_redraw();1392      this.km.frame(performance.now());1393    });1394    if (this.fatalError) return;1395    this.afterFrame();1396    this.overlay?.invalidate();1397    this.controlRectsCache = null;1398    this.syncObstacles(true);1399    this.emitter.emit('resize', { width: w, height: h, pixelRatio: applied });1400    this.requestFrame();1401  }14021403  getPerf(): PerfSample {1404    return this.cmdQuiet<PerfSample>('getPerf');1405  }1406  /** Mesures du SDK : cadence réelle, mémoire wasm, réseau, workers. */1407  getStats(): SdkStats {1408    const heap = (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory?.usedJSHeapSize ?? null;1409    return {1410      backend: this.backend,1411      framesRendered: this.destroyed || this.fatalError ? 0 : this.km.frames_rendered(),1412      fps: this.raf ? this.fpsValue : 0,1413      frameCpuMs: this.cpuMs,1414      wasmMemoryBytes: this.engine.memory.buffer.byteLength,1415      wasmLiveBytes: this.engine.glue.alloc_live_bytes(),1416      wasmPeakBytes: this.engine.glue.alloc_peak_bytes(),1417      jsHeapBytes: heap,1418      fetch: { ...this.fetcher.stats },1419      workers: this.pool ? { ...this.pool.stats } : null,1420      engineLoadMs: this.engine.loadMs,1421      createMs: this.createMs,1422      overlays: this.overlay?.count ?? 0,1423    };1424  }1425  /**1426   * Vrai si le relief est dessiné en élévation à cette trame (mode 3D, zoom ≥ 8, thème à relief, cran de qualité1427   * qui le permet). Les couches au sol y sont drapées ; `slot: "top"` les fait passer devant les volumes.1428   */1429  isReliefActive(): boolean {1430    this.alive();1431    return this.km.relief_active();1432  }1433  /** Version des données de tuiles (`data_version` du TileJSON), une fois connue ; elle entre dans l'adresse des tuiles (`?v=`). */1434  get dataVersion(): string | undefined {1435    return this.dataVersionText;1436  }1437  /** Adaptateur GPU retenu. */1438  getAdapterInfo(): { backend: Backend; name: string; vendor: number; device: number; driver: string; format: string; maxTextureSize: number } {1439    this.alive();1440    return JSON.parse(this.km.adapter_info());1441  }1442  /** Mention des sources (TileJSON du service de tuiles), affichée en permanence par le SDK. */1443  get attribution(): string {1444    return this.attributionText;1445  }1446  getCanvas(): HTMLCanvasElement | OffscreenCanvas {1447    return this.scaffold?.canvas ?? this.offscreen!;1448  }1449  /** Le `<canvas>` de la carte (classe `ka-maps-canvas`), ou `null` sur un OffscreenCanvas. */1450  getCanvasElement(): HTMLCanvasElement | null {1451    return this.scaffold?.canvas ?? null;1452  }1453  getContainer(): HTMLElement | null {1454    return this.scaffold?.root ?? null;1455  }1456  get isDestroyed(): boolean {1457    return this.destroyed;1458  }14591460  /** Libère le GPU, les workers, les écouteurs et le DOM créé par le SDK. */1461  destroy(): void {1462    if (this.destroyed) return;1463    this.emitter.emit('destroy', {});1464    this.destroyed = true;1465    cancelAnimationFrame(this.raf);1466    this.raf = 0;1467    for (const d of this.disposers) d();1468    this.disposers.length = 0;1469    this.input?.destroy();1470    this.fetcher.destroy();1471    this.pool?.destroy();1472    this.nav?.remove();1473    this.scale?.remove();1474    this.overlay?.destroy();1475    try {1476      if (!this.fatalError && this.km.has_store_ops()) this.cache.apply(this.km.take_store_ops() as unknown as StoreOp[]);1477    } catch {1478      /* moteur déjà arrêté */1479    }1480    this.cache.close();1481    try {1482      this.km.free();1483    } catch {1484      /* moteur déjà arrêté */1485    }1486    this.scaffold?.destroy();1487    this.emitter.clear();1488  }1489}14901491function resolveReducedMotion(opt: boolean | 'auto' | undefined): boolean {1492  if (typeof opt === 'boolean') return opt;1493  return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;1494}14951496async function fetchThemeDocument(mapsEndpoint: string, name: string): Promise<string> {1497  if (!/^[a-z0-9][a-z0-9_-]{0,40}$/.test(name)) throw new KaMapError('theme', `nom de thème invalide : ${name}`);1498  const url = `${mapsEndpoint}/v1/themes/${name}.json`;1499  let res: Response;1500  try {1501    res = await fetch(url, { credentials: 'omit' });1502  } catch (cause) {1503    throw new KaMapError('theme', `thème « ${name} » : ${url} injoignable (thème non embarqué dans le moteur)`, { cause });1504  }1505  if (!res.ok) throw new KaMapError('theme', `thème « ${name} » non publié (HTTP ${res.status} sur ${url})`);1506  return await res.text();1507}15081509export { resolveAssetsUrl };1510
Files main
Menu

Theme