All files / player-browser/src/skins/pixi-kit skin-text.ts

19.14% Statements 9/47
0% Branches 0/90
33.33% Functions 2/6
20% Lines 9/45

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                                                                                                                                                                                        48x                                                                                                                         3x 3x 3x 3x 3x   3x   3x               4x    
import { type Color, Container, Text, TextStyle } from 'pixi.js';
import { DEFAULT_TEXT_FONT, layoutTabularRun } from '@be-music/player-skin-sdk';
import { measureGlyph, rememberStyle } from './hud-text.ts';
import { fitTextToWidth } from './marquee.ts';
import { textResolution } from './resolution.ts';
import { alignCapCenter } from './text-metrics.ts';
 
export interface SkinTextOptions {
  size?: number;
  weight?: '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
  fill?: number | Color;
  fontFamily?: string;
  letterSpacing?: number;
  anchorX?: number;
  anchorY?: number;
  /**
   * Width to fit the text into: squeezed horizontally down to `MIN_TEXT_SQUEEZE`, then clipped to the box and scrolled
   * like a marquee (see `fitTextToWidth`).
   */
  maxWidth?: number;
  /** `false` clips an overflowing text at its start instead of scrolling it (e.g. unfocused list rows). */
  marquee?: boolean;
  /** Squeezes further when at most the final two characters would scroll. */
  squeezeShortOverflow?: boolean;
  skewX?: number;
  alpha?: number;
  stroke?: { color: number; width: number; alignment?: number; join?: 'round' | 'bevel' | 'miter' };
  /** Hard offset shadow (blur 0) at 45°. */
  dropShadow?: { color: number; distance: number; blur?: number; alpha?: number; angle?: number };
}
 
/**
 * One text node for built-in skin chrome that is rebuilt on input (select / result), fitted to `maxWidth` when needed
 * (squeezed a little, then scrolled as a marquee; see `fitTextToWidth`). Per-frame HUD text uses pooled nodes instead (see the gameplay chrome renderers).
 */
export function addSkinText(layer: Container, text: string, x: number, y: number, options: SkinTextOptions = {}): Text {
  const node = new Text({
    text,
    // Rasterize at the final device density so text stays crisp after the viewport magnifies the design canvas.
    resolution: textResolution(),
    style: resolveSkinTextStyle(options),
  });
  node.anchor.set(options.anchorX ?? 0, options.anchorY ?? 0);
  alignCapCenter(node, options.fontFamily ?? DEFAULT_TEXT_FONT, options.weight ?? '400', options.size ?? 10);
  node.position.set(x, y);
  node.skew.set(options.skewX ?? 0, 0);
  node.alpha = options.alpha ?? 1;
  layer.addChild(node);
  if (options.maxWidth !== undefined) {
    fitTextToWidth(node, layer, {
      maxWidth: options.maxWidth,
      anchorX: options.anchorX ?? 0,
      anchorY: options.anchorY ?? 0,
      scroll: options.marquee,
      squeezeShortOverflow: options.squeezeShortOverflow,
    });
  }
  return node;
}
 
/**
 * {@link addSkinText} with tabular figures, as {@link addHUDNumber} lays them out: every glyph its own text centred in a
 * cell, each digit's cell as wide as the widest digit, so figures line up down a list and keep their place as they
 * change. A run wider than `maxWidth` is squeezed to fit; it does not scroll. Returns the group holding the glyphs.
 */
export function addSkinNumber(
  layer: Container,
  text: string,
  x: number,
  y: number,
  options: SkinTextOptions = {},
): Container {
  const style = resolveSkinTextStyle(options);
  const run = layoutTabularRun(text, (char) => measureGlyph(char, style));
  const squeeze = options.maxWidth !== undefined && run.width > options.maxWidth ? options.maxWidth / run.width : 1;
  const group = new Container();
  for (const glyph of run.glyphs) {
    if (glyph.char === ' ') continue;
    const node = new Text({ text: glyph.char, resolution: textResolution(), style });
    node.anchor.set(0.5, options.anchorY ?? 0);
    alignCapCenter(node, options.fontFamily ?? DEFAULT_TEXT_FONT, options.weight ?? '400', options.size ?? 10);
    node.position.set(glyph.x + glyph.w / 2, 0);
    group.addChild(node);
  }
  group.scale.set(squeeze, 1);
  group.position.set(x - run.width * squeeze * (options.anchorX ?? 0), y);
  group.skew.set(options.skewX ?? 0, 0);
  group.alpha = options.alpha ?? 1;
  layer.addChild(group);
  return group;
}
 
const SKIN_TEXT_STYLES = new Map<string, TextStyle>();
 
/**
 * The shared `TextStyle` for `options`. Pixi keys a text's texture by its style *instance*, so screens rebuilt every
 * frame must reuse one instance per look for unchanged labels to keep their texture instead of re-rasterizing.
 */
export function resolveSkinTextStyle(options: SkinTextOptions): TextStyle {
  const shadow = options.dropShadow;
  const stroke = options.stroke;
  const fill = options.fill ?? 0xffffff;
  const key = [
    typeof fill === 'number' ? fill : fill.toNumber(),
    options.size ?? 10,
    options.weight ?? '400',
    options.fontFamily ?? DEFAULT_TEXT_FONT,
    options.letterSpacing ?? 0,
    stroke ? `${stroke.color}/${stroke.width}/${stroke.alignment ?? ''}/${stroke.join ?? ''}` : '',
    shadow ? `${shadow.color}/${shadow.distance}/${shadow.blur ?? 0}/${shadow.alpha ?? 1}/${shadow.angle ?? ''}` : '',
  ].join('|');
  let style = SKIN_TEXT_STYLES.get(key);
  if (!style) {
    style = new TextStyle({
      fill,
      fontSize: options.size ?? 10,
      fontWeight: options.weight ?? '400',
      fontFamily: options.fontFamily ?? DEFAULT_TEXT_FONT,
      letterSpacing: options.letterSpacing ?? 0,
      stroke: options.stroke,
      // Room for the blurred glow; without it the shadow is clipped to the glyph box and shows as a hard rectangle.
      padding: shadow ? Math.ceil((shadow.blur ?? 0) * 2 + shadow.distance) : 0,
      ...(shadow
        ? {
            dropShadow: {
              color: shadow.color,
              alpha: shadow.alpha ?? 1,
              blur: shadow.blur ?? 0,
              distance: shadow.distance,
              angle: shadow.angle ?? Math.PI / 4,
            },
          }
        : {}),
    });
    rememberStyle(SKIN_TEXT_STYLES, key, style);
  }
  return style;
}
 
/** A click target declared while a select screen rebuilds (see {@link addHitArea}). */
export interface PixiHitArea {
  x: number;
  y: number;
  w: number;
  h: number;
  cursor: string;
  action: () => void;
}
 
let hitCollector: PixiHitArea[] | undefined;
 
/** Collects the hit areas `build` declares through {@link addHitArea}. */
export function collectHitAreas(build: () => void): PixiHitArea[] {
  const previous = hitCollector;
  const collected: PixiHitArea[] = [];
  hitCollector = collected;
  try {
    build();
  } finally {
    hitCollector = previous;
  }
  return collected;
}
 
/**
 * Makes the rect (design pixels) run `action` when clicked. Pixi skins draw onto their own canvas, which never sees the
 * pointer, so the rect is handed to the player (`frame.hit`) instead of becoming an interactive Pixi node.
 */
export function addHitArea(x: number, y: number, w: number, h: number, cursor: string, action: () => void): void {
  hitCollector?.push({ x, y, w, h, cursor, action });
}