SPB Git

Repository Public

input.ts 17.6 KB 497 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : sdk/web/src/input.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// Reconnaissance des gestes : pointeur (souris, stylet, toucher), molette, clavier.43// Les gestes sont traduits en appels du moteur selon docs/BINDINGS.md § 8 ; le moteur applique lui-même44// les indicateurs de `setInteractive`.4546import type { Camera, CameraOptions, InteractiveOptions } from './types.js';4748export interface InputHost {49  readonly canvas: HTMLElement;50  panBy(dx: number, dy: number): void;51  zoomBy(delta: number, x: number, y: number): void;52  rotateBy(deg: number): void;53  pitchBy(deg: number): void;54  fling(vx: number, vy: number, zoomV: number, bearingV: number): void;55  tap(x: number, y: number): void;56  doubleTap(x: number, y: number, out: boolean): void;57  pointerMove(x: number, y: number): void;58  getCamera(): Camera;59  easeTo(camera: CameraOptions, durationMs: number): void;60  unproject(x: number, y: number): [number, number] | null;61  interactive(): Required<InteractiveOptions>;62  reducedMotion(): boolean;63  keyboardEnabled(): boolean;64  isDrawing(): boolean;65  finishDraw(): void;66  cancelDraw(): void;67  undoDraw(): void;68  hint(kind: 'wheel' | 'touch'): void;69  requestFrame(): void;70  announce(): void;71}7273interface Ptr {74  id: number;75  x: number;76  y: number;77  type: string;78}7980interface Sample {81  t: number;82  x: number;83  y: number;84}8586const TAP_SLOP_MOUSE = 4;87const TAP_SLOP_TOUCH = 12;88const DOUBLE_TAP_MS = 320;89// Deux appuis ne font un double appui que s'ils tombent au même endroit (un tracé pose vite deux sommets voisins).90const DOUBLE_TAP_DIST_MOUSE = 8;91const DOUBLE_TAP_DIST_TOUCH = 28;92const ROTATE_THRESHOLD_DEG = 6;93const KEY_PAN_PX = 120;9495export class InputController {96  private ptrs = new Map<number, Ptr>();97  private dragButton = -1;98  private moved = 0;99  private downAt = 0;100  private downPos: [number, number] = [0, 0];101  private samples: Sample[] = [];102  private gesturing = false;103  private maxPointers = 0;104  private lastTap: { t: number; x: number; y: number } | null = null;105  // Geste à deux doigts106  private pinch: { dist: number; angle: number; cx: number; cy: number; rotAcc: number; rotating: boolean; mode: 'undecided' | 'pinch' | 'pitch'; travel: number } | null = null;107  // Molette lissée108  private wheelLeft = 0;109  private wheelAt: [number, number] = [0, 0];110  private wheelActive = false;111  private wheelEndTimer: ReturnType<typeof setTimeout> | undefined;112  private lastTick = 0;113  private hoverPending: [number, number] | null = null;114  private disposers: (() => void)[] = [];115116  constructor(private host: InputHost) {117    const c = host.canvas;118    const on = <K extends keyof HTMLElementEventMap>(type: K, fn: (e: HTMLElementEventMap[K]) => void, opts?: AddEventListenerOptions) => {119      c.addEventListener(type, fn as EventListener, opts);120      this.disposers.push(() => c.removeEventListener(type, fn as EventListener, opts));121    };122    on('pointerdown', this.onDown);123    on('pointermove', this.onMove);124    on('pointerup', this.onUp);125    on('pointercancel', this.onCancel);126    on('pointerleave', this.onLeave);127    on('wheel', this.onWheel, { passive: false });128    on('contextmenu', (e) => e.preventDefault());129    on('keydown', this.onKey);130    on('dblclick', (e) => e.preventDefault());131    this.applyTouchAction();132  }133134  /** `touch-action` : la carte prend tous les gestes, sauf en mode coopératif (un doigt fait défiler la page). */135  applyTouchAction(): void {136    this.host.canvas.style.touchAction = this.host.interactive().cooperative ? 'pan-x pan-y' : 'none';137  }138139  private pos(e: { clientX: number; clientY: number }): [number, number] {140    const r = this.host.canvas.getBoundingClientRect();141    return [e.clientX - r.left, e.clientY - r.top];142  }143144  private onDown = (e: PointerEvent): void => {145    if (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 2) return;146    const [x, y] = this.pos(e);147    const c = this.host.canvas;148    if (document.activeElement !== c) c.focus({ preventScroll: true });149    try {150      c.setPointerCapture(e.pointerId);151    } catch {152      /* pointeur synthétique sans capture */153    }154    this.ptrs.set(e.pointerId, { id: e.pointerId, x, y, type: e.pointerType });155    this.stopWheel();156    if (this.ptrs.size === 1) {157      this.dragButton = e.pointerType === 'mouse' ? (e.button === 2 || e.ctrlKey ? 2 : 0) : 0;158      this.moved = 0;159      this.maxPointers = 1;160      this.downAt = e.timeStamp;161      this.downPos = [x, y];162      this.samples = [{ t: e.timeStamp, x, y }];163      this.gesturing = false;164      this.pinch = null;165    } else if (this.ptrs.size === 2) {166      this.maxPointers = 2;167      this.startPinch();168    } else {169      this.maxPointers = Math.max(this.maxPointers, this.ptrs.size);170    }171    if (e.pointerType === 'mouse') e.preventDefault();172  };173174  private startPinch(): void {175    const [a, b] = [...this.ptrs.values()];176    const dx = b.x - a.x;177    const dy = b.y - a.y;178    this.pinch = { dist: Math.hypot(dx, dy) || 1, angle: Math.atan2(dy, dx), cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, rotAcc: 0, rotating: false, mode: 'undecided', travel: 0 };179    this.gesturing = true;180  }181182  private onMove = (e: PointerEvent): void => {183    const [x, y] = this.pos(e);184    const p = this.ptrs.get(e.pointerId);185    if (!p) {186      // Survol (souris sans bouton) : état de survol des pastilles, aperçu de l'outil de dessin.187      if (e.pointerType === 'mouse' || e.pointerType === 'pen') {188        this.hoverPending = [x, y];189        this.host.requestFrame();190      }191      return;192    }193    const dx = x - p.x;194    const dy = y - p.y;195    if (this.ptrs.size === 1) {196      p.x = x;197      p.y = y;198      this.moved = Math.max(this.moved, Math.hypot(x - this.downPos[0], y - this.downPos[1]));199      const slop = p.type === 'mouse' ? TAP_SLOP_MOUSE : TAP_SLOP_TOUCH;200      if (!this.gesturing && this.moved < slop) return;201      const it = this.host.interactive();202      if (p.type === 'touch' && it.cooperative) {203        // Un doigt en mode coopératif : la page défile (touch-action), la carte ne bouge pas.204        if (!this.gesturing) this.host.hint('touch');205        this.gesturing = true;206        return;207      }208      this.gesturing = true;209      if (this.dragButton === 2) {210        this.host.rotateBy(dx * 0.8);211        this.host.pitchBy(-dy * 0.5);212      } else {213        this.host.panBy(dx, dy);214        this.samples.push({ t: e.timeStamp, x, y });215        if (this.samples.length > 24) this.samples.shift();216      }217      this.host.canvas.style.cursor = 'grabbing';218      this.host.requestFrame();219    } else if (this.ptrs.size === 2 && this.pinch) {220      p.x = x;221      p.y = y;222      const [a, b] = [...this.ptrs.values()];223      const ddx = b.x - a.x;224      const ddy = b.y - a.y;225      const dist = Math.hypot(ddx, ddy) || 1;226      const angle = Math.atan2(ddy, ddx);227      const cx = (a.x + b.x) / 2;228      const cy = (a.y + b.y) / 2;229      const g = this.pinch;230      const mcx = cx - g.cx;231      const mcy = cy - g.cy;232      g.travel += Math.hypot(mcx, mcy);233      this.moved = Math.max(this.moved, g.travel, Math.abs(dist - g.dist));234      if (g.mode === 'undecided') {235        // Deux doigts qui glissent ensemble verticalement, écartement stable : inclinaison.236        const spread = Math.abs(dist - g.dist);237        if (g.travel > 14 || spread > 10) {238          const horizontalPair = Math.abs(ddy) < Math.abs(ddx) * 0.9;239          g.mode = horizontalPair && spread < 8 && Math.abs(mcy) > Math.abs(mcx) * 1.5 ? 'pitch' : 'pinch';240        }241      }242      if (g.mode === 'pitch') {243        this.host.pitchBy(-mcy * 0.4);244      } else {245        let dAng = ((angle - g.angle) * 180) / Math.PI;246        if (dAng > 180) dAng -= 360;247        if (dAng < -180) dAng += 360;248        if (mcx || mcy) this.host.panBy(mcx, mcy);249        const dz = Math.log2(dist / g.dist);250        if (dz) this.host.zoomBy(dz, cx, cy);251        if (!g.rotating) {252          g.rotAcc += dAng;253          if (Math.abs(g.rotAcc) > ROTATE_THRESHOLD_DEG) g.rotating = true;254        } else if (dAng) {255          this.host.rotateBy(-dAng);256        }257      }258      g.dist = dist;259      g.angle = angle;260      g.cx = cx;261      g.cy = cy;262      this.host.requestFrame();263    } else {264      p.x = x;265      p.y = y;266    }267  };268269  private velocity(now: number): [number, number] {270    const recent = this.samples.filter((s) => now - s.t <= 120);271    if (recent.length < 2) return [0, 0];272    const a = recent[0];273    const b = recent[recent.length - 1];274    const dt = (b.t - a.t) / 1000;275    if (dt < 0.016) return [0, 0];276    const clamp = (v: number) => Math.max(-4000, Math.min(4000, v));277    return [clamp((b.x - a.x) / dt), clamp((b.y - a.y) / dt)];278  }279280  private onUp = (e: PointerEvent): void => {281    const p = this.ptrs.get(e.pointerId);282    if (!p) return;283    const [x, y] = this.pos(e);284    this.ptrs.delete(e.pointerId);285    try {286      this.host.canvas.releasePointerCapture(e.pointerId);287    } catch {288      /* rien */289    }290    if (this.ptrs.size >= 2) return;291    if (this.ptrs.size === 1) {292      // Retour à un doigt : le glisser reprend depuis la position du doigt restant.293      const rest = [...this.ptrs.values()][0];294      this.pinch = null;295      this.downPos = [rest.x, rest.y];296      this.samples = [{ t: e.timeStamp, x: rest.x, y: rest.y }];297      return;298    }299    this.host.canvas.style.cursor = '';300    const slop = p.type === 'mouse' ? TAP_SLOP_MOUSE : TAP_SLOP_TOUCH;301    const quick = e.timeStamp - this.downAt < 600;302    if (this.maxPointers >= 2) {303      // Toucher bref à deux doigts : dézoom d'un niveau.304      if (this.moved < TAP_SLOP_TOUCH * 1.5 && quick) this.host.doubleTap(x, y, true);305      else this.host.fling(0, 0, 0, 0);306      this.gesturing = false;307      this.pinch = null;308      this.host.requestFrame();309      return;310    }311    if (this.gesturing && this.moved >= slop) {312      const cooperativeTouch = p.type === 'touch' && this.host.interactive().cooperative;313      if (!cooperativeTouch) {314        const [vx, vy] = this.dragButton === 2 ? [0, 0] : this.velocity(e.timeStamp);315        // Toujours appelé, même à vitesse nulle : c'est lui qui émet `moveend`.316        this.host.fling(vx, vy, 0, 0);317      }318    } else if (this.dragButton === 0 && e.timeStamp - this.downAt < 700) {319      this.handleTap(x, y, e.timeStamp, p.type);320    }321    this.gesturing = false;322    this.host.requestFrame();323  };324325  private handleTap(x: number, y: number, t: number, type = 'mouse'): void {326    const last = this.lastTap;327    const reach = type === 'touch' ? DOUBLE_TAP_DIST_TOUCH : DOUBLE_TAP_DIST_MOUSE;328    if (last && t - last.t < DOUBLE_TAP_MS && Math.hypot(x - last.x, y - last.y) < reach) {329      this.lastTap = null;330      if (this.host.isDrawing()) this.host.finishDraw();331      else this.host.doubleTap(x, y, false);332      return;333    }334    this.lastTap = { t, x, y };335    this.host.tap(x, y);336  }337338  private onCancel = (e: PointerEvent): void => {339    if (!this.ptrs.delete(e.pointerId)) return;340    if (this.ptrs.size === 0) {341      if (this.gesturing && !(e.pointerType === 'touch' && this.host.interactive().cooperative)) this.host.fling(0, 0, 0, 0);342      this.gesturing = false;343      this.pinch = null;344      this.host.canvas.style.cursor = '';345      this.host.requestFrame();346    }347  };348349  private onLeave = (e: PointerEvent): void => {350    if (this.ptrs.has(e.pointerId)) return;351    // Pendant un tracé, le sommet d'aperçu reste où il était (une position hors carte donnerait une coordonnée aberrante).352    if (this.host.isDrawing()) return;353    // Sortie du pointeur : plus aucun marqueur survolé.354    this.hoverPending = [-1e6, -1e6];355    this.host.requestFrame();356  };357358  private onWheel = (e: WheelEvent): void => {359    const it = this.host.interactive();360    if (!it.zoom) return;361    if (it.cooperative && !(e.ctrlKey || e.metaKey)) {362      this.host.hint('wheel');363      return; // la page défile364    }365    e.preventDefault();366    const [x, y] = this.pos(e);367    let dy = e.deltaY;368    if (e.deltaMode === 1) dy *= 40;369    else if (e.deltaMode === 2) dy *= 600;370    // Ctrl + molette = pincement du pavé tactile (deltas petits et précis).371    let delta = e.ctrlKey && e.deltaMode === 0 && Math.abs(dy) < 50 ? -dy / 100 : -dy / 320;372    delta = Math.max(-1.5, Math.min(1.5, delta));373    this.wheelAt = [x, y];374    if (this.host.reducedMotion() || Math.abs(dy) < 30) {375      // Pavé tactile (rafale de petits deltas) ou mouvement réduit : application directe.376      this.host.zoomBy(delta, x, y);377    } else {378      this.wheelLeft = Math.max(-4, Math.min(4, this.wheelLeft + delta));379    }380    this.wheelActive = true;381    clearTimeout(this.wheelEndTimer);382    this.wheelEndTimer = setTimeout(() => this.endWheel(), 180);383    this.host.requestFrame();384  };385386  private endWheel(): void {387    if (!this.wheelActive) return;388    if (Math.abs(this.wheelLeft) > 0.001) {389      // La décélération n'est pas finie : on attend qu'elle se solde.390      this.wheelEndTimer = setTimeout(() => this.endWheel(), 60);391      this.host.requestFrame();392      return;393    }394    this.wheelActive = false;395    this.host.fling(0, 0, 0, 0);396    this.host.announce();397    this.host.requestFrame();398  }399400  private stopWheel(): void {401    if (!this.wheelActive) return;402    clearTimeout(this.wheelEndTimer);403    this.wheelLeft = 0;404    this.wheelActive = false;405    this.host.fling(0, 0, 0, 0);406  }407408  /** Appelé par la carte au début de chaque trame. Rend vrai si une autre trame est nécessaire. */409  tick(nowMs: number): boolean {410    const dt = this.lastTick ? Math.min(0.1, (nowMs - this.lastTick) / 1000) : 1 / 60;411    this.lastTick = nowMs;412    if (this.hoverPending) {413      const [x, y] = this.hoverPending;414      this.hoverPending = null;415      if (this.ptrs.size === 0) this.host.pointerMove(x, y);416    }417    if (Math.abs(this.wheelLeft) > 0.001) {418      const step = Math.abs(this.wheelLeft) < 0.01 ? this.wheelLeft : this.wheelLeft * Math.min(1, dt * 14);419      this.wheelLeft -= step;420      this.host.zoomBy(step, this.wheelAt[0], this.wheelAt[1]);421      return true;422    }423    this.lastTick = 0;424    return false;425  }426427  private onKey = (e: KeyboardEvent): void => {428    if (!this.host.keyboardEnabled() || e.altKey || e.ctrlKey || e.metaKey) return;429    const it = this.host.interactive();430    const cam = this.host.getCamera();431    const dur = this.host.reducedMotion() ? 0 : 220;432    const r = this.host.canvas.getBoundingClientRect();433    const panTo = (dx: number, dy: number) => {434      if (!it.pan) return;435      const c = this.host.unproject(r.width / 2 + dx, r.height / 2 + dy);436      if (c) this.host.easeTo({ center: c }, dur);437    };438    let handled = true;439    switch (e.key) {440      case 'ArrowLeft':441        if (e.shiftKey) it.rotate && this.host.easeTo({ bearing: cam.bearing - 15 }, dur);442        else panTo(-KEY_PAN_PX, 0);443        break;444      case 'ArrowRight':445        if (e.shiftKey) it.rotate && this.host.easeTo({ bearing: cam.bearing + 15 }, dur);446        else panTo(KEY_PAN_PX, 0);447        break;448      case 'ArrowUp':449        if (e.shiftKey) it.pitch && this.host.easeTo({ pitch: Math.min(72, cam.pitch + 10) }, dur);450        else panTo(0, -KEY_PAN_PX);451        break;452      case 'ArrowDown':453        if (e.shiftKey) it.pitch && this.host.easeTo({ pitch: Math.max(0, cam.pitch - 10) }, dur);454        else panTo(0, KEY_PAN_PX);455        break;456      case '+':457      case '=':458        it.zoom && this.host.easeTo({ zoom: Math.min(20, Math.round(cam.zoom + 1)) }, dur);459        break;460      case '-':461      case '_':462        it.zoom && this.host.easeTo({ zoom: Math.max(0, Math.round(cam.zoom - 1)) }, dur);463        break;464      case '0':465        this.host.easeTo({ bearing: 0, pitch: 0 }, dur);466        break;467      case 'Escape':468        if (this.host.isDrawing()) this.host.cancelDraw();469        else handled = false;470        break;471      case 'Enter':472        if (this.host.isDrawing()) this.host.finishDraw();473        else handled = false;474        break;475      case 'Backspace':476      case 'Delete':477        if (this.host.isDrawing()) this.host.undoDraw();478        else handled = false;479        break;480      default:481        handled = false;482    }483    if (handled) {484      e.preventDefault();485      this.host.announce();486      this.host.requestFrame();487    }488  };489490  destroy(): void {491    clearTimeout(this.wheelEndTimer);492    for (const d of this.disposers) d();493    this.disposers.length = 0;494    this.ptrs.clear();495  }496}497
Files main
Menu

Theme