All files / app-play/src/app app.ts

0% Statements 0/412
0% Branches 0/111
0% Functions 0/238
0% Lines 0/385

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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { createChartDiagnosticsPanel } from '../ui/chart-diagnostics.ts';
import { promptRandomMixConditions } from '../ui/random-mix-dialog.ts';
import { promptRandomMixSave } from '../ui/random-mix-save-dialog.ts';
import { playerText } from '../player-copy.ts';
import { BGACameraService } from '../services/bga-camera.ts';
import { requestPlayerWindowClose } from '../ui/close-window.ts';
import { DialogPauseController } from '../ui/dialog-pause.ts';
// Imports are split across `@be-music/player-browser`'s entries (`./host`, `./skin`, `./collection`, `./audio`,
// `./recording`) so the dependency surface of this player is explicit at the file top. The main `@be-music/player-browser`
// entry is reserved for symbols that don't belong to any single entry (`logger`, `Rectangle`).
import {
  PixiSceneHost,
  resolveControlActions,
  resolveControlScheme,
  type PlayScene,
  type SelectScene,
} from '@be-music/player-browser/host';
import type { BrowseSnapshot, LibraryChart, PlayOptions } from '@be-music/player-scene-model';
import type { SkinFamilyId } from '@be-music/player-browser/skin';
import { createAudioService, setMasterVolume, type AudioService } from '@be-music/player-browser/audio';
import { downloadBlob } from '@be-music/player-browser/recording';
import { resolveChartSource } from '@be-music/player-browser/collection';
import { logger } from '@be-music/player-browser';
import { BeatorajaSkinOptionsPanel, type BeatorajaSkinOptionsPanelDeps } from '../ui/beatoraja-skin-options.ts';
import { LeaderboardPanel } from '../leaderboard-ui.ts';
import { fetchLeaderboardRankingPage, fetchLeaderboardTopReplay } from '../leaderboard.ts';
import { GhostReplayFile } from '../services/ghost.ts';
import { playerFullscreenElement, toggleFullscreen } from '../fullscreen.ts';
import { bindPlayerHeader, runPlayerHeaderAction, setPlayerHeaderSettingsOpen } from '../player-header.ts';
import { SceneRouter } from './scene-router.ts';
import { DropTarget } from './drop-target.ts';
import { CourseRoute } from './routes/course.ts';
import { NonstopRoute } from './routes/nonstop.ts';
import { SelectRoute } from './routes/select.ts';
import { DecideRoute } from './routes/decide.ts';
import { PlayRoute } from './routes/play.ts';
import { ResultRoute } from './routes/result.ts';
import { ReplayRoute } from './routes/replay.ts';
import { PlayerShell } from './shell.ts';
import { InlineSearch } from '../inline-search.ts';
import { OptionsDialog, type OptionsDialogDeps } from '../ui/options/index.ts';
import { confirmSkinDrop, promptSkinDrop } from '../ui/skin-drop-prompt.ts';
import { showPlayOptionMismatch } from '../ui/play-option-mismatch.ts';
import { showMissingReplayCharts } from '../ui/replay-missing.ts';
import { showMissingCourseStages } from '../ui/course-missing.ts';
import { readDeviceSignals, type DeviceProfile } from '../device-profile.ts';
import { captureScreenshot, finalizeRecordingIfActive, toggleRecording } from '../recording-controller.ts';
import type { PlayerGUIState, PlayerScene, PlayerWebElements, SkinFamilyOverride } from '../types.ts';
import { createPlayerGUIState, readCompressorRequest, storeBuiltInSkinId } from '../services/settings.ts';
import { BE_MUSIC_SKINS } from '../services/built-in-skins.ts';
import { SilentModeSetting } from '../services/silent-mode.ts';
import { copyPlayOptionsToGUI, playOptionsFromGUI, PlayOptionsService } from '../services/play-options.ts';
import { REPLAY_RECORDER, ReplayAutoSave } from '../services/replays.ts';
import { ReplaySlotStore } from '../services/replay-slots.ts';
import { createIndexedDBReplaySlotBackend } from '../services/replay-slot-database.ts';
import { ReplaySlotService } from '../services/replay-slot-service.ts';
import { ReplaySlotsPanel } from '../replay-slots-panel.ts';
import { RecordingService } from '../services/recording.ts';
import { StatusLine } from '../services/status.ts';
import { CourseMakerService } from '../services/course-maker.ts';
import { LibraryService } from '../services/library.ts';
import { listFolderInWorker } from '../services/folder-listing.ts';
import { createIndexedDBFolderSnapshotStore } from '../services/folder-snapshots.ts';
import { RecordsService } from '../services/records.ts';
import { CourseRunService } from '../services/courses.ts';
import { BeatorajaThemeService } from '../services/themes/beatoraja.ts';
import { BuiltInThemeService } from '../services/themes/built-in.ts';
import { LR2ThemeService } from '../services/themes/lr2.ts';
import { FamilyKits } from './family-kits.ts';
import { controlSettingsOf } from '../control-keys.ts';
import { showExitMenu } from '../ui/exit-menu.ts';
import { PracticeBarsDialog } from '../ui/practice-bars.ts';
import { storePlayTempoSettings } from '../play-tempo-settings.ts';
import { PracticeBarsMemory } from '../ui/practice-bars-model.ts';
import { createFpsOverlay } from '../ui/fps-overlay.ts';
import { openHelpModal, setHelpKeyboardSource, watchHelpExpanded } from '../help-modal.ts';
import type { TestHookRecorder } from '../test-hook.ts';
import { nameResultJingle, type LiveTestHookDeps } from '../services/test-hook.ts';
 
const gamereplay = logger('gameplay');
 
/** What the app is made with: the page's elements, the device it runs on, and the test hook's recorder when enabled. */
export interface PlayerWebAppOptions {
  readonly elements: PlayerWebElements;
  /** Phone or tablet, from the device's signals (`resolveDeviceProfile`). */
  readonly deviceProfile: DeviceProfile;
  /** `window.__beMusicTest`'s recorder (`?e2e=1` or a development build; `test-hook.ts`), or none. */
  readonly testHook: TestHookRecorder | undefined;
}
 
/**
 * The player's composition root: it makes the services, the scene router and the routes, and wires them to each other,
 * the Options dialog and the Leaderboard. `main.ts` makes it, installs the test hook over it and starts it.
 */
export class PlayerWebApp {
  /** The LR2 theme: every theme the drops brought, the one mounted, and its skins, BGM and system sounds. */
  private readonly lr2: LR2ThemeService;
  /** The beatoraja theme: its bundle, BGM and system sounds, and its entries loaded as scene kits. */
  private readonly beatoraja: BeatorajaThemeService;
  /** The Be-Music Skin the built-in family draws with, the player's values for its settings, and the skins added. */
  private readonly builtIn: BuiltInThemeService;
  /** The family each screen is drawn by, and the kit it is drawn with, from the theme services and "Skin system". */
  private readonly familyKits: FamilyKits;
  /**
   * Single PixiJS host shared by every scene (select / gameplay / result). Scenes are attached and detached through
   * `PixiSceneHost` instead of constructing a separate Pixi `Application` per view.
   */
  private readonly sceneHost = new PixiSceneHost();
  /** The frame rate readout the frame rate key switches (`ui/fps-overlay.ts`). */
  private readonly fpsOverlay = createFpsOverlay(
    document.querySelector<HTMLElement>('#fps-overlay') ?? document.createElement('div'),
  );
  private readonly chartDiagnostics = createChartDiagnosticsPanel(
    document.querySelector<HTMLElement>('#chart-diagnostics') ?? document.createElement('div'),
  );
  /** Mounting {@link sceneHost} on the page, started as the first scene shows (`mountStage`). */
  private stageMount: Promise<void> | undefined;
  /**
   * The one owner of the scene on the stage (ADR 0006): every transition finalizes a video recording in progress, hands
   * the stage to the next scene (the one showing exits as it enters) and then disposes the scene that left, unless it is
   * the select scene, which it keeps across a decide, play and result. Transitions run one at a time, and a scene made
   * for a navigation a newer one replaced is disposed instead of shown.
   */
  private readonly router = new SceneRouter<PlayerScene, PlayScene, SelectScene>({
    host: {
      setScene: async (scene, role) => {
        if (role === 'decide' || role === 'play') this.library.pauseBackgroundRefresh();
        await this.mountStage();
        this.chartDiagnostics.show();
        await this.sceneHost.setScene(scene);
        // The quick options belong to choosing a chart and playing it.
        this.optionsDialog?.setQuickOptionsShown(role === 'select' || role === 'play');
        // The BGA camera opens for a play on the stage and closes on every other screen.
        this.bgaCamera.follow(role === 'play' ? (scene as PlayScene | undefined) : undefined);
        // The replay slots' card belongs to the screen that shows it: the select screen shows it again for its bar, the
        // result route for its run.
        this.replaySlotsPanel.hide();
      },
    },
    recorder: { finalize: () => finalizeRecordingIfActive(this.recording.deps()) },
    // A navigation the scenes did not ask for (a drop, a skin or theme change, files or a replay loaded) ends the
    // course run, so the next single play is not taken for its next stage.
    onInterrupt: () => {
      // The select screen comes back where the course was started, unless that navigation has put it somewhere already.
      const courseReturn = this.courses.endRun();
      if (courseReturn !== undefined) this.lastSelectNavigation ??= courseReturn;
    },
  });
  /** The charts and courses the select screen lists, and the drops, file picks and URL loads that add to them. */
  private readonly library: LibraryService;
  /** Files dragged onto the page or picked in the Options dialog, read and handed to {@link library}. */
  private readonly dropTarget: DropTarget;
  /** The course run in progress: the EXPERT / GRADE course between its stages, its AUTO and where it started from. */
  private readonly courses = new CourseRunService();
  /** A course from its course bar to its course result (`app/routes/course.ts`). */
  private readonly courseRoute: CourseRoute;
  /** A NONSTOP course from its start, or a restitch, to its result (`app/routes/nonstop.ts`). */
  private readonly nonstopRoute: NonstopRoute;
  /** The player's own courses and the course being made (LR2's course maker), kept in IndexedDB, and its card. */
  private readonly courseMaker = new CourseMakerService({
    resolveChartHashes: (chartEntry) => this.records.resolveChartHashes(chartEntry),
    collection: () => this.library.collection,
    refreshMadeCourses: () => this.library.refreshMadeCourses(),
    selectView: () => this.selectView,
    setStatus: (text) => this.status.set(text),
  });
  /** The select screen (`createSelectScene`), whichever family draws it, kept by the router across the other screens. */
  private get selectView(): SelectScene | undefined {
    return this.router.select;
  }
  /** The play (`createPlayScene`), whichever family draws it: loading behind a decide screen, or on the stage. */
  private get gameplayView(): PlayScene | undefined {
    return this.router.play;
  }
  /**
   * The search field: typed into in place over the skin's search box (built-in and LR2 skins), or at the foot of the
   * screen where the skin has none (beatoraja). It filters whichever select scene is on screen.
   */
  private readonly search = new InlineSearch({
    input: document.querySelector<HTMLInputElement>('#search')!,
    error: document.querySelector<HTMLElement>('#search-error') ?? undefined,
    shell: document.querySelector<HTMLElement>('.shell')!,
    canvas: () => this.sceneHost?.app.canvas,
    fieldRect: () => this.selectView?.searchFieldRect(),
    nativeSearch: () =>
      this.selectView?.ownsSearchInput
        ? {
            focus: () => {
              this.selectView?.focusSearch();
            },
          }
        : undefined,
    setQuery: (query) => this.selectView?.setSearch(query),
    searchError: () => this.selectView?.searchError(),
    setEditing: (editing) => this.selectView?.setSearchEditing(editing),
    touch: () => document.documentElement.classList.contains('touch-first'),
  });
  /**
   * The player's audio service (ADR 0007): one system AudioContext for the sounds of the screens built on it, the
   * built-in decide and result screens so far. The other screens still play on contexts of their own.
   */
  private readonly audio: AudioService = createAudioService();
  /** The bars each chart was last practised on (PRACTICE), which its plays loop. */
  private readonly practiceBars = new PracticeBarsMemory();
  /** The PRACTICE bar picker, made on its first use. */
  private practiceBarsDialog: PracticeBarsDialog | undefined;
  /** The select screen, from its first showing to every return, and the starts made on it (`app/routes/select.ts`). */
  private readonly selectRoute: SelectRoute;
  /** A start's decide screen, and the play it hands the stage to (`app/routes/decide.ts`). */
  private readonly decideRoute: DecideRoute;
  /** A play, from its start to where it leads (`app/routes/play.ts`). */
  private readonly playRoute: PlayRoute;
  /** A play's, a course's or a NONSTOP run's result screen, and where it leads (`app/routes/result.ts`). */
  private readonly resultRoute: ResultRoute;
  /** A replay played back from a file (`app/routes/replay.ts`). */
  private readonly replayRoute: ReplayRoute;
  /** Where the select screen was, for its next showing to come back to (the select route's). */
  private get lastSelectNavigation(): BrowseSnapshot | undefined {
    return this.selectRoute.lastSelectNavigation;
  }
  private set lastSelectNavigation(navigation: BrowseSnapshot | undefined) {
    this.selectRoute.lastSelectNavigation = navigation;
  }
  /** The status line: the Options dialog's Status row, and whether it describes a play or result. */
  private readonly status: StatusLine;
  /** The skin system the "Drop a skin" prompt asked for, until a drop answers it or it is cancelled. */
  private pendingSkinSystem: 'lr2' | 'beatoraja' | undefined;
  /**
   * Compressor architecture for `audioCompressorMode` on every gameplay mount. Defaults to `'split'` (the new 3-stage
   * bus — see `audio-bus.ts` for the design rationale); the player accepts a `?compressor=legacy` URL flag for A/B
   * comparison against the old single-compressor topology, and `?compressor=off` to spawn gameplay with the bypass path
   * active out of the gate (the checkbox can also reach `off` mid-session).
   */
  private compressorMode: 'split' | 'legacy' = 'split';
  /**
   * GUI state object the Tweakpane controllers read / write. Held on the instance so the GUI build code and the runtime
   * handlers (`toggleRecording` etc.) share a single source of truth — programmatic updates go through `state.foo = …`
   * + `controller.updateDisplay()`.
   */
  private readonly guiState: PlayerGUIState;
  /** The Leaderboard's Options dialog folder, account chip and play submission. */
  private readonly leaderboard = new LeaderboardPanel({
    // Read on use: `guiState` is initialized after this field.
    settings: () => this.guiState,
    setStatus: (text) => this.status.set(text),
    warn: (message, error) => gamereplay.warn(message, error),
    recorder: REPLAY_RECORDER,
    bestEXScore: (chartEntry) => this.records.peekChartBestRecord(chartEntry)?.exScore,
  });
  /**
   * The play options in force, the full set: fed by the select screen (`on.playOptions`) and the Options dialog
   * ({@link setPlayOptions}); every select screen starts from them, and a decide screen and a play take them.
   */
  private readonly playOptions: PlayOptionsService;
  /** The best records and the chart-file hashes they are keyed by, and the record keys of the play in flight. */
  private readonly records = new RecordsService({
    collection: () => this.library.collection,
    judgeRuleset: () => this.guiState.judgeRuleset,
  });
  /**
   * Replay auto-save, by `guiState.autoSaveReplay` as it was when the current play STARTED: the result-screen
   * auto-save of a play, and of a course after its last stage, reads this latch, not the live checkbox (the checkbox is
   * disabled during gameplay anyway — the latch is the enforcement for any path that slips through).
   */
  private readonly replayAutoSave = new ReplayAutoSave({
    download: downloadBlob,
    warn: (message, error) => gamereplay.warn(message, error),
  });
  /**
   * The replay slots: four replays per chart and per course kept in IndexedDB, saved into from a result and played from
   * the select screen.
   */
  private readonly replaySlots = new ReplaySlotService({
    store: new ReplaySlotStore({ backend: createIndexedDBReplaySlotBackend() }),
    // Read on use: `guiState` is initialized after this field.
    nonstopPlacement: () => this.guiState.nonstopPlacement,
  });
  /** The replay file picked as a ghost (Options dialog → Replay / ghost → "Ghost replay file…"), for this visit. */
  private readonly ghostReplayFile = new GhostReplayFile();
  /** The replay slots' card, on the skins without a replay-slot UI of their own (`replay-slots-panel.ts`). */
  private readonly replaySlotsPanel = new ReplaySlotsPanel({
    service: this.replaySlots,
    replay: (slot) => this.selectView?.replay(slot),
    replayHistory: (record) => void this.replayRoute.startReplayFromHistory(record),
    setStatus: (text) => this.status.set(text),
  });
  /**
   * The camera a play can show in its BGA frame (Options → Camera). It opens only while a play is on the
   * stage with the setting on.
   */
  private readonly bgaCamera = new BGACameraService({
    mediaDevices: navigator.mediaDevices,
    permissions: navigator.permissions,
    setStatus: (text) => this.status.set(text),
  });
  /** The Capture folder's video recording and screenshots: the record armed, the next file name, the format. */
  private readonly recording: RecordingService;
  /** "Play in silent mode": the setting, its checkboxes and its hint. */
  private readonly silentMode: SilentModeSetting;
  /** The Options dialog (`ui/options/`), made once the settings and services it works with are. */
  private readonly optionsDialog: OptionsDialog;
  /** The skin-options panel for the beatoraja screen showing (`ui/beatoraja-skin-options.ts`). */
  private readonly beatorajaSkinOptions: BeatorajaSkinOptionsPanel;
  /** `window.__beMusicTest` for the end-to-end suite (`?e2e=1` or a development build; `test-hook.ts`). */
  private readonly testHook: TestHookRecorder | undefined;
  /** The page around the stage: its gameplay state, fullscreen and touch controls (`app/shell.ts`). */
  private readonly shell: PlayerShell;
  private readonly elements: PlayerWebElements;
  public constructor({ elements, deviceProfile, testHook }: PlayerWebAppOptions) {
    this.elements = elements;
    this.testHook = testHook;
    this.guiState = createPlayerGUIState({
      signals: readDeviceSignals(),
      devicePixelRatio: window.devicePixelRatio || 1,
      builtInSkinId: (stored) => BE_MUSIC_SKINS.resolve(stored).id,
      actions: {
        openFolder: () => void this.dropTarget.openFolder(),
        openFiles: () => this.elements.filesInput.click(),
        record: () => {
          void toggleRecording(this.recording.deps());
        },
        screenshot: () => {
          void captureScreenshot(this.recording.deps());
        },
      },
    });
    this.status = new StatusLine({
      settings: this.guiState,
      refresh: () => this.optionsDialog.refreshStatus(),
      record: (text) => this.testHook?.recordStatus(text),
    });
    this.recording = new RecordingService({
      sceneHost: this.sceneHost,
      recordController: () => this.optionsDialog.recordController,
      activeGameplay: () => this.gameplayView?.recording,
      settings: this.guiState,
      setStatus: (text) => this.status.set(text),
      setRecordingSettingsLocked: (locked) => this.optionsDialog.setRecordingSettingsLocked(locked),
    });
    // Every sound plays through the master volume; start from the remembered level and mute state.
    setMasterVolume(this.guiState.muted ? 0 : this.guiState.masterVolume / 100);
    this.playOptions = new PlayOptionsService(playOptionsFromGUI(this.guiState));
    this.silentMode = new SilentModeSetting({
      settings: this.guiState,
      touchFirst: deviceProfile.touchFirst,
      onRemember: () => this.optionsDialog.scheduleSettingsSave(),
    });
    this.silentMode.install();
    // `?compressor=split|legacy|off` wins for this visit. With no flag, the remembered checkbox stays.
    const compressor = readCompressorRequest(window.location.href);
    if (compressor) {
      this.compressorMode = compressor.mode;
      this.guiState.compressor = compressor.enabled;
    }
    this.lr2 = new LR2ThemeService({
      elements,
      setStatus: (text) => this.status.set(text),
      rebuildSkinFamilyPicker: () => this.optionsDialog.rebuildSkinFamilyPicker(),
      rebuildLR2ThemePicker: () => this.optionsDialog.rebuildLR2ThemePicker(),
    });
    this.beatoraja = new BeatorajaThemeService({
      elements,
      audio: this.audio,
      setStatus: (text) => this.status.set(text),
      selectView: () => this.selectView,
      gameplayView: () => this.gameplayView,
      rebuildBeatorajaSkinPickers: () => this.optionsDialog.rebuildBeatorajaSkinPickers(),
      rebuildSkinFamilyPicker: () => this.optionsDialog.rebuildSkinFamilyPicker(),
      refreshBeatorajaPlaySkinOptions: () => this.beatorajaSkinOptions.refreshBeatorajaPlaySkinOptions(),
      refreshBeatorajaSelectSkinOptions: () => this.beatorajaSkinOptions.refreshBeatorajaSelectSkinOptions(),
    });
    this.builtIn = new BuiltInThemeService({
      guiState: this.guiState,
      setStatus: (text) => this.status.set(text),
      handleBuiltInSkinChange: (id) => this.handleBuiltInSkinChange(id),
    });
    this.familyKits = new FamilyKits({
      lr2: this.lr2,
      beatoraja: this.beatoraja,
      builtIn: this.builtIn,
      guiState: this.guiState,
    });
    this.library = new LibraryService({
      elements,
      resolveChartHashes: (chartEntry) => this.records.resolveChartHashes(chartEntry),
      bemuseReplayGain: () => this.guiState.bemuseReplayGain,
      courseMaker: this.courseMaker.maker,
      selectView: () => this.selectView,
      showing: () => this.router.current?.identity.kind,
      setStatus: (text) => this.status.set(text),
      showSelect: () => this.showSelect(),
      leaveSelect: () => this.leaveSelect(),
      browseTo: (navigation) => {
        this.lastSelectNavigation = navigation;
      },
      startReplayReplayFromFile: (file) => this.replayRoute.startReplayReplayFromFile(file),
      loadTheme: (files) => this.lr2.loadTheme(files, false),
      loadBeatorajaTheme: (files) => this.beatoraja.loadBeatorajaTheme(files, false),
      playSkins: () => this.lr2.playSkins,
      selectSkin: () => this.lr2.selectSkin,
      resultSkin: () => this.lr2.resultSkin,
      beatorajaTheme: () => this.beatoraja.beatorajaTheme,
      confirmSkinDrop: (families) => {
        const preferred = this.pendingSkinSystem;
        this.pendingSkinSystem = undefined;
        const policy = this.guiState.confirmDroppedSkin
          ? 'ask'
          : this.guiState.skipDroppedSkin
            ? 'keep-current'
            : 'apply';
        return confirmSkinDrop(families, preferred, policy, (apply) => {
          this.guiState.confirmDroppedSkin = false;
          this.guiState.skipDroppedSkin = !apply;
          this.optionsDialog.confirmDroppedSkinController?.refresh();
          this.optionsDialog.scheduleSettingsSave();
        });
      },
      applyDroppedSkin: (family) => this.applyDroppedSkin(family),
    });
    this.dropTarget = new DropTarget({
      elements,
      leaveSelect: () => this.leaveSelect(),
      processIncomingFiles: (files, origin, signal) => this.library.processIncomingFiles(files, origin, signal),
      runBackgroundRefresh: (work) => this.library.runBackgroundRefresh(work),
      refreshCharts: () => this.library.refreshCharts(),
      folders: {
        // A remembered folder is walked off the page's thread.
        list: (folder, onProgress, signal) =>
          listFolderInWorker(
            () => new Worker(new URL('../folder-listing-worker.ts', import.meta.url), { type: 'module' }),
            folder,
            onProgress,
            signal,
          ),
        snapshots: createIndexedDBFolderSnapshotStore(),
      },
      resumeSelect: () => (this.router.current ? Promise.resolve() : this.showSelect()),
      setStatus: (text) => this.status.set(text),
      loadPickedFiles: (files) => this.library.loadPickedFiles(files),
      recordLoad: () => this.testHook?.recordLoad(),
    });
    this.nonstopRoute = new NonstopRoute({
      courses: this.courses,
      library: this.library,
      records: this.records,
      guiState: this.guiState,
      replayAutoSave: this.replayAutoSave,
      leaderboard: this.leaderboard,
      familyKits: this.familyKits,
      replayRecorder: REPLAY_RECORDER,
      testHook: this.testHook,
      setStatus: (text) => this.status.set(text),
      showSelect: () => this.showSelect(),
      showDecide: (chartEntry, overrides, then) => this.decideRoute.showDecide(chartEntry, overrides, then),
      playChart: (chartEntry, overrides) => this.playRoute.playChart(chartEntry, overrides),
      showResult: (data, mode) => this.resultRoute.showResult(data, mode),
      showBeatorajaResult: (data, options) => this.resultRoute.showBeatorajaResult(data, options),
      courseReplaySlots: (courseLog, native, kept, fromReplay) =>
        this.resultRoute.courseReplaySlots(courseLog, native, kept, fromReplay),
      unlockReplayOptions: () => this.unlockReplayOptions(),
      onRunResult: (course) => this.courseRoute.noteNonstopResult(course),
    });
    this.courseRoute = new CourseRoute({
      courses: this.courses,
      library: this.library,
      records: this.records,
      courseMaker: this.courseMaker,
      promptRandomMix: (request) => promptRandomMixConditions(request),
      promptRandomMixSave: (request) => promptRandomMixSave(request),
      replayAutoSave: this.replayAutoSave,
      leaderboard: this.leaderboard,
      familyKits: this.familyKits,
      replayRecorder: REPLAY_RECORDER,
      selectNavigation: () => this.selectView?.snapshot() ?? this.lastSelectNavigation,
      setStatus: (text) => this.status.set(text),
      showMissingCourseStages: (course) =>
        showMissingCourseStages(course, (missing) => this.library.findMissingCourseStages(missing)),
      startNonstopCourse: (course, options) => this.nonstopRoute.startNonstopCourse(course, options),
      showSelect: () => this.showSelect(),
      showDecide: (chartEntry, overrides, then) => this.decideRoute.showDecide(chartEntry, overrides, then),
      playChart: (chartEntry, overrides) => this.playRoute.playChart(chartEntry, overrides),
      showResult: (data, mode) => this.resultRoute.showResult(data, mode),
      showBeatorajaResult: (data, options) => this.resultRoute.showBeatorajaResult(data, options),
      courseReplaySlots: (courseLog, native, kept, fromReplay) =>
        this.resultRoute.courseReplaySlots(courseLog, native, kept, fromReplay),
      unlockReplayOptions: () => this.unlockReplayOptions(),
    });
    this.optionsDialog = new OptionsDialog(this.optionsDialogDeps());
    this.fpsOverlay.setShown(this.guiState.showFPS);
    this.beatorajaSkinOptions = new BeatorajaSkinOptionsPanel(this.beatorajaSkinOptionsDeps());
    this.selectRoute = new SelectRoute({
      controls: () => controlSettingsOf(this.guiState),
      showExitMenu,
      closeWindow: () => requestPlayerWindowClose(window, () => this.status.set(playerText().shell.windowCloseBlocked)),
      router: this.router,
      elements,
      library: this.library,
      records: this.records,
      courses: this.courses,
      courseRoute: this.courseRoute,
      courseMaker: this.courseMaker,
      familyKits: this.familyKits,
      lr2: this.lr2,
      beatoraja: this.beatoraja,
      builtIn: this.builtIn,
      playOptions: this.playOptions,
      guiState: this.guiState,
      audio: this.audio,
      search: this.search,
      optionsDialog: this.optionsDialog,
      beatorajaSkinOptions: this.beatorajaSkinOptions,
      playStatusShown: () => this.status.playShown,
      setStatus: (text) => this.status.set(text),
      showChartDiagnostics: (chart, path) => this.chartDiagnostics.show(chart, path),
      unlockReplayOptions: () => this.unlockReplayOptions(),
      rememberHiSpeed: (value, source) => this.playRoute.rememberHiSpeed(value, source),
      showDecide: (chartEntry, overrides) => this.decideRoute.showDecide(chartEntry, overrides),
      preloadOnLaunch: (chartEntry, overrides) => this.decideRoute.preloadOnLaunch(chartEntry, overrides),
      pickPracticeBars: (chartEntry) => {
        this.practiceBarsDialog ??= new PracticeBarsDialog({
          audio: this.audio,
          memory: this.practiceBars,
          playOptions: () => this.playOptions.current,
          ruleset: () => this.guiState.judgeRuleset,
          // As a select screen's edit: kept, mirrored into the Options dialog and saved.
          setPlayOptions: (changes) => {
            this.setPlayOptions(changes);
            copyPlayOptionsToGUI(this.playOptions.current, this.guiState);
            this.optionsDialog.refreshRulesetChoices();
            this.optionsDialog.refreshPlayOptionControllers();
          },
          tempo: () => ({
            enabled: this.guiState.tempoEnabled,
            percent: this.guiState.tempoPercent,
            pitchMode: this.guiState.tempoPitchMode,
            stretchAlgorithm: this.guiState.tempoStretchAlgorithm,
          }),
          // As the Options dialog's Tempo page, its Enabled switch included; kept and saved.
          setTempo: ({ enabled, percent, pitchMode }) => {
            if (enabled !== undefined) this.guiState.tempoEnabled = enabled;
            if (percent !== undefined) this.guiState.tempoPercent = percent;
            if (pitchMode !== undefined) this.guiState.tempoPitchMode = pitchMode;
            storePlayTempoSettings(this.guiState);
            this.optionsDialog.refreshPlayOptionControllers();
          },
        });
        // The select screen's preview of the chart gives way to the bars' auditions.
        this.audio.preview.stop();
        return this.practiceBarsDialog.open(chartEntry, resolveChartSource(this.library.collection, chartEntry));
      },
      replaySlots: this.replaySlots,
      replaySlotsPanel: this.replaySlotsPanel,
      startReplayFromSlot: (entry, slot) => this.replayRoute.startReplayFromSlot(entry, slot),
    });
    this.decideRoute = new DecideRoute({
      controls: () => controlSettingsOf(this.guiState),
      router: this.router,
      selectRoute: this.selectRoute,
      elements,
      library: this.library,
      records: this.records,
      familyKits: this.familyKits,
      beatoraja: this.beatoraja,
      playOptions: this.playOptions,
      guiState: this.guiState,
      audio: this.audio,
      beatorajaSkinOptions: this.beatorajaSkinOptions,
      lastPlay: () => this.playRoute.lastPlay,
      recordingDeps: () => this.recording.deps(),
      setRecordingFilenameBase: (base) => this.recording.setFilenameBase(base),
      setStatus: (text) => this.status.set(text),
      showChartDiagnostics: (chart, path) => this.chartDiagnostics.show(chart, path),
      setPlayStatus: (text) => this.status.setPlay(text),
      lockReplayOptionsForPlay: (liveTempo, chartEntry) => this.lockReplayOptionsForPlay(liveTempo, chartEntry),
      showSelect: () => this.showSelect(),
      playChart: (chartEntry, overrides) => this.playRoute.playChart(chartEntry, overrides),
      buildPlayScene: (chartEntry, kit, overrides) => this.playRoute.buildPlayScene(chartEntry, kit, overrides),
      latchPlay: (view) => this.playRoute.latchPlay(view),
    });
    this.resultRoute = new ResultRoute({
      controls: () => controlSettingsOf(this.guiState),
      router: this.router,
      library: this.library,
      records: this.records,
      courses: this.courses,
      courseRoute: this.courseRoute,
      familyKits: this.familyKits,
      lr2: this.lr2,
      beatoraja: this.beatoraja,
      builtIn: this.builtIn,
      replayAutoSave: this.replayAutoSave,
      leaderboard: this.leaderboard,
      audio: this.audio,
      testHook: this.testHook,
      lastPlay: () => this.playRoute.lastPlay,
      nameResultJingle: (bytes) => nameResultJingle(bytes, { lr2: this.lr2, beatoraja: this.beatoraja }),
      setPlayStatus: (text) => this.status.setPlay(text),
      showSelect: () => this.showSelect(),
      playChart: (chartEntry, overrides) => this.playRoute.playChart(chartEntry, overrides),
      unlockReplayOptions: () => this.unlockReplayOptions(),
      replaySlots: {
        store: this.replaySlots.store,
        rules: () => [
          this.guiState.replaySlotAutoSave1,
          this.guiState.replaySlotAutoSave2,
          this.guiState.replaySlotAutoSave3,
          this.guiState.replaySlotAutoSave4,
        ],
        panel: this.replaySlotsPanel,
      },
      setStatus: (text) => this.status.set(text),
    });
    this.playRoute = new PlayRoute({
      router: this.router,
      selectRoute: this.selectRoute,
      elements,
      library: this.library,
      records: this.records,
      leaderboard: this.leaderboard,
      familyKits: this.familyKits,
      beatoraja: this.beatoraja,
      courses: this.courses,
      courseRoute: this.courseRoute,
      nonstopRoute: this.nonstopRoute,
      results: this.resultRoute,
      playOptions: this.playOptions,
      guiState: this.guiState,
      ghostSources: {
        replays: this.replaySlots.store,
        replayFile: this.ghostReplayFile,
        // The top run under the ruleset the play is judged by.
        fetchLeaderboardTopReplay: (chartFingerprint) =>
          fetchLeaderboardTopReplay(chartFingerprint, this.guiState.judgeRuleset),
      },
      // The ranking under the ruleset the play is judged by, as the ghost's top run is.
      fetchRankingPage: (chartFingerprint, offset, limit) =>
        fetchLeaderboardRankingPage(chartFingerprint, this.guiState.judgeRuleset, offset, limit),
      optionsDialog: this.optionsDialog,
      compressorMode: this.compressorMode,
      deviceProfile,
      audio: this.audio,
      sceneHost: this.sceneHost,
      replayRecorder: REPLAY_RECORDER,
      testHook: this.testHook,
      recordingDeps: () => this.recording.deps(),
      setRecordingFilenameBase: (base) => this.recording.setFilenameBase(base),
      setStatus: (text) => this.status.set(text),
      setPlayStatus: (text) => this.status.setPlay(text),
      lockReplayOptionsForPlay: (liveTempo, chartEntry) => this.lockReplayOptionsForPlay(liveTempo, chartEntry),
      unlockReplayOptions: () => this.unlockReplayOptions(),
      showSelect: () => this.showSelect(),
      practiceRange: (chartEntry) => this.practiceBars.rangeFor(chartEntry.id),
      practiceSkipped: (chartEntry) => this.practiceBars.skipsPractice(chartEntry.id),
      practiceNoteShare: (chartEntry) => this.practiceBars.noteShareFor(chartEntry.id),
      showPlayOptionMismatch,
      setPlayOptions: (changes) => this.setPlayOptions(changes),
    });
    this.replayRoute = new ReplayRoute({
      library: this.library,
      records: this.records,
      setStatus: (text) => this.status.set(text),
      setPlayStatus: (text) => this.status.setPlay(text),
      playChart: (chartEntry, overrides) => this.playRoute.playChart(chartEntry, overrides),
      showSelect: () => this.showSelect(),
      startCourseReplay: (course, courseLog) => this.courseRoute.startCourseReplay(course, courseLog),
      startNonstopCourse: (course, options) => this.nonstopRoute.startNonstopCourse(course, options),
      showMissingReplayCharts,
      replaySlots: this.replaySlots,
    });
    this.shell = new PlayerShell({
      sceneHost: this.sceneHost,
      elements,
      search: this.search,
      deviceProfile,
      gameplayView: () => this.gameplayView,
      showing: () => this.router.current?.identity.kind,
      launching: () => this.selectView?.launching() === true,
    });
  }
 
  /** What the Options dialog reaches of the app: the settings and services, readers of the app's state, and its actions. */
  private optionsDialogDeps(): OptionsDialogDeps {
    return {
      settings: this.guiState,
      ghostReplayFile: this.ghostReplayFile,
      sceneHost: this.sceneHost,
      showFPSOverlay: (shown) => this.fpsOverlay.setShown(shown),
      silentMode: this.silentMode,
      bgaCamera: this.bgaCamera,
      leaderboard: this.leaderboard,
      library: this.library,
      records: this.records,
      courseMaker: this.courseMaker,
      skinSettings: this.builtIn.skinSettings,
      beatorajaSkinOverridesByType: this.beatoraja.beatorajaSkinOverridesByType,
      compressorMode: this.compressorMode,
      shell: this.elements.shell,
      gameplayView: () => this.gameplayView,
      selectView: () => this.selectView,
      familyDispatchState: () => this.familyKits.familyDispatchState(),
      hasPendingSkin: (family) => (family === 'lr2' ? this.lr2.hasPendingTheme() : this.beatoraja.hasPendingTheme()),
      beatorajaTheme: () => this.beatoraja.beatorajaTheme,
      availableLR2Themes: () => this.lr2.availableLR2Themes,
      activeLR2ThemeName: () => this.lr2.activeLR2ThemeName,
      beMusicSkin: () => this.builtIn.beMusicSkin,
      activeBeatorajaPlay: () => this.beatoraja.activeBeatorajaPlay,
      beatorajaSkinConfig: (entryPath, header) => this.beatoraja.beatorajaSkinConfig(entryPath, header),
      setStatus: (text) => this.status.set(text),
      reusePreviousArrangement: () => this.playOptions.reusePreviousArrangement(this.guiState.judgeRuleset),
      clearArrangement: () => this.playOptions.clearArrangement(),
      setPlayOptions: (changes) => this.setPlayOptions(changes),
      rememberHiSpeed: (value, source) => this.playRoute.rememberHiSpeed(value, source),
      refreshSelectRecords: () => this.refreshSelectRecords(),
      handleSkinFamilyOverrideChange: (value) => this.handleSkinFamilyOverrideChange(value),
      handleBuiltInSkinChange: (id) => this.handleBuiltInSkinChange(id),
      addBeMusicSkin: (skin) => this.builtIn.addBeMusicSkin(skin),
      addBeMusicSkinFromURL: (url) => this.builtIn.addBeMusicSkinFromURL(url),
      applyBeMusicSkinSettings: () => this.applyBeMusicSkinSettings(),
      applyLR2ThemeByName: (name) => this.applyLR2ThemeByName(name),
      promptSkinDrop: (family) =>
        promptSkinDrop(family, (pending) => {
          this.pendingSkinSystem = pending;
        }),
      applyBeatorajaSelectSkinConfig: (entryPath, config) =>
        this.beatoraja.applyBeatorajaSelectSkinConfig(entryPath, config),
      applyBeatorajaPlaySkinConfig: (entryPath, config) =>
        this.beatoraja.applyBeatorajaPlaySkinConfig(entryPath, config),
    };
  }
 
  /** What the beatoraja skin-options panel reaches of the app: the screens showing, their entries' options, applying. */
  private beatorajaSkinOptionsDeps(): BeatorajaSkinOptionsPanelDeps {
    const surface = playerFullscreenElement(document);
    return {
      container: surface instanceof HTMLElement ? surface : this.elements.shell,
      beatorajaKitCaches: this.beatoraja.beatorajaKitCaches,
      gameplayView: () => this.gameplayView,
      activeBeatorajaPlay: () => this.beatoraja.activeBeatorajaPlay,
      beatorajaSelectKit: () => this.beatoraja.beatorajaSelectKit,
      beatorajaSkinConfig: (entryPath, header) => this.beatoraja.beatorajaSkinConfig(entryPath, header),
      collectBeatorajaFileCandidates: (entryPath, header) =>
        this.beatoraja.collectBeatorajaFileCandidates(entryPath, header),
      applyBeatorajaPlaySkinConfig: (entryPath, config) =>
        this.beatoraja.applyBeatorajaPlaySkinConfig(entryPath, config),
      applyBeatorajaSelectSkinConfig: (entryPath, config) =>
        this.beatoraja.applyBeatorajaSelectSkinConfig(entryPath, config),
    };
  }
 
  /** What the test hook reads at each `state()` call: the scenes the router holds, and the services' state. */
  public testHookDeps(): LiveTestHookDeps {
    return {
      router: this.router,
      elements: this.elements,
      guiState: this.guiState,
      library: this.library,
      records: this.records,
      courses: this.courses,
      courseMaker: this.courseMaker,
      lastPlay: () => this.playRoute.lastPlay,
    };
  }
 
  public start(): void {
    const modalPause = new DialogPauseController(() => {
      const play = this.gameplayView;
      return play !== undefined && this.router.current === play ? play : undefined;
    });
    watchHelpExpanded((open) => modalPause.setOpen('help', open));
    this.optionsDialog.watchExpanded((open) => {
      setPlayerHeaderSettingsOpen(open);
      modalPause.setOpen('settings', open);
    });
    document.querySelector('#fullscreen-exit')?.addEventListener('click', () => runPlayerHeaderAction('fullscreen'));
    this.optionsDialog.buildGUI();
    bindPlayerHeader({
      toggleOptions: () => this.optionsDialog.toggle(),
      openSignIn: () => this.leaderboard.openSignIn(),
    });
    this.courseMaker.start();
    // The replay slots load once; the select screen draws them again whenever they change.
    void this.replaySlots.store.load();
    this.replaySlots.store.subscribe(() => this.selectView?.refreshRecords());
    // Prepare the renderer and the saved index together. The first selection does not wait for disk walks or fetches.
    void this.mountStage().catch(() => undefined);
    let startRefresh!: () => void;
    const refreshAfter = new Promise<void>((resolve) => {
      startRefresh = resolve;
    });
    const initialSelectReady = Promise.allSettled([
      this.library.restoreStartupCache(),
      this.dropTarget.restoreFolder(refreshAfter),
    ]).then(async () => {
      await this.library
        .finishStartupCache()
        .catch((error: unknown) => console.warn('Library cache setup failed', error));
      await this.showSelect();
      startRefresh();
    });
    // A page put away (closed, or into the back/forward cache) keeps no decoded samples for a retry.
    window.addEventListener('pagehide', () => this.audio.chartSamples.release());
 
    // The Options dialog's file pickers, and files dragged onto the page.
    this.dropTarget.wire();
 
    // Global `/` shortcut focuses the search input. Standard editor convention — same as GitHub / Slack / Discord. We
    // suppress the actual `/` character so it doesn't end up in the input field.
    window.addEventListener('keydown', (event) => {
      if (event.key !== '/') return;
      const target = event.target as HTMLElement | null;
      // Don't hijack `/` when the user is already typing into some other input.
      if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) {
        return;
      }
      event.preventDefault();
      this.search.open();
    });
 
    // Help's Keyboard tab draws the player's keys, on the key map of the screen shown.
    setHelpKeyboardSource(() => ({
      settings: controlSettingsOf(this.guiState),
      scheme: resolveControlScheme(
        this.router.current?.identity.family ?? 'built-in',
        this.guiState.builtInControlScheme,
      ),
    }));
 
    // The keys every screen takes, as LR2 and beatoraja do: F4 switches full screen and F6 takes a screenshot (the
    // player's own keys for them when set, `global.*` in the key config).
    window.addEventListener('keydown', (event) => {
      if (event.repeat) return;
      const target = event.target as HTMLElement | null;
      if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return;
      // A 24 / 48 KEY chart can play F-keys: a lane's key is the lane's.
      if (this.router.current?.identity.kind === 'play' && this.router.play?.takesKey(event) === true) return;
      // The skin's family's keys (F1 is beatoraja's frame rate and LR2's help).
      const family = this.router.current?.identity.family ?? 'built-in';
      const scheme = resolveControlScheme(family, this.guiState.builtInControlScheme);
      const actions = resolveControlActions(scheme, this.guiState.actionKeys);
      if (actions.is('global.help', event)) {
        event.preventDefault();
        openHelpModal();
      } else if (actions.is('global.fps', event)) {
        event.preventDefault();
        this.guiState.showFPS = !this.guiState.showFPS;
        this.fpsOverlay.setShown(this.guiState.showFPS);
        this.optionsDialog.fpsOverlayController?.refresh();
        this.optionsDialog.scheduleSettingsSave();
      } else if (actions.is('global.fullscreen', event)) {
        event.preventDefault();
        void toggleFullscreen(playerFullscreenElement(document));
      } else if (actions.is('global.screenshot', event)) {
        event.preventDefault();
        void captureScreenshot(this.recording.deps());
      }
    });
 
    // Restore the remote library once the select screen is up. Local folders load independently.
    void this.library.autoLoad(window.location.href, initialSelectReady);
  }
 
  /**
   * Mounts the scene host on the page once, as the first scene shows (the router's stage); every later call waits on
   * that one mount, so no scene enters before the renderer exists.
   */
  private mountStage(): Promise<void> {
    this.stageMount ??= (async () => {
      await this.sceneHost.mount(this.elements.stage, {
        resolution: this.guiState.renderResolution,
        renderer: this.guiState.renderer,
      });
      this.shell.wireCanvasFullscreen();
      this.shell.wireTouchControls();
      this.sceneHost.app.ticker.add(this.shell.syncGameplayShellState);
    })();
    return this.stageMount;
  }
 
  /**
   * Takes the select scene off the stage when it is the one showing, leaving no scene up; any other scene stays. The
   * select scene goes off this way while files load (the router keeps it: its BGM, preview and drawing pause until it
   * shows again).
   */
  private leaveSelect(): Promise<boolean> {
    const select = this.router.select;
    return select !== undefined && this.router.current === select ? this.router.leave() : Promise.resolve(false);
  }
 
  /**
   * Applies a confirmed skin drop. While a play is on the stage, that play draws with the new family and keeps its
   * chart. Otherwise the select scene is released so the next `showSelect` builds it for the new family.
   */
  private async applyDroppedSkin(family: SkinFamilyId): Promise<void> {
    if (family !== 'lr2' && family !== 'beatoraja') return;
    if (family === 'lr2') this.lr2.activatePendingTheme();
    else await this.beatoraja.activatePendingTheme();
    this.guiState.skinFamilyOverride = family;
    this.optionsDialog.showSkinSystem(family);
    const play = this.gameplayView;
    if (play !== undefined && this.router.current === play) {
      await this.switchPlayFamily(play);
      return;
    }
    await this.selectRoute.dropSelect();
  }
 
  /** Redraws the select screen in place with the records of the current judge ruleset, after it changed. */
  private refreshSelectRecords(): void {
    this.selectView?.setLibrary(this.library.collection);
  }
 
  /**
   * Apply a user-picked LR2 theme. Disposes the persistent select view so it gets reconstructed against the new
   * skin on the next `showSelect`, mounts the theme into the slot fields, and returns to song-select.
   */
  private async applyLR2ThemeByName(name: string): Promise<void> {
    const theme = this.lr2.availableLR2Themes.find((entry) => entry.name === name);
    if (theme === undefined) return;
    await this.selectRoute.dropSelect();
    await this.lr2.mountLR2Theme(theme.files, theme.name);
    await this.showSelect();
  }
 
  /**
   * Apply an Options dialog built-in skin change: persist it and rebuild the persistent select scene (the same dispose-and-
   * rebuild the skin-family override uses). Gameplay / result pick the skin up on their next mount.
   */
  private handleBuiltInSkinChange(id: string): void {
    this.guiState.builtInSkin = BE_MUSIC_SKINS.resolve(id).id;
    storeBuiltInSkinId(this.guiState.builtInSkin);
    this.optionsDialog.rebuildSkinSettingsFolder();
    void this.handleSkinFamilyOverrideChange(this.guiState.skinFamilyOverride);
  }
 
  /**
   * Hands the active Be-Music Skin's settings to the scenes on screen (and to the select scene and a play loading off
   * it), which draw with them from their next frame.
   */
  private applyBeMusicSkinSettings(): void {
    for (const scene of new Set([this.router.select, this.router.play, this.router.current])) {
      if (scene?.identity.family === 'built-in') scene.updateKit(this.builtIn.builtInKit);
    }
  }
 
  /**
   * Apply an Options dialog skin-family change. While a play is on the stage, that play draws with the new family and keeps
   * its chart. Otherwise the persistent select scene is made again for the family the pick gives.
   */
  private async handleSkinFamilyOverrideChange(value: SkinFamilyOverride): Promise<void> {
    if (value === 'lr2') this.lr2.activatePendingTheme();
    else if (value === 'beatoraja') await this.beatoraja.activatePendingTheme();
    this.guiState.skinFamilyOverride = value;
    this.optionsDialog.showSkinSystem(value);
    const play = this.gameplayView;
    if (play !== undefined && this.router.current === play) {
      void this.switchPlayFamily(play);
      return;
    }
    void this.selectRoute.dropSelect().then(() => this.showSelect());
  }
 
  /** Swaps the play on the stage to the family just picked, and shows that family's skin options when it has them. */
  private async switchPlayFamily(play: PlayScene): Promise<void> {
    await this.playRoute.switchPlayFamily(play);
    if (play.disposed || this.router.current !== play) return;
    if (play.identity.family === 'beatoraja') this.beatorajaSkinOptions.refreshBeatorajaPlaySkinOptions();
    else this.beatorajaSkinOptions.clear();
  }
 
  /**
   * Shows the select screen (`SelectRoute.showSelect`): at start-up, and on every way back to it. The decoded samples
   * of the play stay while the cursor is on a chart of its track, so another chart of it plays without decoding them
   * again; a focus on any other chart releases them (`AudioServicePreview.focus`).
   */
  private async showSelect(): Promise<void> {
    await this.selectRoute.showSelect();
    this.library.selectShown();
    // A RANDOM MIX run that just ended offers to save its course over the select screen.
    void this.courseRoute.offerRandomMixSave();
  }
 
  /**
   * Latches the replay-related GUI options for the play that is about to start and disables their controllers.
   * Replay options are per-play: the value in effect at song start governs the whole play, and mid-song changes
   * are rejected by keeping the controls disabled until {@link unlockReplayOptions} runs (result mounted or back
   * at select). The Options dialog disables its skin controls with them (`OptionsDialog.lockForPlay`).
   */
  private lockReplayOptionsForPlay(liveTempo = false, chartEntry?: LibraryChart): void {
    this.library.pauseBackgroundRefresh();
    this.replayAutoSave.latch(this.guiState.autoSaveReplay);
    this.leaderboard.lockForPlay(chartEntry);
    this.optionsDialog.lockForPlay(liveTempo);
  }
 
  /** Re-enables the replay option controllers, and the skin controls, once no play is in flight. */
  private unlockReplayOptions(): void {
    this.leaderboard.unlock();
    this.optionsDialog.unlockAfterPlay();
  }
 
  /**
   * A play option set from the Options dialog (or a hi-speed from the play): kept for every screen and play
   * ({@link playOptions}), and pushed to the select screen, on the stage or off it.
   */
  private setPlayOptions(changes: Partial<PlayOptions>): void {
    this.playOptions.update(changes);
    this.selectView?.setPlayOptions(changes);
  }
}