SPB Git

Repository Public

input.ts 18.1 KB 332 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : apps/navigator-web/src/viewer/input.ts9 * Module           : viewer10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@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// Pointer, wheel, keyboard and touch capture for the remote view.43// Privacy rule for this file: nothing typed is ever logged, stored or echoed. Key events and composed text go44// straight to the socket; the hidden text area that receives on-screen keyboard input is emptied after every event.45import type { ViewerMsg } from '../types.ts';4647export type View = { z: number; tx: number; ty: number };48export const IDENTITY: View = { z: 1, tx: 0, ty: 0 };49export interface InputOptions {50  send(m: ViewerMsg): void;51  /** True only while this viewer holds the control lease on an open socket. */52  canControl(): boolean;53  /** Size of the remote viewport in CSS pixels (frame header), null before the first frame. */54  frame(): { w: number; h: number } | null;55  clipboardAllowed(): boolean;56  onClipboardBlocked(): void;57  /** The user tried to act on the page without control. */58  onDenied(): void;59  onView(v: View): void;60  onKeyboardFocus(focused: boolean): void;61  /** Ctrl+Alt+Escape: give the keyboard back to the local page. */62  onExitKeyboard(): void;63}6465const BUTTONS = ['left', 'middle', 'right'] as const;66type Mods = { altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean };67const modsOf = (e: Mods) => (e.altKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.metaKey ? 4 : 0) | (e.shiftKey ? 8 : 0);68const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));69const MAX_ZOOM = 5;7071export class InputController {72  private stage!: HTMLElement; private canvas!: HTMLCanvasElement; private ta!: HTMLTextAreaElement;73  private off: Array<() => void> = [];74  private view: View = IDENTITY;75  private raf = 0;76  private pendingMove: { x: number; y: number; mods: number; button: 'left' | 'middle' | 'right' | 'none' } | null = null;77  private pendingWheel: { x: number; y: number; dx: number; dy: number; mods: number } | null = null;78  private pendingTouch: { x: number; y: number } | null = null;79  private click = { t: 0, x: 0, y: 0, button: -1, count: 0 };80  private buttonsDown = new Set<number>();81  private keysDown = new Map<string, string>();82  private touches = new Map<number, { x: number; y: number }>();83  private remoteTouch: number | null = null;84  private pinch: { d0: number; z0: number; qx: number; qy: number } | null = null;85  private pan: { x: number; y: number; tx: number; ty: number } | null = null;86  private composing = false;87  private lastNamedKey = 0;88  private deniedAt = 0;89  /** Primary input is a finger: printable characters come from the on-screen keyboard as text, not as key events. */90  private soft = window.matchMedia('(pointer: coarse)').matches;9192  constructor(private readonly o: InputOptions) {}9394  attach(stage: HTMLElement, canvas: HTMLCanvasElement, textarea: HTMLTextAreaElement) {95    this.stage = stage; this.canvas = canvas; this.ta = textarea;96    const on = <K extends keyof HTMLElementEventMap>(el: HTMLElement | Window, type: K, fn: (e: HTMLElementEventMap[K]) => void, opts?: AddEventListenerOptions) => {97      el.addEventListener(type, fn as EventListener, opts); this.off.push(() => el.removeEventListener(type, fn as EventListener, opts));98    };99    on(stage, 'pointerdown', this.onPointerDown);100    on(stage, 'pointermove', this.onPointerMove);101    on(stage, 'pointerup', this.onPointerUp);102    on(stage, 'pointercancel', this.onPointerUp);103    on(stage, 'wheel', this.onWheel, { passive: false });104    on(stage, 'contextmenu', (e) => e.preventDefault());105    on(stage, 'dragstart', (e) => e.preventDefault());106    on(stage, 'mousedown', (e) => { if (e.button === 1) e.preventDefault(); }); // no local autoscroll on middle click107    on(stage, 'auxclick', (e) => e.preventDefault());108    on(textarea, 'keydown', this.onKeyDown);109    on(textarea, 'keyup', this.onKeyUp);110    on(textarea, 'beforeinput', this.onBeforeInput);111    on(textarea, 'input', this.onInput);112    on(textarea, 'compositionstart', () => { this.composing = true; });113    on(textarea, 'compositionend', () => { this.composing = false; window.setTimeout(this.flushText, 0); });114    on(textarea, 'paste', (e) => { if (!this.o.clipboardAllowed()) { e.preventDefault(); this.o.onClipboardBlocked(); } });115    on(textarea, 'copy', (e) => e.preventDefault());116    on(textarea, 'cut', (e) => e.preventDefault());117    on(textarea, 'drop', (e) => e.preventDefault());118    on(textarea, 'focus', () => this.o.onKeyboardFocus(true));119    on(textarea, 'blur', () => { this.releaseKeys(); this.ta.value = ''; this.composing = false; this.o.onKeyboardFocus(false); });120    on(window, 'blur', () => this.releaseKeys());121  }122  detach() { for (const f of this.off) f(); this.off = []; cancelAnimationFrame(this.raf); this.raf = 0; }123124  focusKeyboard() { this.ta.focus({ preventScroll: true }); }125  blurKeyboard() { this.ta.blur(); }126  resetView() { this.setView(IDENTITY); }127  /** Control was lost: forget everything in flight without sending anything more. */128  dropAll() {129    this.pendingMove = null; this.pendingWheel = null; this.pendingTouch = null;130    this.buttonsDown.clear(); this.keysDown.clear(); this.remoteTouch = null;131    if (this.ta) this.ta.value = '';132  }133134  /* ── Coordinates: client pixels → remote viewport CSS pixels (letterbox and local zoom included) ── */135  private map(clientX: number, clientY: number, clampInside: boolean): { x: number; y: number } | null {136    const f = this.o.frame(); if (!f) return null;137    const r = this.canvas.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) return null;138    const x = ((clientX - r.left) / r.width) * f.w, y = ((clientY - r.top) / r.height) * f.h;139    if (!clampInside && (x < 0 || y < 0 || x >= f.w || y >= f.h)) return null;140    return { x: Math.round(clamp(x, 0, f.w - 1) * 10) / 10, y: Math.round(clamp(y, 0, f.h - 1) * 10) / 10 };141  }142  private denied() { const now = performance.now(); if (now - this.deniedAt > 1500) { this.deniedAt = now; this.o.onDenied(); } }143  private schedule() { if (!this.raf) this.raf = requestAnimationFrame(this.flush); }144  /** At most one move, one wheel and one touch-move per animation frame (~60/s). */145  private flush = () => {146    this.raf = 0;147    const mv = this.pendingMove, wh = this.pendingWheel, tc = this.pendingTouch;148    this.pendingMove = null; this.pendingWheel = null; this.pendingTouch = null;149    if (!this.o.canControl()) return;150    if (mv) this.o.send({ t: 'mouse', type: 'move', x: mv.x, y: mv.y, button: mv.button, dx: 0, dy: 0, clicks: 0, mods: mv.mods });151    if (wh) this.o.send({ t: 'mouse', type: 'wheel', x: wh.x, y: wh.y, button: 'none', dx: clamp(Math.round(wh.dx), -5000, 5000), dy: clamp(Math.round(wh.dy), -5000, 5000), clicks: 0, mods: wh.mods });152    if (tc && this.remoteTouch !== null) this.o.send({ t: 'touch', type: 'move', points: [{ x: tc.x, y: tc.y, id: 0 }] });153  };154  private flushNow() { if (this.raf) { cancelAnimationFrame(this.raf); this.flush(); } }155156  /* ── Mouse / pen ── */157  private onPointerDown = (e: PointerEvent) => {158    if (e.pointerType === 'touch') return this.touchDown(e);159    e.preventDefault();160    this.focusKeyboard();161    const p = this.map(e.clientX, e.clientY, false);162    if (!p || e.button < 0 || e.button > 2) return;163    if (!this.o.canControl()) return this.denied();164    try { this.stage.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }165    const now = performance.now(), c = this.click;166    const again = c.button === e.button && now - c.t < 450 && Math.abs(c.x - e.clientX) < 6 && Math.abs(c.y - e.clientY) < 6;167    this.click = { t: now, x: e.clientX, y: e.clientY, button: e.button, count: again ? (c.count % 3) + 1 : 1 };168    this.flushNow();169    this.buttonsDown.add(e.button);170    this.o.send({ t: 'mouse', type: 'down', x: p.x, y: p.y, button: BUTTONS[e.button]!, dx: 0, dy: 0, clicks: this.click.count, mods: modsOf(e) });171  };172  private onPointerMove = (e: PointerEvent) => {173    if (e.pointerType === 'touch') return this.touchMove(e);174    if (!this.o.canControl()) return;175    const p = this.map(e.clientX, e.clientY, this.buttonsDown.size > 0); if (!p) return;176    this.pendingMove = { ...p, mods: modsOf(e), button: e.buttons & 1 ? 'left' : e.buttons & 2 ? 'right' : e.buttons & 4 ? 'middle' : 'none' };177    this.schedule();178  };179  private onPointerUp = (e: PointerEvent) => {180    if (e.pointerType === 'touch') return this.touchUp(e);181    const released = e.type === 'pointercancel' ? [...this.buttonsDown] : this.buttonsDown.has(e.button) ? [e.button] : [];182    if (!released.length) return;183    this.flushNow();184    const p = this.map(e.clientX, e.clientY, true);185    for (const b of released) {186      this.buttonsDown.delete(b);187      if (p && this.o.canControl()) this.o.send({ t: 'mouse', type: 'up', x: p.x, y: p.y, button: BUTTONS[b]!, dx: 0, dy: 0, clicks: this.click.count, mods: modsOf(e) });188    }189  };190  private onWheel = (e: WheelEvent) => {191    if (!this.o.canControl()) return;192    const p = this.map(e.clientX, e.clientY, false); if (!p) return;193    e.preventDefault();194    const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? (this.o.frame()?.h ?? 800) : 1;195    const w = this.pendingWheel;196    this.pendingWheel = { x: p.x, y: p.y, dx: (w?.dx ?? 0) + e.deltaX * unit, dy: (w?.dy ?? 0) + e.deltaY * unit, mods: modsOf(e) };197    this.schedule();198  };199200  /* ── Touch: one finger goes to the remote page, two fingers zoom and pan the local view ── */201  private touchDown(e: PointerEvent) {202    e.preventDefault();203    this.touches.set(e.pointerId, { x: e.clientX, y: e.clientY });204    try { this.stage.setPointerCapture(e.pointerId); } catch { /* */ }205    if (this.touches.size === 1) {206      this.pan = null;207      const p = this.map(e.clientX, e.clientY, false);208      if (this.o.canControl()) { if (p) { this.remoteTouch = e.pointerId; this.o.send({ t: 'touch', type: 'start', points: [{ x: p.x, y: p.y, id: 0 }] }); } }209      else { if (p) this.denied(); this.pan = { x: e.clientX, y: e.clientY, tx: this.view.tx, ty: this.view.ty }; }210    } else if (this.touches.size === 2) {211      if (this.remoteTouch !== null) { this.pendingTouch = null; if (this.o.canControl()) this.o.send({ t: 'touch', type: 'cancel', points: [] }); this.remoteTouch = null; }212      this.pan = null;213      const [a, b] = [...this.touches.values()] as [{ x: number; y: number }, { x: number; y: number }];214      const c = this.center();215      const cx = (a.x + b.x) / 2, cy = (a.y + b.y) / 2;216      this.pinch = { d0: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)), z0: this.view.z, qx: (cx - c.x - this.view.tx) / this.view.z, qy: (cy - c.y - this.view.ty) / this.view.z };217    }218  }219  private touchMove(e: PointerEvent) {220    const t = this.touches.get(e.pointerId); if (!t) return;221    t.x = e.clientX; t.y = e.clientY;222    if (this.pinch && this.touches.size >= 2) {223      const [a, b] = [...this.touches.values()] as [{ x: number; y: number }, { x: number; y: number }];224      const c = this.center();225      const z = clamp(this.pinch.z0 * (Math.hypot(a.x - b.x, a.y - b.y) / this.pinch.d0), 1, MAX_ZOOM);226      this.setView({ z, tx: (a.x + b.x) / 2 - c.x - z * this.pinch.qx, ty: (a.y + b.y) / 2 - c.y - z * this.pinch.qy });227    } else if (this.remoteTouch === e.pointerId) {228      const p = this.map(e.clientX, e.clientY, true);229      if (p && this.o.canControl()) { this.pendingTouch = p; this.schedule(); }230    } else if (this.pan && this.touches.size === 1) {231      this.setView({ z: this.view.z, tx: this.pan.tx + e.clientX - this.pan.x, ty: this.pan.ty + e.clientY - this.pan.y });232    }233  }234  private touchUp(e: PointerEvent) {235    if (!this.touches.delete(e.pointerId)) return;236    if (this.remoteTouch === e.pointerId) {237      this.flushNow();238      const p = this.map(e.clientX, e.clientY, true);239      if (this.o.canControl()) this.o.send({ t: 'touch', type: e.type === 'pointercancel' ? 'cancel' : 'end', points: p ? [{ x: p.x, y: p.y, id: 0 }] : [] });240      this.remoteTouch = null;241    }242    if (this.touches.size < 2 && this.pinch) {243      this.pinch = null;244      // The finger that stays down after a pinch keeps panning the local view; it never turns into a remote touch.245      const rest = [...this.touches.values()][0];246      this.pan = rest ? { x: rest.x, y: rest.y, tx: this.view.tx, ty: this.view.ty } : null;247    }248    if (this.touches.size === 0) this.pan = null;249  }250  private center() { const r = this.stage.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }251  private setView(v: View) {252    let { z, tx, ty } = v;253    z = clamp(z, 1, MAX_ZOOM);254    if (z <= 1.001) { z = 1; tx = 0; ty = 0; }255    else {256      const mx = Math.max(0, (this.canvas.offsetWidth * z - this.stage.clientWidth) / 2), my = Math.max(0, (this.canvas.offsetHeight * z - this.stage.clientHeight) / 2);257      tx = clamp(tx, -mx, mx); ty = clamp(ty, -my, my);258    }259    this.view = { z, tx, ty };260    this.o.onView(this.view);261  }262263  /* ── Keyboard. The focus target is a visually hidden text area so dead keys, IME and on-screen keyboards work. ── */264  private isClipboardShortcut(e: KeyboardEvent) {265    const k = e.key.toLowerCase();266    return ((e.ctrlKey || e.metaKey) && (k === 'v' || k === 'c' || k === 'x')) || (k === 'insert' && (e.shiftKey || e.ctrlKey)) || k === 'paste' || k === 'copy' || k === 'cut';267  }268  private onKeyDown = (e: KeyboardEvent) => {269    if (e.ctrlKey && e.altKey && e.key === 'Escape') { e.preventDefault(); this.releaseKeys(); this.o.onExitKeyboard(); return; }270    if (!this.o.canControl()) return; // read-only: the local browser keeps its normal keyboard behaviour (Tab leaves the view)271    // Composition in progress (dead key, IME, some on-screen keyboards): the composed text arrives through `input`.272    if (e.isComposing || this.composing || e.key === 'Process' || e.key === 'Dead' || e.key === 'Unidentified' || e.keyCode === 229) return;273    if (this.isClipboardShortcut(e)) {274      e.preventDefault();275      if (!this.o.clipboardAllowed()) { this.o.onClipboardBlocked(); return; }276    }277    const printable = [...e.key].length === 1 && !e.ctrlKey && !e.metaKey;278    if (printable && this.soft) return;279    if (e.key.length > 32 || e.code.length > 32) return;280    e.preventDefault();281    if (e.key === 'Backspace' || e.key === 'Enter') this.lastNamedKey = performance.now();282    this.keysDown.set(e.code || e.key, e.key);283    this.o.send({ t: 'key', type: 'down', key: e.key, code: e.code, mods: modsOf(e) });284  };285  private onKeyUp = (e: KeyboardEvent) => {286    const id = e.code || e.key;287    if (!this.keysDown.has(id)) return;288    e.preventDefault();289    this.keysDown.delete(id);290    if (this.o.canControl()) this.o.send({ t: 'key', type: 'up', key: e.key, code: e.code, mods: modsOf(e) });291    // macOS never delivers keyup for keys released while Command is held: release them with it.292    if (e.key === 'Meta') this.releaseKeys();293  };294  private releaseKeys() {295    if (!this.keysDown.size) return;296    const can = this.o.canControl();297    for (const [code, key] of this.keysDown) if (can) this.o.send({ t: 'key', type: 'up', key, code: code === key ? '' : code, mods: 0 });298    this.keysDown.clear();299  }300  private tap(key: string) {301    this.o.send({ t: 'key', type: 'down', key, code: key, mods: 0 });302    this.o.send({ t: 'key', type: 'up', key, code: key, mods: 0 });303  }304  private onBeforeInput = (e: InputEvent) => {305    const ty = e.inputType ?? '';306    if (ty === 'insertFromPaste' || ty === 'insertFromDrop' || ty === 'insertFromYank') {307      if (!this.o.clipboardAllowed()) { e.preventDefault(); this.o.onClipboardBlocked(); }308      return;309    }310    if (e.isComposing || this.composing || !this.o.canControl()) return;311    // Keyboards that send no usable keydown (code 229) still announce deletions and line breaks here.312    const dup = performance.now() - this.lastNamedKey < 80;313    if (ty.startsWith('delete')) { e.preventDefault(); if (!dup) this.tap(ty === 'deleteContentForward' ? 'Delete' : 'Backspace'); }314    else if (ty === 'insertLineBreak' || ty === 'insertParagraph') { e.preventDefault(); if (!dup) this.tap('Enter'); }315  };316  private onInput = (e: Event) => { if (this.composing || (e as InputEvent).isComposing) return; this.flushText(); };317  /** Sends what the keyboard composed, then empties the field. Nothing is kept. */318  private flushText = () => {319    if (this.composing) return;320    const v = this.ta.value;321    this.ta.value = '';322    if (!v || !this.o.canControl()) return;323    let chunk = '';324    for (const ch of v) { // by code point: a surrogate pair is never split across two messages325      if (ch === '\n' || ch === '\r') { if (chunk) { this.o.send({ t: 'text', text: chunk }); chunk = ''; } if (ch === '\n') this.tap('Enter'); continue; }326      if (chunk.length + ch.length > 200) { this.o.send({ t: 'text', text: chunk }); chunk = ''; }327      chunk += ch;328    }329    if (chunk) this.o.send({ t: 'text', text: chunk });330  };331}332
Files main
Menu

Theme