All files / player-browser/src/session/play/ghost presented-playfield.ts

94.44% Statements 17/18
87.5% Branches 7/8
75% Functions 3/4
93.75% Lines 15/16

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                                  9x 5x 5x   9x 9x                 5x 5x   21x 3x 3x 1x 1x 1x 1x   1x              
/**
 * A playfield presented over the live play: the play with a few of its members answered in their place, which is how a
 * ghost adds what it draws to the live play without touching it (`SidePlayfieldGhost.present`,
 * `LaneOverlayGhost.present`). The proxy is kept per play, so the view's per-play caches hold across frames.
 */
 
import type { PlayfieldRuntime } from '../../../view/shared/playfield/context.ts';
 
/** The members of the live play a presented playfield answers in its place. */
export type PlayfieldOverrides = Partial<Record<keyof PlayfieldRuntime, unknown>>;
 
/** One cached presented playfield: the overrides are rewritten each frame, the proxy kept while the play is the same. */
export class PresentedPlayfield {
  private presented: { play: PlayfieldRuntime; overrides: PlayfieldOverrides; runtime: PlayfieldRuntime } | undefined;
 
  /** `play` with `overrides` in place of its members of those names (the same proxy for the same play). */
  public present(play: PlayfieldRuntime, overrides: PlayfieldOverrides): PlayfieldRuntime {
    if (this.presented?.play !== play) {
      const kept: PlayfieldOverrides = {};
      this.presented = { play, overrides: kept, runtime: presentWith(play, kept) };
    }
    Object.assign(this.presented.overrides, overrides);
    return this.presented.runtime;
  }
}
 
/**
 * `play` with `overrides` in place of its members of those names. Everything else is the live play's own, methods
 * bound to it, so the view's writes (its lanes, its BGA videos) still land on the play.
 */
function presentWith(play: PlayfieldRuntime, overrides: PlayfieldOverrides): PlayfieldRuntime {
  const bound = new Map<PropertyKey, unknown>();
  return new Proxy(play, {
    get(target, key) {
      if (Object.hasOwn(overrides, key)) return overrides[key as keyof PlayfieldRuntime];
      const value: unknown = Reflect.get(target, key, target);
      if (typeof value !== 'function') return value;
      let method = bound.get(key);
      Eif (method === undefined) {
        method = (value as (...args: unknown[]) => unknown).bind(target);
        bound.set(key, method);
      }
      return method;
    },
    set(target, key, value) {
      return Reflect.set(target, key, value, target);
    },
  });
}