All files / player-browser/src/session session-scene.ts

84.39% Statements 119/141
85.32% Branches 93/109
92.3% Functions 24/26
88.88% Lines 104/117

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331                                                                                                                          3x       34x         22x 7x 7x 6x 22x 5x                                       27x 27x                                       20x                                             85x         85x               85x 85x 85x 85x 85x   85x       85x 85x 85x       19x       2x         8x         3x         2x       8x               53x 52x 51x 51x 51x 51x     2x 2x   49x 49x 49x 49x 53x 53x 53x 53x         84x 2x 2x 2x   82x 41x 41x 41x 84x 84x 84x 84x 84x 84x               3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x                     3x 3x 3x 3x         73x 72x 72x 72x 72x 72x             93x 93x 93x 93x 92x       3x 3x 3x       12x 12x 11x     21x 21x     1x 1x     3x 3x   3x 2x       22x 22x   18x 22x 17x      
/**
 * The scene every screen runs as: a **scene session** (the screen's behaviour, family-neutral) with the **family view**
 * that draws it (ADR 0001). `SessionScene` is the `PixiScene` the host mounts. It owns the parts every screen shares:
 * the ticker that asks the session for a frame and has the view draw it, the key listener that hands keys to the
 * session, and the view's intents routed to the session.
 *
 * Lifecycle (the host's `setScene`): `enter(host)` attaches the view and starts the session, `exit()` detaches both but
 * keeps them for the next `enter` (the select screen is kept through a play), and `dispose()` ends the scene.
 *
 * Sessions use Pixi only for types (`vite.config.ts` lints `session/**`), so a session runs in Node tests against a
 * fake view.
 */
 
import type { Container } from 'pixi.js';
import type { SceneIdentity } from '../host/family-kit.ts';
import type { PixiScene, PixiSceneHost } from '../host/scene-host.ts';
import type { FamilyView, IntentSink } from '../view/types.ts';
 
export type { SceneSession, SessionKeyEvent } from './contracts.ts';
import type { SceneSession, SessionKeyEvent } from './contracts.ts';
import { SceneController } from './controller.ts';
import {
  controlButtonsOfKey,
  DEFAULT_CONTROL_BUTTONS,
  resolveControlButtons,
  type ControlButtonMap,
  type ControlButton,
  type ControlSettings,
} from './controls/control-buttons.ts';
import {
  createGamepadMenuInput,
  GAMEPAD_MENU_ARROW_CODES,
  type GamepadMenuEvent,
  type GamepadMenuInput,
} from '../runtime/gamepad-menu.ts';
 
/** Where the scene listens for keys: `window` in a browser. */
export interface SessionKeyTarget {
  addEventListener(type: 'keydown' | 'keyup', listener: (event: KeyboardEvent) => void): void;
  removeEventListener(type: 'keydown' | 'keyup', listener: (event: KeyboardEvent) => void): void;
}
 
export interface SessionSceneOptions {
  /** Where keys are listened for. Defaults to `window`; without one (Node) the scene gets no keys. */
  readonly keyTarget?: SessionKeyTarget;
  /** The clock frames are drawn on, in ms. Defaults to `performance.now()`. */
  readonly now?: () => number;
  /** The player's keys the screen reads its control buttons by (`SessionKeyEvent.buttons`); the defaults without. */
  readonly controls?: ControlSettings;
  /**
   * The gamepads the screen reads as its control buttons (`runtime/gamepad-menu.ts`), or `false` for none. Every scene
   * but the play reads them by default; the play reads its pads through the engine's input runtime.
   */
  readonly gamepad?: GamepadMenuInput | false;
  /** Whether a pad press is someone else's (a dialog over the stage); a modal dialog's or a text field's by default. */
  readonly shouldSkipGamepad?: () => boolean;
}
 
type SceneState = 'idle' | 'attaching' | 'entered' | 'disposed';
 
function defaultKeyTarget(): SessionKeyTarget | undefined {
  return typeof window === 'undefined' ? undefined : window;
}
 
function defaultNow(): number {
  return performance.now();
}
 
/** A key typed into a text field (the host's search box, a dialog) is the field's, not the scene's. */
function isEditableKeyTarget(target: EventTarget | null): boolean {
  if (target === null || typeof target !== 'object') return false;
  const element = target as { tagName?: unknown; isContentEditable?: unknown; type?: unknown };
  if (element.isContentEditable === true) return true;
  const tag = typeof element.tagName === 'string' ? element.tagName : '';
  if (tag === 'TEXTAREA' || tag === 'SELECT') return true;
  return tag === 'INPUT' && !['checkbox', 'radio', 'button', 'range'].includes(String(element.type));
}
 
/** A modal dialog or a focused text field takes the pads from the stage, as it takes the keys. */
function defaultShouldSkipGamepad(): boolean {
  if (typeof document === 'undefined') return false;
  if (isEditableKeyTarget(document.activeElement)) return true;
  try {
    return document.querySelector('dialog:modal') !== null;
  } catch {
    return document.querySelector('dialog[open]') !== null;
  }
}
 
/**
 * A pad press as the key event a screen reads: a key, turntable key, START or SELECT as its control button (with a code
 * no keyboard key has), a D-pad direction as its arrow key.
 */
export function gamepadSessionKeyEvent(event: GamepadMenuEvent): SessionKeyEvent {
  const arrow = GAMEPAD_MENU_ARROW_CODES[event.button];
  const buttons: ControlButton[] = arrow === undefined ? [`${event.side}-${event.button}` as ControlButton] : [];
  return {
    type: event.type,
    buttons,
    code: arrow ?? `Gamepad${event.side}-${event.button}`,
    key: arrow ?? '',
    repeat: event.repeat,
    timeStamp: event.timeStamp,
    shiftKey: false,
    ctrlKey: false,
    altKey: false,
    metaKey: false,
  };
}
 
/** The plain-data form of a DOM key event. */
export function toSessionKeyEvent(
  type: SessionKeyEvent['type'],
  event: KeyboardEvent,
  buttons: ControlButtonMap = DEFAULT_CONTROL_BUTTONS,
): SessionKeyEvent {
  return {
    type,
    buttons: controlButtonsOfKey(event, buttons),
    code: event.code,
    key: event.key,
    repeat: event.repeat,
    timeStamp: event.timeStamp,
    shiftKey: event.shiftKey,
    ctrlKey: event.ctrlKey,
    altKey: event.altKey,
    metaKey: event.metaKey,
  };
}
 
/** A `PixiScene` made of a scene session and the family view that draws it. See the module comment. */
export class SessionScene<Frame, Intent> implements PixiScene {
  private readonly sceneIdentity: { kind: SceneIdentity['kind']; family: SceneIdentity['family'] };
  /** The view's screenshot descriptor, when it has one. */
  private stageInfo: (() => { container: Container; width: number; height: number }) | undefined;
  public readonly controller: SceneController<Frame, Intent>;
  private view: FamilyView<Frame, Intent>;
  private readonly keyTarget: SessionKeyTarget | undefined;
  private readonly now: () => number;
  private state: SceneState = 'idle';
  private readonly controlButtons: ControlButtonMap;
  private readonly gamepad: GamepadMenuInput | undefined;
  private readonly shouldSkipGamepad: () => boolean;
  /** Bumped by every `exit` / `dispose`, so an `enter` still waiting on the view's `attach` knows it was overtaken. */
  private generation = 0;
  private host: PixiSceneHost | undefined;
 
  public constructor(
    session: SceneSession<Frame, Intent>,
    view: FamilyView<Frame, Intent>,
    options: SessionSceneOptions = {},
  ) {
    this.controller = new SceneController(session);
    this.view = view;
    this.keyTarget = options.keyTarget ?? defaultKeyTarget();
    this.now = options.now ?? defaultNow;
    this.controlButtons =
      options.controls === undefined ? DEFAULT_CONTROL_BUTTONS : resolveControlButtons(options.controls);
    this.gamepad =
      options.gamepad === false || (options.gamepad === undefined && session.kind === 'play')
        ? undefined
        : (options.gamepad ?? (this.keyTarget === undefined ? undefined : createGamepadMenuInput()));
    this.shouldSkipGamepad = options.shouldSkipGamepad ?? defaultShouldSkipGamepad;
    this.sceneIdentity = { kind: session.kind, family: view.family };
    this.stageInfo = view.getStageInfo !== undefined ? () => view.getStageInfo!() : undefined;
  }
 
  public get identity(): SceneIdentity {
    return this.sceneIdentity;
  }
 
  public get getStageInfo(): (() => { container: Container; width: number; height: number }) | undefined {
    return this.stageInfo;
  }
 
  /** The view's scene graph, which the host puts on the stage. */
  public get root(): Container {
    return this.view.root;
  }
 
  /** Whether the view draws on the Pixi canvas; the host takes the canvas out while it does not. */
  public get drawsOnCanvas(): boolean {
    return this.view.drawsOnCanvas !== false;
  }
 
  /** Whether the scene is on the stage: attached, ticking and listening. */
  public get entered(): boolean {
    return this.state === 'entered';
  }
 
  public get disposed(): boolean {
    return this.state === 'disposed';
  }
 
  /**
   * Attaches the view, starts the session, then listens for keys and ticks; the first frame is drawn before this
   * resolves, so the stage never shows an empty scene. Entering a scene already entered does nothing.
   */
  public async enter(host: PixiSceneHost): Promise<void> {
    if (this.state === 'disposed') throw new Error('SessionScene: entered after dispose');
    if (this.state !== 'idle') return;
    this.state = 'attaching';
    const generation = this.generation;
    await this.view.attach(host, this.emit);
    if (generation !== this.generation) {
      // Left while the view was attaching: undo the attach, unless the scene ended (the view is disposed) or a newer
      // `enter` is attaching it again.
      if ((this.state as SceneState) === 'idle') this.view.detach();
      return;
    }
    this.state = 'entered';
    this.host = host;
    this.controller.enter(this.now());
    this.keyTarget?.addEventListener('keydown', this.onKeyDown);
    this.keyTarget?.addEventListener('keyup', this.onKeyUp);
    this.gamepad?.start(this.onGamepad);
    host.app.ticker.add(this.tick);
    this.tick();
  }
 
  /** Stops ticking and listening and detaches the view and the session, keeping both for the next `enter`. */
  public exit(): void {
    if (this.state === 'attaching') {
      this.generation += 1;
      this.state = 'idle';
      return;
    }
    if (this.state !== 'entered') return;
    this.generation += 1;
    this.state = 'idle';
    this.host?.app.ticker.remove(this.tick);
    this.host = undefined;
    this.keyTarget?.removeEventListener('keydown', this.onKeyDown);
    this.keyTarget?.removeEventListener('keyup', this.onKeyUp);
    this.gamepad?.stop();
    this.view.detach();
    this.controller.exit();
  }
 
  /**
   * Draws with `next` from here on. The session stays. While the scene is on the stage, the previous view is detached
   * and `next` is attached in its place. The caller disposes the previous view once this resolves `true`.
   */
  public async replaceView(next: FamilyView<Frame, Intent>): Promise<boolean> {
    Iif (this.state === 'disposed' || this.state === 'attaching') return false;
    const previous = this.view;
    Iif (previous === next) return true;
    const host = this.host;
    const entered = this.state === 'entered';
    Eif (entered) {
      previous.detach();
      previous.root.parent?.removeChild(previous.root);
    }
    this.installView(next);
    Iif (!entered || host === undefined) return true;
    try {
      await next.attach(host, this.emit);
    } catch (error) {
      next.detach();
      this.installView(previous);
      if (this.state === 'entered') {
        await previous.attach(host, this.emit);
        host.app.stage.addChild(previous.root);
        host.syncCanvas(this.drawsOnCanvas);
      }
      throw error;
    }
    Iif (this.state !== 'entered' || this.view !== next) return false;
    host.app.stage.addChild(next.root);
    host.syncCanvas(this.drawsOnCanvas);
    return true;
  }
 
  /** Ends the scene: leaves the stage if on it, then disposes the view and the session. */
  public dispose(): void {
    if (this.state === 'disposed') return;
    this.exit();
    this.state = 'disposed';
    this.generation += 1;
    this.view.dispose();
    this.controller.dispose();
  }
 
  /**
   * One frame: the session advances, the view draws. Advancing can end the screen (a decide screen's time runs out and
   * its host moves on), and a scene its host left or disposed meanwhile draws nothing more.
   */
  private readonly tick = (): void => {
    Iif (this.state !== 'entered') return;
    const frame = this.controller.advance(this.now());
    if ((this.state as SceneState) !== 'entered' || frame === undefined) return;
    this.view.draw(frame);
  };
 
  private installView(view: FamilyView<Frame, Intent>): void {
    this.view = view;
    this.sceneIdentity.family = view.family;
    this.stageInfo = view.getStageInfo !== undefined ? () => view.getStageInfo!() : undefined;
  }
 
  /** The view's intents reach the session only while the scene is on the stage. */
  private readonly emit: IntentSink<Intent> = (intent) => {
    if (this.state !== 'entered') return;
    this.controller.dispatch(intent);
  };
 
  private readonly onKeyDown = (event: KeyboardEvent): void => {
    this.handleKey('down', event);
  };
 
  private readonly onKeyUp = (event: KeyboardEvent): void => {
    this.handleKey('up', event);
  };
 
  private readonly onGamepad = (event: GamepadMenuEvent): void => {
    Iif (this.state !== 'entered') return;
    // A press over a dialog is the dialog's; its release still reaches the screen, which saw the press.
    if (event.type === 'down' && this.shouldSkipGamepad()) return;
    this.controller.handleKey(gamepadSessionKeyEvent(event));
  };
 
  private handleKey(type: SessionKeyEvent['type'], event: KeyboardEvent): void {
    const target = event.composedPath?.()[0] ?? event.target;
    if (this.state !== 'entered' || isEditableKeyTarget(target)) return;
    // Native controls activate themselves on Enter/Space. Let their click generate exactly one intent.
    const tag = (target as { tagName?: string } | null)?.tagName;
    if ((tag === 'BUTTON' || tag === 'A') && (event.code === 'Enter' || event.code === 'Space')) return;
    if (this.controller.handleKey(toSessionKeyEvent(type, event, this.controlButtons))) event.preventDefault();
  }
}