All files / app-play/src/services replay-slot-service.ts

91.3% Statements 63/69
84.48% Branches 49/58
94.11% Functions 16/17
93.22% Lines 55/59

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                                                            9x 9x 7x 7x 7x   2x                               20x 20x 20x               20x 20x 20x 20x         2x 2x         25x         11x 11x 44x           14x         4x         17x 17x 3x 17x 3x               3x 3x 3x 3x                   7x 5x 5x   7x         7x 7x 7x 2x 2x   5x 4x 4x 4x 4x   4x     7x 4x 4x   4x 4x   4x       5x                   3x 3x         6x                    
// The replay slots as the screens use them (`replay-slots.ts` keeps them): which slots a select bar has, and a result
// screen's slots, saved into by hand or by each slot's auto-save rule, as beatoraja's `MusicResult` / `CourseResult` do.
 
import type { BestRecord } from '@be-music/player-engine/records';
import { REPLAY_SLOT_COUNT, type LibraryEntry, type ReplaySlotState } from '@be-music/player-scene-model';
import {
  libraryChartReplaySlotTarget,
  libraryCourseReplaySlotTarget,
  resolveReplayAutoSaveSlots,
  type ReplayAutoSaveRule,
  type ReplaySlotList,
  type ReplaySlotPayload,
  type ReplaySlotSaveOutcome,
  type ReplaySlotScore,
  type ReplaySlotStore,
  type ReplaySlotTarget,
} from './replay-slots.ts';
 
/** What a result can save: its replay, its score, its title, and the best record as it was before the play. */
export interface ResultReplaySave {
  readonly payload: ReplaySlotPayload;
  readonly score: ReplaySlotScore;
  readonly title: string;
  readonly previous: BestRecord | undefined;
  /** A run can have history without being eligible to update the slots. */
  readonly historyOnly?: boolean;
}
 
/** How a save into a slot is described on the status line. */
export function describeReplaySlotSave(slot: number, outcome: ReplaySlotSaveOutcome, auto: boolean): string {
  const name = `replay slot ${slot + 1}`;
  if (outcome.saved) {
    const evicted = outcome.evicted.length;
    const room = evicted === 0 ? '' : ` (removed ${evicted} older replay${evicted === 1 ? '' : 's'} to make room)`;
    return `${auto ? 'Auto-saved' : 'Saved'} the replay to ${name}${room}`;
  }
  return outcome.reason === 'budget'
    ? `Not saved to ${name}: the replay history is at the size limit`
    : `Not saved to ${name}: the browser's storage is full or unavailable`;
}
 
/**
 * A result screen's replay slots: the slots of its chart or course, and the slots this result saved into (beatoraja's
 * `ReplayStatus.SAVED`). Each slot takes one save per result. A result that cannot be saved (a replay, AUTO, a practice
 * play, a play whose record does not count) still shows which slots hold a replay.
 */
export class ResultReplaySlots {
  public readonly target: ReplaySlotTarget | undefined;
  private readonly store: ReplaySlotStore;
  private readonly source: ResultReplaySave | undefined;
  private readonly report: (text: string) => void;
  private historySave: Promise<ReplaySlotSaveOutcome> | undefined;
  private readonly saved = new Set<number>();
  private readonly saving = new Set<number>();
  private readonly listeners = new Set<() => void>();
 
  public constructor(options: {
    store: ReplaySlotStore;
    target: ReplaySlotTarget | undefined;
    save: ResultReplaySave | undefined;
    report: (text: string) => void;
  }) {
    this.store = options.store;
    this.target = options.target;
    this.source = options.target !== undefined ? options.save : undefined;
    this.report = options.report;
  }
 
  /** Calls `listener` whenever a slot of this result is saved; returns the unsubscribe. */
  public subscribe(listener: () => void): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }
 
  /** Whether the result can be saved into a slot. */
  public get saveable(): boolean {
    return this.source !== undefined && !this.source.historyOnly;
  }
 
  /** Each slot's state: saved by this result, holding a replay, or empty. */
  public states(): ReplaySlotState[] {
    const exists = this.store.exists(this.target);
    return Array.from({ length: REPLAY_SLOT_COUNT }, (_, slot) =>
      this.saved.has(slot) ? 'saved' : exists[slot] === true ? 'exists' : 'none',
    );
  }
 
  /** Whether the slots have been read, so the card can tell an empty slot from one not read yet. */
  public get loaded(): boolean {
    return this.store.loaded;
  }
 
  /** The slots' records, for a card that names what each one holds. */
  public slots(): ReplaySlotList {
    return this.store.slots(this.target);
  }
 
  /** Saves this result once, with any selections its slot rules made. */
  public async autoSave(rules: readonly ReplayAutoSaveRule[]): Promise<void> {
    const source = this.source;
    if (source === undefined || this.target === undefined) return;
    const slots = source.historyOnly ? [] : resolveReplayAutoSaveSlots(rules, source.previous, source.score);
    const outcome = await this.saveHistory(this.target, source, slots);
    Iif (!outcome.saved) {
      this.report(
        outcome.reason === 'budget'
          ? 'Replay history is at the size limit'
          : 'Could not save replay history: browser storage is full or unavailable',
      );
      return;
    }
    for (const slot of slots) this.saved.add(slot);
    if (slots.length > 0) this.notify();
    for (const slot of slots) this.report(describeReplaySlotSave(slot, outcome, true));
    Iif (slots.length === 0 && outcome.evicted.length > 0) {
      this.report(`Saved to replay history (removed ${outcome.evicted.length} older replays to make room)`);
    }
  }
 
  private saveHistory(
    target: ReplaySlotTarget,
    source: ResultReplaySave,
    slots: readonly number[],
  ): Promise<ReplaySlotSaveOutcome> {
    this.historySave ??= this.store.save(target, slots, source.payload, source.score, source.title).then((outcome) => {
      Iif (!outcome.saved) this.historySave = undefined;
      return outcome;
    });
    return this.historySave;
  }
 
  /** Saves the result into `slot`, once per result; resolves `undefined` when nothing was saved. */
  public async save(slot: number, auto = false): Promise<ReplaySlotSaveOutcome | undefined> {
    const source = this.source;
    const target = this.target;
    if (source === undefined || source.historyOnly || target === undefined) {
      Eif (!auto) this.report('This play cannot be saved to a replay slot');
      return undefined;
    }
    if (this.saved.has(slot) || this.saving.has(slot)) return undefined;
    this.saving.add(slot);
    try {
      const history = await this.saveHistory(target, source, [slot]);
      Iif (this.saved.has(slot)) return undefined;
      const outcome =
        history.saved && !history.record.slots.includes(slot)
          ? await this.store.assign(history.record.key, slot)
          : history;
      if (outcome.saved) {
        this.saved.add(slot);
        this.notify();
      }
      this.report(describeReplaySlotSave(slot, outcome, auto));
      return outcome;
    } finally {
      this.saving.delete(slot);
    }
  }
  private notify(): void {
    for (const listener of this.listeners) listener();
  }
}
 
/** The replay slots of the library's bars, by the slot targets worked out once per bar. */
export class ReplaySlotService {
  public readonly store: ReplaySlotStore;
  private readonly placement: () => 'intended' | 'lr2';
 
  public constructor(options: { store: ReplaySlotStore; nonstopPlacement: () => 'intended' | 'lr2' }) {
    this.store = options.store;
    this.placement = options.nonstopPlacement;
  }
 
  /** The slot target of a chart or course bar (a NONSTOP course's by the placement it would be played with). */
  public targetOf(entry: Exclude<LibraryEntry, { kind: 'folder' }>): ReplaySlotTarget | undefined {
    return entry.kind === 'chart'
      ? libraryChartReplaySlotTarget(entry.chart)
      : libraryCourseReplaySlotTarget(entry.course, this.placement());
  }
 
  /** Which of a bar's slots hold a replay. */
  public exists(entry: Exclude<LibraryEntry, { kind: 'folder' }>): boolean[] {
    return this.store.exists(this.targetOf(entry));
  }
}