All files / app-play/src/services course-maker.ts

79.48% Statements 31/39
55.55% Branches 10/18
66.66% Functions 6/9
82.35% Lines 28/34

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                          1x                                                   3x 3x 3x 3x 3x 6x 11x                                   11x 11x   10x 10x   1x 1x               1x 1x   1x                 8x 8x 7x 1x 1x 1x   6x 6x 6x 6x       6x      
// LR2's course maker in the player: the player's own courses and the course being made, kept in IndexedDB
// (`course-maker-store.ts`) and shown on the course-maker card (`course-maker-panel.ts`). While a course is being made,
// a chart decided on the select screen joins it instead of playing.
 
import { logger } from '@be-music/player-browser';
import { CourseMaker, type BrowserChartCollection, type ChartFileHashes } from '@be-music/player-browser/collection';
import type { SelectScene } from '@be-music/player-browser/host';
import { LR2_COURSE_MAKER_MAX_STAGES } from '@be-music/player-engine/course';
import type { LibraryChart } from '@be-music/player-scene-model';
import { CourseMakerPanel } from '../course-maker-panel.ts';
import { playerText } from '../player-copy.ts';
import { loadMadeCourses, saveMadeCourses } from '../course-maker-store.ts';
 
const dropLog = logger('drop');
 
export interface CourseMakerServiceOptions {
  /** A chart's file hashes, cached per chart (`RecordsService`): a course keys its stages by MD5. */
  readonly resolveChartHashes: (chartEntry: LibraryChart) => Promise<ChartFileHashes | undefined>;
  /** The library as last loaded (`LibraryService`). */
  readonly collection: () => BrowserChartCollection;
  /** Relists the course folders after the player's own courses changed (`LibraryService`). */
  readonly refreshMadeCourses: () => Promise<void>;
  /** The select screen the router keeps, on the stage or off it; `undefined` before the first. */
  readonly selectView: () => SelectScene | undefined;
  readonly setStatus: (text: string) => void;
}
 
/** The course maker, its card, and what it saves and redraws as it changes. */
export class CourseMakerService {
  /** The player's own courses and the course being made (LR2's course maker), kept in IndexedDB. */
  public readonly maker: CourseMaker;
  /** The course-maker card and the "My courses" manager, mounted by {@link start}. */
  public panel: CourseMakerPanel | undefined;
  private readonly collection: CourseMakerServiceOptions['collection'];
  private readonly refreshMadeCourses: CourseMakerServiceOptions['refreshMadeCourses'];
  private readonly selectView: CourseMakerServiceOptions['selectView'];
  private readonly setStatus: CourseMakerServiceOptions['setStatus'];
 
  public constructor(options: CourseMakerServiceOptions) {
    this.collection = options.collection;
    this.refreshMadeCourses = options.refreshMadeCourses;
    this.selectView = options.selectView;
    this.setStatus = options.setStatus;
    this.maker = new CourseMaker({
      md5Of: async (chartEntry) => (await options.resolveChartHashes(chartEntry))?.md5,
      onChange: (change) => void this.handleCourseMakerChange(change),
    });
  }
 
  /** Mounts the course-maker card and restores the courses kept in IndexedDB, relisting them once they are read. */
  public start(): void {
    this.panel = new CourseMakerPanel(this.maker, { onStatus: (text) => this.setStatus(text) });
    void loadMadeCourses().then(async (made) => {
      this.maker.restore(made);
      if (made.courses.length > 0 && this.collection().charts.length > 0) await this.refreshMadeCourses();
    });
  }
 
  /**
   * Reacts to the course maker: redraws its card and the select skin for the course being made, and saves the courses
   * (and relists them) when they or the settings (the default connection, the RANDOM MIX settings and conditions) change.
   */
  private async handleCourseMakerChange(change: 'draft' | 'courses' | 'settings'): Promise<void> {
    this.panel?.update();
    if (change === 'draft') {
      // Same collection: the select view only redraws (an LR2 skin's course-maker ops and texts).
      this.selectView()?.setLibrary(this.collection());
      return;
    }
    try {
      await saveMadeCourses({
        courses: [...this.maker.courses],
        defaultConnection: this.maker.defaultConnection,
        randomMixSettings: this.maker.randomMixSettings,
        randomMixConditions: this.maker.randomMixConditions,
        randomMixes: [...this.maker.randomMixes],
      });
    } catch (error) {
      this.setStatus(playerText().course.unsaved);
      dropLog.warn('course save failed', error);
    }
    if (change === 'courses') await this.refreshMadeCourses();
    else Ethis.selectView()?.setLibrary(this.collection());
  }
 
  /**
   * While a course is being made, deciding a song adds it to the course instead of playing it, as LR2 does; deciding one
   * more once it holds five saves the course. Returns whether the song was taken.
   */
  public addChartToCourseBeingMade(chartEntry: LibraryChart): boolean {
    const draft = this.maker.draft;
    if (draft === undefined) return false;
    if (draft.stages.length >= LR2_COURSE_MAKER_MAX_STAGES) {
      const saved = this.maker.finish();
      Eif (saved !== undefined) this.setStatus(playerText().course.saved(saved.name));
      return true;
    }
    void this.maker.append(chartEntry).then((result) => {
      Eif (result.ok) {
        this.setStatus(playerText().course.added(chartEntry.title, this.maker.draft?.stages.length ?? 0));
        return;
      }
      this.setStatus(playerText().course.couldNotAdd(chartEntry.title, playerText().course.addReasons[result.reason]));
    });
    return true;
  }
}