Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

14.5 KB
Raw Blame
// DOM events: Event, EventTarget and the UI event classes.
//
// Dispatch walks `_eventParent()` from the target up (Node → parent … → Document → window), with the
// capture, target and bubble phases. `on<type>` handler properties are installed per prototype with
// `defineHandlers`, and run in listener order from the moment they are first set (as in browsers).

type Listener = { fn: EventListenerOrEventListenerObject | null; capture: boolean; once: boolean; passive: boolean; removed?: boolean };

export class DOMExceptionImpl extends Error {
  code = 0;
  constructor(message = "", public override name = "Error") { super(message); }
}

export class Event {
  static readonly NONE = 0; static readonly CAPTURING_PHASE = 1; static readonly AT_TARGET = 2; static readonly BUBBLING_PHASE = 3;
  readonly NONE = 0; readonly CAPTURING_PHASE = 1; readonly AT_TARGET = 2; readonly BUBBLING_PHASE = 3;
  readonly type: string;
  readonly bubbles: boolean;
  readonly cancelable: boolean;
  readonly composed: boolean;
  readonly timeStamp = __native.sys.now();
  readonly isTrusted: boolean = false;
  target: any = null;
  currentTarget: any = null;
  eventPhase = 0;
  defaultPrevented = false;
  /** @internal */ _stop = false;
  /** @internal */ _stopNow = false;
  /** @internal */ _passive = false;
  /** @internal */ _path: any[] = [];
  constructor(type: string, init: EventInit = {}) {
    this.type = String(type);
    this.bubbles = !!init.bubbles;
    this.cancelable = !!init.cancelable;
    this.composed = !!init.composed;
  }
  get srcElement() { return this.target; }
  get returnValue() { return !this.defaultPrevented; }
  set returnValue(v: boolean) { if (!v) this.preventDefault(); }
  get cancelBubble() { return this._stop; }
  set cancelBubble(v: boolean) { if (v) this._stop = true; }
  preventDefault() { if (this.cancelable && !this._passive) this.defaultPrevented = true; }
  stopPropagation() { this._stop = true; }
  stopImmediatePropagation() { this._stop = true; this._stopNow = true; }
  composedPath() { return this._path.slice(); }
  initEvent(type: string, bubbles = false, cancelable = false) {
    (this as any).type = type; (this as any).bubbles = bubbles; (this as any).cancelable = cancelable;
  }
}

export class CustomEvent<T = any> extends Event {
  readonly detail: T;
  constructor(type: string, init: CustomEventInit<T> = {}) { super(type, init); this.detail = init.detail as T; }
}

export class UIEvent extends Event {
  readonly view: any; readonly detail: number;
  constructor(type: string, init: UIEventInit = {}) { super(type, init); this.view = init.view ?? null; this.detail = init.detail ?? 0; }
  get which() { return 0; }
}

export class FocusEvent extends UIEvent {
  readonly relatedTarget: any;
  constructor(type: string, init: FocusEventInit = {}) { super(type, init); this.relatedTarget = init.relatedTarget ?? null; }
}

export class MouseEvent extends UIEvent {
  readonly screenX: number; readonly screenY: number; readonly clientX: number; readonly clientY: number;
  readonly ctrlKey: boolean; readonly shiftKey: boolean; readonly altKey: boolean; readonly metaKey: boolean;
  readonly button: number; readonly buttons: number; readonly relatedTarget: any;
  readonly movementX: number; readonly movementY: number;
  offsetX = 0; offsetY = 0;
  constructor(type: string, init: MouseEventInit = {}) {
    super(type, init);
    this.screenX = init.screenX ?? 0; this.screenY = init.screenY ?? 0;
    this.clientX = init.clientX ?? 0; this.clientY = init.clientY ?? 0;
    this.ctrlKey = !!init.ctrlKey; this.shiftKey = !!init.shiftKey; this.altKey = !!init.altKey; this.metaKey = !!init.metaKey;
    this.button = init.button ?? 0; this.buttons = init.buttons ?? 0; this.relatedTarget = init.relatedTarget ?? null;
    this.movementX = init.movementX ?? 0; this.movementY = init.movementY ?? 0;
  }
  get x() { return this.clientX; } get y() { return this.clientY; }
  get pageX() { return this.clientX; } get pageY() { return this.clientY; }
  getModifierState(k: string) { return k === "Shift" ? this.shiftKey : k === "Control" ? this.ctrlKey : k === "Alt" ? this.altKey : k === "Meta" ? this.metaKey : false; }
}

export class PointerEvent extends MouseEvent {
  readonly pointerId: number; readonly pointerType: string; readonly isPrimary: boolean;
  readonly width = 1; readonly height = 1; readonly pressure: number; readonly tiltX = 0; readonly tiltY = 0;
  constructor(type: string, init: PointerEventInit = {}) {
    super(type, init);
    this.pointerId = init.pointerId ?? 1; this.pointerType = init.pointerType ?? "mouse"; this.isPrimary = init.isPrimary ?? true;
    this.pressure = init.pressure ?? (this.buttons ? 0.5 : 0);
  }
}

export class WheelEvent extends MouseEvent {
  static readonly DOM_DELTA_PIXEL = 0; static readonly DOM_DELTA_LINE = 1; static readonly DOM_DELTA_PAGE = 2;
  readonly deltaX: number; readonly deltaY: number; readonly deltaZ: number; readonly deltaMode: number;
  constructor(type: string, init: WheelEventInit = {}) {
    super(type, init);
    this.deltaX = init.deltaX ?? 0; this.deltaY = init.deltaY ?? 0; this.deltaZ = init.deltaZ ?? 0; this.deltaMode = init.deltaMode ?? 0;
  }
}

export class KeyboardEvent extends UIEvent {
  static readonly DOM_KEY_LOCATION_STANDARD = 0;
  readonly key: string; readonly code: string; readonly location: number; readonly repeat: boolean; readonly isComposing: boolean;
  readonly ctrlKey: boolean; readonly shiftKey: boolean; readonly altKey: boolean; readonly metaKey: boolean;
  constructor(type: string, init: KeyboardEventInit = {}) {
    super(type, init);
    this.key = init.key ?? ""; this.code = init.code ?? ""; this.location = init.location ?? 0; this.repeat = !!init.repeat;
    this.isComposing = !!init.isComposing;
    this.ctrlKey = !!init.ctrlKey; this.shiftKey = !!init.shiftKey; this.altKey = !!init.altKey; this.metaKey = !!init.metaKey;
  }
  get keyCode() { return legacyKeyCode(this.key, this.code); }
  get which() { return this.keyCode; }
  get charCode() { return this.type === "keypress" && this.key.length === 1 ? this.key.charCodeAt(0) : 0; }
  getModifierState(k: string) { return k === "Shift" ? this.shiftKey : k === "Control" ? this.ctrlKey : k === "Alt" ? this.altKey : k === "Meta" ? this.metaKey : false; }
}

export class InputEvent extends UIEvent {
  readonly data: string | null; readonly inputType: string; readonly isComposing: boolean;
  constructor(type: string, init: InputEventInit = {}) {
    super(type, init);
    this.data = init.data ?? null; this.inputType = init.inputType ?? ""; this.isComposing = !!init.isComposing;
  }
}

export class CompositionEvent extends UIEvent {
  readonly data: string;
  constructor(type: string, init: CompositionEventInit = {}) { super(type, init); this.data = init.data ?? ""; }
}

export class SubmitEvent extends Event {
  readonly submitter: any;
  constructor(type: string, init: SubmitEventInit = {}) { super(type, init); this.submitter = init.submitter ?? null; }
}

export class ErrorEvent extends Event {
  readonly message: string; readonly error: any; readonly filename = ""; readonly lineno = 0; readonly colno = 0;
  constructor(type: string, init: ErrorEventInit = {}) { super(type, init); this.message = init.message ?? ""; this.error = init.error; }
}

export class MessageEvent<T = any> extends Event {
  readonly data: T; readonly origin: string; readonly lastEventId = ""; readonly source = null; readonly ports = [];
  constructor(type: string, init: MessageEventInit<T> = {}) { super(type, init); this.data = init.data as T; this.origin = init.origin ?? ""; }
}

export class CloseEvent extends Event {
  readonly code: number; readonly reason: string; readonly wasClean: boolean;
  constructor(type: string, init: CloseEventInit = {}) { super(type, init); this.code = init.code ?? 0; this.reason = init.reason ?? ""; this.wasClean = !!init.wasClean; }
}

export class ProgressEvent extends Event {
  readonly lengthComputable: boolean; readonly loaded: number; readonly total: number;
  constructor(type: string, init: ProgressEventInit = {}) { super(type, init); this.lengthComputable = !!init.lengthComputable; this.loaded = init.loaded ?? 0; this.total = init.total ?? 0; }
}

const LISTENERS = Symbol("listeners");
const HANDLERS = Symbol("handlers");

export class EventTarget {
  /** @internal */ [LISTENERS]?: Map<string, Listener[]>;
  /** @internal */ [HANDLERS]?: Map<string, { value: any; wrapper: Listener }>;

  /** The next target up the propagation path (overridden by Node and Document). */
  _eventParent(_e: Event): EventTarget | null { return null; }

  addEventListener(type: string, fn: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) {
    if (!fn) return;
    const capture = typeof options === "boolean" ? options : !!options?.capture;
    const once = typeof options === "object" && !!options?.once;
    const passive = typeof options === "object" && !!options?.passive;
    const signal = typeof options === "object" ? options?.signal : undefined;
    if (signal?.aborted) return;
    const map: Map<string, Listener[]> = (this[LISTENERS] ??= new Map());
    let list = map.get(type);
    if (!list) { list = []; map.set(type, list); }
    if (list.some((l) => l.fn === fn && l.capture === capture)) return;
    const entry: Listener = { fn, capture, once, passive };
    list.push(entry);
    listenerAdded(this, type);
    signal?.addEventListener("abort", () => this.removeEventListener(type, fn, { capture }));
  }

  removeEventListener(type: string, fn: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) {
    const capture = typeof options === "boolean" ? options : !!options?.capture;
    const list = this[LISTENERS]?.get(type);
    if (!list) return;
    const i = list.findIndex((l) => l.fn === fn && l.capture === capture);
    if (i >= 0) { list[i].removed = true; list.splice(i, 1); }
  }

  dispatchEvent(event: Event): boolean {
    const path: EventTarget[] = [];
    for (let t: EventTarget | null = this; t; t = t._eventParent(event)) path.push(t);
    event.target = this;
    event._path = path;
    event._stop = false; event._stopNow = false;
    for (let i = path.length - 1; i >= 1 && !event._stop; i--) invoke(path[i], event, Event.CAPTURING_PHASE);
    if (!event._stop) invoke(this, event, Event.AT_TARGET);
    if (event.bubbles) for (let i = 1; i < path.length && !event._stop; i++) invoke(path[i], event, Event.BUBBLING_PHASE);
    event.eventPhase = 0;
    event.currentTarget = null;
    return !event.defaultPrevented;
  }

  /** @internal does anyone listen for `type` here (listeners or an on-handler)? */
  _hasListener(type: string) { return !!this[LISTENERS]?.get(type)?.length; }
}

/** Hook for the UI engine: it only forwards high-frequency events (mousemove …) once someone listens. */
export let listenerAdded: (target: EventTarget, type: string) => void = () => {};
export function onListenerAdded(f: (target: EventTarget, type: string) => void) { listenerAdded = f; }

function invoke(target: EventTarget, event: Event, phase: number) {
  const list = target[LISTENERS]?.get(event.type);
  if (!list || !list.length) return;
  event.currentTarget = target;
  event.eventPhase = phase;
  for (const l of list.slice()) {
    if (l.removed) continue;
    if (phase === Event.CAPTURING_PHASE && !l.capture) continue;
    if (phase === Event.BUBBLING_PHASE && l.capture) continue;
    if (l.once) target.removeEventListener(event.type, l.fn, { capture: l.capture });
    event._passive = l.passive;
    try {
      const fn = l.fn as any;
      if (typeof fn === "function") fn.call(target, event);
      else if (fn && typeof fn.handleEvent === "function") fn.handleEvent(event);
    } catch (e) {
      reportError(e);
    }
    event._passive = false;
    if (event._stopNow) break;
  }
}

export function reportError(e: unknown) {
  const err = e as any;
  try { console.error(err?.stack ? `${err.message}\n${err.stack}` : String(err)); } catch { /* */ }
  try {
    const g = globalThis as any;
    if (typeof g.onerror === "function") g.onerror(String(err?.message ?? err), "", 0, 0, err);
  } catch { /* */ }
}

/** Define `on<type>` handler properties on a prototype. */
export function defineHandlers(proto: object, types: string[]) {
  for (const type of types) {
    Object.defineProperty(proto, "on" + type, {
      configurable: true,
      enumerable: true,
      get(this: EventTarget) { return this[HANDLERS]?.get(type)?.value ?? null; },
      set(this: EventTarget, value: any) {
        const handlers = (this[HANDLERS] ??= new Map());
        const existing = handlers.get(type);
        const fn = typeof value === "function" ? value : null;
        if (existing) {
          existing.value = fn;
          if (!fn) { this.removeEventListener(type, existing.wrapper.fn); handlers.delete(type); }
          return;
        }
        if (!fn) return;
        const self = this;
        const wrapper: Listener = {
          fn: function (this: any, e: Event) {
            const h = self[HANDLERS]?.get(type)?.value;
            if (!h) return;
            const r = h.call(self, e);
            if (r === false && type !== "mouseover" && type !== "error") e.preventDefault();
          } as any,
          capture: false, once: false, passive: false,
        };
        handlers.set(type, { value: fn, wrapper });
        this.addEventListener(type, wrapper.fn);
      },
    });
  }
}

export const HANDLER_TYPES = [
  "abort", "blur", "cancel", "change", "click", "close", "contextmenu", "dblclick", "error", "focus", "focusin", "focusout",
  "input", "invalid", "keydown", "keypress", "keyup", "load", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout",
  "mouseover", "mouseup", "pointerdown", "pointermove", "pointerup", "pointercancel", "pointerenter", "pointerleave", "pointerover",
  "pointerout", "reset", "resize", "scroll", "select", "submit", "toggle", "wheel", "animationend", "transitionend",
  "compositionstart", "compositionupdate", "compositionend", "beforeinput",
];

const KEYCODES: Record<string, number> = {
  Backspace: 8, Tab: 9, Enter: 13, Shift: 16, Control: 17, Alt: 18, Pause: 19, CapsLock: 20, Escape: 27, " ": 32,
  PageUp: 33, PageDown: 34, End: 35, Home: 36, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Delete: 46, Meta: 91,
  F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123,
};
function legacyKeyCode(key: string, code: string) {
  if (KEYCODES[key] !== undefined) return KEYCODES[key];
  if (/^Key[A-Z]$/.test(code)) return code.charCodeAt(3);
  if (/^Digit[0-9]$/.test(code)) return code.charCodeAt(5);
  if (key.length === 1) return key.toUpperCase().charCodeAt(0);
  return 0;
}