SPB Git

Repository Public

index.tsx 10.6 KB 269 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : sdk/web/src/react/index.tsx9 * Module           : react10 * 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'use client';43// @ka/maps/react — liaisons React minces (React 18.3+ / 19 ; Vite + React et Next.js 16, app router).44// Le cœur du SDK reste sans framework : ce module ne fait que créer / détruire la carte avec le45// cycle de vie du composant et exposer quelques hooks.4647import { createContext, useContext, useEffect, useImperativeHandle, useRef, useState, type CSSProperties, type ReactNode, type Ref } from 'react';48import { KaMap } from '../map.js';49import { KaMapError, type AppId, type CameraOptions, type KaMapEvent, type KaMapEventType, type KaMapOptions, type LayerDataByType, type LayerOptionsByType, type LayerType, type LngLat, type Mode, type OverlayOptions } from '../types.js';50import { createPortal } from 'react-dom';5152const MapContext = createContext<KaMap | null>(null);5354export interface KaMapViewProps {55  /** Options de création (lues une fois, au montage). Thème, marque, mode et caméra suivent ensuite les props dédiées. */56  options?: KaMapOptions;57  theme?: string;58  app?: AppId | null;59  mode?: Mode;60  /** Caméra pilotée : tout changement déclenche un `easeTo` (ou `jumpTo` si mouvement réduit). */61  camera?: CameraOptions;62  className?: string;63  style?: CSSProperties;64  /** Contenu affiché si la carte ne peut pas démarrer (ni WebGPU ni WebGL 2, actifs introuvables) : la liste de repli du site. */65  fallback?: ReactNode | ((error: KaMapError) => ReactNode);66  /** Contenu affiché pendant le chargement du moteur. */67  loading?: ReactNode;68  onReady?: (map: KaMap) => void;69  onError?: (error: KaMapError) => void;70  /** Enfants rendus une fois la carte prête ; ils peuvent utiliser `useKaMap()`. */71  children?: ReactNode;72  ref?: Ref<KaMap | null>;73  'aria-label'?: string;74}7576/** Carte KA Maps. Le conteneur prend la taille que lui donne le site (`className` / `style`). */77export function KaMapView(props: KaMapViewProps) {78  const { options, theme, app, mode, camera, className, style, fallback, loading, onReady, onError, children, ref } = props;79  const host = useRef<HTMLDivElement>(null);80  const [map, setMap] = useState<KaMap | null>(null);81  const [error, setError] = useState<KaMapError | null>(null);82  const cb = useRef({ onReady, onError });83  cb.current = { onReady, onError };84  const initial = useRef({ options, theme, app, mode, camera });8586  useEffect(() => {87    const el = host.current;88    if (!el) return;89    let cancelled = false;90    let created: KaMap | null = null;91    const init = initial.current;92    const label = props['aria-label'];93    KaMap.create(el, {94      ...init.options,95      ...(init.theme !== undefined ? { theme: init.theme } : null),96      ...(init.app ? { app: init.app } : null),97      ...(init.mode ? { mode: init.mode } : null),98      ...init.camera,99      ...(label ? { strings: { ...init.options?.strings, mapLabel: label } } : null),100    }).then(101      (m) => {102        if (cancelled) {103          m.destroy();104          return;105        }106        created = m;107        setMap(m);108        cb.current.onReady?.(m);109      },110      (e) => {111        if (cancelled) return;112        const err = e instanceof KaMapError ? e : new KaMapError('engine', String(e?.message ?? e), { cause: e });113        setError(err);114        cb.current.onError?.(err);115      },116    );117    return () => {118      cancelled = true;119      created?.destroy();120      setMap(null);121    };122    // Création unique : les options de création ne sont pas réactives (voir les props dédiées).123    // eslint-disable-next-line react-hooks/exhaustive-deps124  }, []);125126  useImperativeHandle<KaMap | null, KaMap | null>(ref, () => map, [map]);127128  useEffect(() => {129    if (map && theme !== undefined && map.getTheme().name !== theme) map.setTheme(theme).catch((e) => cb.current.onError?.(e));130  }, [map, theme]);131  useEffect(() => {132    if (map && app !== undefined && map.getTheme().brand !== app) map.setBrand(app);133  }, [map, app]);134  useEffect(() => {135    if (map && mode && map.getMode() !== mode) map.setMode(mode);136  }, [map, mode]);137  const camKey = camera ? JSON.stringify(camera) : '';138  const firstCam = useRef(true);139  useEffect(() => {140    if (!map || !camera) return;141    if (firstCam.current) {142      firstCam.current = false;143      if (camKey === JSON.stringify(initial.current.camera ?? null)) return;144    }145    map.easeTo(camera, { duration: 600 });146    // eslint-disable-next-line react-hooks/exhaustive-deps147  }, [map, camKey]);148149  // Aucun style en ligne par défaut : le rendu serveur reste compatible avec une CSP sans150  // 'unsafe-inline' (le SDK pose `position: relative` par le CSSOM si le conteneur est statique).151  return (152    <div ref={host} className={className} style={style} data-ka-map="">153      {error ? (typeof fallback === 'function' ? fallback(error) : (fallback ?? null)) : null}154      {!map && !error ? (loading ?? null) : null}155      {map ? <MapContext.Provider value={map}>{children}</MapContext.Provider> : null}156    </div>157  );158}159160/** La carte du `<KaMapView>` englobant (les enfants ne sont rendus qu'une fois la carte prête). */161export function useKaMap(): KaMap {162  const map = useContext(MapContext);163  if (!map) throw new Error('useKaMap : à utiliser dans un enfant de <KaMapView>');164  return map;165}166167/** Abonnement à un événement de la carte ; le dernier `handler` est toujours celui appelé. */168export function useKaMapEvent<K extends KaMapEventType>(type: K, handler: (event: KaMapEvent<K>) => void, map?: KaMap | null): void {169  const ctx = useContext(MapContext);170  const target = map === undefined ? ctx : map;171  const h = useRef(handler);172  h.current = handler;173  useEffect(() => {174    if (!target) return;175    return target.on(type, (e) => h.current(e));176  }, [target, type]);177}178179/** Couche d'application déclarative : créée au montage, données et options mises à jour, retirée au démontage. */180export function useKaLayer<T extends LayerType>(id: string, type: T, data: LayerDataByType[T] | undefined, options?: LayerOptionsByType[T], map?: KaMap | null): void {181  const ctx = useContext(MapContext);182  const target = map === undefined ? ctx : map;183  const optKey = options ? JSON.stringify(options) : '';184  const first = useRef(true);185  useEffect(() => {186    if (!target) return;187    target.addLayer({ id, type, data, options });188    first.current = true;189    return () => {190      if (!target.isDestroyed) {191        try {192          target.removeLayer(id);193        } catch {194          /* carte arrêtée */195        }196      }197    };198    // eslint-disable-next-line react-hooks/exhaustive-deps199  }, [target, id, type]);200  useEffect(() => {201    if (!target || target.isDestroyed) return;202    if (first.current) {203      first.current = false;204      return;205    }206    if (data !== undefined) target.setLayerData(id, data);207    // eslint-disable-next-line react-hooks/exhaustive-deps208  }, [data]);209  useEffect(() => {210    if (!target || target.isDestroyed || !options || !target.hasLayer(id)) return;211    target.setLayerOptions(id, options);212    // eslint-disable-next-line react-hooks/exhaustive-deps213  }, [optKey]);214}215216/** Composant équivalent à `useKaLayer`. */217export function KaLayer<T extends LayerType>(props: { id: string; type: T; data?: LayerDataByType[T]; options?: LayerOptionsByType[T] }): null {218  useKaLayer(props.id, props.type, props.data, props.options);219  return null;220}221222/** Caméra courante, mise à jour à la fin de chaque mouvement (`moveend`). */223export function useKaCamera(map?: KaMap | null) {224  const ctx = useContext(MapContext);225  const target = map === undefined ? ctx : map;226  const [cam, setCam] = useState(() => (target && !target.isDestroyed ? target.getCamera() : null));227  useEffect(() => {228    if (!target) return;229    setCam(target.getCamera());230    return target.on('moveend', (e) => setCam({ center: e.center, zoom: e.zoom, bearing: e.bearing, pitch: e.pitch }));231  }, [target]);232  return cam;233}234235/**236 * Élément React posé à une coordonnée (marqueur DOM, infobulle) : les enfants sont rendus dans un237 * élément que la carte repositionne à chaque mouvement.238 */239export function KaOverlay(props: { lngLat: LngLat; options?: OverlayOptions; className?: string; children?: ReactNode }) {240  const map = useKaMap();241  const [el, setEl] = useState<HTMLDivElement | null>(null);242  const handle = useRef<ReturnType<KaMap['addOverlay']> | null>(null);243  const optKey = props.options ? JSON.stringify(props.options) : '';244  useEffect(() => {245    const node = document.createElement('div');246    if (props.className) node.className = props.className;247    handle.current = map.addOverlay(node, props.lngLat, props.options);248    setEl(node);249    return () => {250      handle.current?.remove();251      handle.current = null;252      setEl(null);253    };254    // eslint-disable-next-line react-hooks/exhaustive-deps255  }, [map]);256  useEffect(() => {257    handle.current?.setLngLat(props.lngLat);258    // eslint-disable-next-line react-hooks/exhaustive-deps259  }, [props.lngLat[0], props.lngLat[1]]);260  useEffect(() => {261    if (props.options) handle.current?.setOptions(props.options);262    // eslint-disable-next-line react-hooks/exhaustive-deps263  }, [optKey]);264  return el ? createPortal(props.children, el) : null;265}266267export { KaMap, KaMapError };268export type { KaMapOptions };269
Files main
Menu

Theme