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

0% Statements 0/345
0% Branches 0/48
0% Functions 0/125
0% Lines 0/327

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 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { optionDefault } from '../../option-defaults.ts';
import { selectBinding, type PaneBinding } from '../../pane-controls.ts';
// The Options dialog's Play options folder, split into pages, the Replay / ghost folder on its last page, the View
// folder and the Select folder. They are built with the dialog as `this` (`OptionsDialog`).
import {
  DIFFICULTY_FILTER_CYCLE,
  CLASSIC_HI_SPEED_STEPS,
  NORMAL_HI_SPEED_GREEN_NUMBERS,
  snapClassicHiSpeed,
  HISPEED_MAX,
  HISPEED_MIN,
  HISPEED_STEP,
  JUDGE_POSITION_LIMIT,
  KEYS_FILTER_CYCLE,
  parseRankingScoreTarget,
  PLAY_OPTION_CHOICES,
  resolveScoreTarget,
  SCORE_TARGET_IDS,
  SORT_CYCLE,
  type PlayOptions,
} from '@be-music/player-scene-model';
import { parseReplay } from '@be-music/player-engine/replay';
import { storeReplayView } from '../../replay-view-settings.ts';
import type { OptionsDialog } from './index.ts';
import { buildLR2ManiaRows } from './lr2-mania.ts';
import { resolveBPMGuideKinds } from '../../app/play-scene-options.ts';
import {
  bottomShiftableGaugeItems,
  crazyNotesItems,
  gaugeChoices,
  laneOptionItems,
  practiceGaugeItems,
} from './play-option-items.ts';
/**
 * How the player plays: auto play, hi-speed, gauge, lane options and assists.
 *
 * Play options — the playMode / chartOptions / assists / judge / gauge settings that get recorded into the replay.
 * Two-way synced with the LR2 select scene's PLAY OPTION panel where a counterpart exists (the panel pushes user
 * edits back through `onPlayOptionsChange`; these controllers push through `setPlayOptions`). Most are latched at
 * song start and DISABLED during a play. The ones a play takes live (hi-speed, the covers and LIFT, the judge timing
 * and CONSTANT visibility) and the select screen's sort and filters, which a play does not read, stay enabled.
 *
 * The options are many, so the folder splits them into pages. The ones that only change what the lanes show go to the
 * View folder, split into pages of its own, and the select screen's sort and filters to the Select folder. Which page
 * each goes on is `options-layout.json`'s; each is placed by its id (`OptionsDialog.place`).
 */
export function buildPlayOptionsFolder(this: OptionsDialog): void {
  // The judge ruleset, above the pages: every judge rule (windows, note selection, empty POOR, long notes, gauge, score —
  // see docs/replay.md) and the choices of several options on the pages follow it. No skin has a counterpart.
  this.trackPlayOption(
    selectBinding(this.place('judgeRuleset'), this.guiState, 'judgeRuleset', 'Judgment windows', {
      LR2: 'lr2',
      beatoraja: 'beatoraja',
      '????': '____',
      plugout: 'plugout',
    }).on('change', () => {
      this.refreshRulesetChoices();
      this.deps.refreshSelectRecords();
    }),
  );
  // What the options picked do to a play's record, from the resolver a finished play's record goes through.
  this.recordConsequenceController = this.place('recordConsequence').addBinding(this.recordConsequence, 'text', {
    label: 'Record kept',
    readonly: true,
  });
  const trackPlayOption = (controller: PaneBinding): PaneBinding => this.trackPlayOption(controller);
  trackPlayOption(
    this.place('autoPlay')
      .addBinding(this.guiState, 'autoPlay', { label: 'Auto play' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ autoPlay: value });
      }),
  );
  this.gaugeController = selectBinding(
    this.place('gauge'),
    this.guiState,
    'gauge',
    'Gauge',
    gaugeChoices(this.guiState),
  );
  trackPlayOption(
    this.gaugeController.on('change', ({ value }) => {
      this.setPlayOptions({ gauge1P: value });
    }),
  );
  this.judgeAlgorithmController = selectBinding(
    this.place('judgeAlgorithm'),
    this.guiState,
    'judgeAlgorithm',
    'Judge algorithm',
    {
      Combo: 'combo',
      Duration: 'duration',
      Lowest: 'lowest',
    },
  );
  trackPlayOption(
    this.judgeAlgorithmController.on('change', ({ value }) => this.setPlayOptions({ judgeAlgorithm: value })),
  );
  for (const side of ['1P', '2P'] as const) {
    const key = `random${side}` as const;
    const controller = selectBinding(
      this.place(key),
      this.guiState,
      key,
      `Random ${side}`,
      Object.fromEntries(laneOptionItems(this.guiState.judgeRuleset).map((item) => [item.text, item.value])),
    );
    if (side === '1P') this.random1PController = controller;
    else this.random2PController = controller;
    trackPlayOption(
      controller.on('change', ({ value }) => {
        this.setPlayOptions({ [key]: value });
        this.refreshRulesetChoices();
      }),
    );
  }
  trackPlayOption(
    this.place('hRandomThresholdBPM')
      .addBinding(this.guiState, 'hRandomThresholdBPM', {
        label: 'H-RANDOM threshold BPM (beatoraja)',
        min: 1,
        max: 1000,
        step: 1,
      })
      .on('change', ({ value }) => this.setPlayOptions({ hRandomThresholdBPM: value })),
  );
  for (const side of ['1P', '2P'] as const) {
    const key = `lr2RandomScratch${side}` as const;
    trackPlayOption(
      this.place(key)
        .addBinding(this.guiState, key, { label: `Include scratch ${side} (LR2)` })
        .on('change', ({ value }) => this.setPlayOptions({ [key]: value })),
    );
  }
  for (const side of ['1P', '2P'] as const) {
    const key = `randomFixedLane${side}` as const;
    trackPlayOption(
      this.place(key)
        .addBinding(this.guiState, key, {
          label: `Fixed key ${side} (LR2; 0=default)`,
          min: 0,
          max: 9,
          step: 1,
        })
        .on('change', ({ value }) => this.setPlayOptions({ [key]: value })),
    );
  }
  for (const side of ['1P', '2P'] as const) {
    const key = `randomSeed${side}` as const;
    const controller = this.place(key)
      .addBinding(this.guiState, key, { label: `Seed ${side} (-1=random)` })
      .on('change', ({ value }) => this.setPlayOptions({ [key]: value }));
    this.trackPlayOption(controller);
    if (side === '1P') this.randomSeed1PController = controller;
    else this.randomSeed2PController = controller;
  }
  this.sevenToNinePatternController = selectBinding(
    this.place('sevenToNinePattern'),
    this.guiState,
    'sevenToNinePattern',
    '7-to-9 (beatoraja)',
    {
      OFF: 0,
      'SC1 KEY2–8': 1,
      'SC1 KEY3–9': 2,
      'SC2 KEY3–9': 3,
      'SC8 KEY1–7': 4,
      'SC9 KEY1–7': 5,
      'SC9 KEY2–8': 6,
    },
  );
  trackPlayOption(
    this.sevenToNinePatternController.on('change', ({ value }) => this.setPlayOptions({ sevenToNinePattern: value })),
  );
  this.sevenToNineTypeController = selectBinding(
    this.place('sevenToNineType'),
    this.guiState,
    'sevenToNineType',
    '7-to-9 scratch',
    {
      Fixed: 0,
      'Avoid repeated hits': 1,
      Alternate: 2,
    },
  );
  trackPlayOption(
    this.sevenToNineTypeController.on('change', ({ value }) => this.setPlayOptions({ sevenToNineType: value })),
  );
  const reuse = this.place('reuseArrangement')
    .addButton({ title: 'Reuse previous arrangement' })
    .on('click', () => {
      const changes = this.deps.reusePreviousArrangement?.();
      if (changes) {
        this.setPlayOptions(changes);
        this.refreshPlayOptionControllers();
        this.setStatus('Previous arrangement selected for the same chart. Live input remains enabled.');
      } else this.setStatus('Play a chart with the current judgment rules first to retain its arrangement.');
    });
  const fresh = this.place('newArrangement')
    .addButton({ title: 'New arrangement' })
    .on('click', () => {
      this.deps.clearArrangement?.();
      // The menu's seeds too, which the saved settings keep.
      this.guiState.randomSeed1P = '-1';
      this.guiState.randomSeed2P = '-1';
      this.setPlayOptions({ randomSeed1P: '-1', randomSeed2P: '-1' });
      this.refreshPlayOptionControllers();
      this.setStatus('A new arrangement will be drawn for the next play.');
    });
  // Every ruleset reuses its own previous arrangement (#774) and seeds its lane randoms (#933).
  for (const controller of [reuse, fresh]) this.trackPlayOption(controller);
  trackPlayOption(
    selectBinding(this.place('bmsonTotalMode'), this.guiState, 'bmsonTotalMode', 'bmson TOTAL 0', {
      'Native compatibility': 'beatoraja',
      'No recovery (bmson spec)': 'spec',
    }).on('change', ({ value }) => this.setPlayOptions({ bmsonTotalMode: value })),
  );
  this.gaugeAutoShiftController = selectBinding(
    this.place('gaugeAutoShift'),
    this.guiState,
    'gaugeAutoShift',
    'Gauge auto-shift',
    {
      NONE: 'NONE',
      CONTINUE: 'CONTINUE',
      'SURVIVAL TO GROOVE': 'SURVIVAL_TO_GROOVE',
      'BEST CLEAR': 'BEST_CLEAR',
      'SELECT TO UNDER': 'SELECT_TO_UNDER',
    },
  );
  trackPlayOption(
    this.gaugeAutoShiftController.on('change', ({ value }) => this.setPlayOptions({ gaugeAutoShift: value })),
  );
  this.bottomShiftableGaugeController = selectBinding(
    this.place('bottomShiftableGauge'),
    this.guiState,
    'bottomShiftableGauge',
    'Lowest auto-shift gauge',
    bottomShiftableGaugeItems(this.guiState.judgeRuleset).map((item) => item.value),
  );
  trackPlayOption(
    this.bottomShiftableGaugeController.on('change', ({ value }) =>
      this.setPlayOptions({ bottomShiftableGauge: value }),
    ),
  );
  // LR2's mania chart generators: 0 is off, 10–100 the rate, as LR2's panel steps them. They build the chart before the
  // play, so they are locked during one.
  for (const [key, label] of [
    ['lr2AddNotes', 'ADD NOTES (LR2)'],
    ['lr2Loudness', 'LOUDNESS (LR2)'],
    ['lr2AddLongNotes', 'ADD LONGNOTES (LR2)'],
    ['lr2AddMines', 'ADD MINES (LR2)'],
  ] as const) {
    trackPlayOption(
      this.place(key)
        .addBinding(this.guiState, key, { label, min: 0, max: 100, step: 10 })
        .on('change', ({ value }) => this.setPlayOptions({ [key]: value })),
    );
  }
  this.scrollModifierController = selectBinding(
    this.place('scrollModifier'),
    this.guiState,
    'scrollModifier',
    'Scroll',
    {
      OFF: 'OFF',
      'REMOVE (beatoraja)': 'REMOVE',
      'ADD (beatoraja)': 'ADD',
      'SOFTLANDING LEVEL 1 (LR2)': 'SOFTLANDING-1',
      'SOFTLANDING LEVEL 2 (LR2)': 'SOFTLANDING-2',
    },
  );
  trackPlayOption(
    this.scrollModifierController.on('change', ({ value }) => {
      this.setPlayOptions({ scrollModifier: value });
      this.refreshRulesetChoices();
    }),
  );
  this.scrollSectionController = trackPlayOption(
    this.place('scrollSection')
      .addBinding(this.guiState, 'scrollSection', { label: 'Scroll section lines', min: 1, max: 1024, step: 1 })
      .on('change', ({ value }) => this.setPlayOptions({ scrollSection: value })),
  );
  this.scrollRateController = trackPlayOption(
    this.place('scrollRate')
      .addBinding(this.guiState, 'scrollRate', { label: 'Scroll rate', min: 0, max: 1, step: 0.01 })
      .on('change', ({ value }) => this.setPlayOptions({ scrollRate: value })),
  );
  // beatoraja's mine modifiers. nanasigroove's ADDMINE is its own option below and replaces them while it is on.
  this.mineModifierController = selectBinding(this.place('mineModifier'), this.guiState, 'mineModifier', 'Mines', {
    OFF: 'OFF',
    'REMOVE (beatoraja)': 'REMOVE',
    'ADD RANDOM (beatoraja)': 'ADD_RANDOM',
    'ADD NEAR (beatoraja)': 'ADD_NEAR',
    'ADD ALL (beatoraja)': 'ADD_BLANK',
  });
  trackPlayOption(
    this.mineModifierController.on('change', ({ value }) => this.setPlayOptions({ mineModifier: value })),
  );
  this.refreshRulesetChoices();
  trackPlayOption(
    this.place('dpFlip')
      .addBinding(this.guiState, 'dpFlip', { label: 'DP flip' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ dpFlip: value });
      }),
  );
  trackPlayOption(
    this.place('autoScratch1P')
      .addBinding(this.guiState, 'autoScratch1P', { label: 'Auto scratch 1P' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ autoScratch1P: value });
      }),
  );
  trackPlayOption(
    this.place('autoScratch2P')
      .addBinding(this.guiState, 'autoScratch2P', { label: 'Auto scratch 2P' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ autoScratch2P: value });
      }),
  );
  // beatoraja's GUIDE SE: the sound set's sound for each judgment. Read as the play starts, when the sounds are decoded.
  trackPlayOption(
    this.place('guideSE')
      .addBinding(this.guiState, 'guideSE', { label: 'GUIDE SE (beatoraja)' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ guideSE: value });
      }),
  );
  // The PC edition's ANY KEY (#751), offered with the `____` judge rules (`refreshRulesetChoices`); saves no record.
  this.anyKeyController = trackPlayOption(
    this.place('anyKey').addBinding(this.guiState, 'anyKey', { label: 'ANY KEY (PC)' }),
  );
  this.longNoteModifierController = selectBinding(
    this.place('longNoteModifier'),
    this.guiState,
    'longNoteModifier',
    'Long notes',
    {
      OFF: 'OFF',
      'LEGACY NOTE (AC 34)': 'LEGACY',
      'LN REMOVE (beatoraja)': 'REMOVE',
      'ADD LN (beatoraja)': 'ADD_LN',
      'ADD CN (beatoraja)': 'ADD_CN',
      'ADD HCN (beatoraja)': 'ADD_HCN',
      'ADD ALL (beatoraja)': 'ADD_ALL',
    },
  );
  trackPlayOption(
    this.longNoteModifierController.on('change', ({ value }) => {
      this.setPlayOptions({ longNoteModifier: value });
      this.refreshRulesetChoices();
    }),
  );
  this.battleModeController = selectBinding(this.place('battleMode'), this.guiState, 'battleMode', 'Battle', {
    OFF: 'OFF',
    'SP TO DP': 'SP-TO-DP',
  });
  trackPlayOption(
    this.battleModeController.on('change', ({ value }) => {
      this.setPlayOptions({ battleMode: value });
      this.refreshRulesetChoices();
    }),
  );
  // Two-player play (LR2 BATTLE): the 2P player's gauge, and That-Which-Must-Not-Be-Named's M-RAN per player.
  this.gauge2PController = selectBinding(
    this.place('gauge2P'),
    this.guiState,
    'gauge2P',
    'Gauge 2P',
    gaugeChoices(this.guiState),
  );
  trackPlayOption(this.gauge2PController.on('change', ({ value }) => this.setPlayOptions({ gauge2P: value })));
  this.mRanControllers = (['mRan1P', 'mRan2P'] as const).map((key) =>
    trackPlayOption(
      this.place(key)
        .addBinding(this.guiState, key, { label: key === 'mRan1P' ? 'M-RAN 1P' : 'M-RAN 2P' })
        .on('change', ({ value }) => this.setPlayOptions({ [key]: value })),
    ),
  );
  // LR2 keeps the scratch through a hidden command at decide (`randSC`, buttons 12 + 13); the dialog has a switch instead.
  this.dBattleScratchController = trackPlayOption(
    this.place('dBattleScratch')
      .addBinding(this.guiState, 'dBattleScratch', { label: 'D-BATTLE scratch (LR2)' })
      .on('change', ({ value }) => this.setPlayOptions({ dBattleScratch: value })),
  );
  this.lr2ExtraModeController = trackPlayOption(
    this.place('lr2ExtraMode')
      .addBinding(this.guiState, 'lr2ExtraMode', { label: 'EXTRA MODE (LR2)' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ lr2ExtraMode: value });
        this.refreshRulesetChoices();
      }),
  );
  this.lr2ExtraLevelController = selectBinding(
    this.place('lr2ExtraLevel'),
    this.guiState,
    'lr2ExtraLevel',
    'EXTRA minimum level (LR2)',
    {
      'LEVEL 1': 0,
      'LEVEL 2': 1,
      'LEVEL 3': 2,
    },
  );
  trackPlayOption(
    this.lr2ExtraLevelController.on('change', ({ value }) => this.setPlayOptions({ lr2ExtraLevel: value })),
  );
  this.longNoteModeController = selectBinding(
    this.place('longNoteMode'),
    this.guiState,
    'longNoteMode',
    'LN MODE (beatoraja)',
    {
      'LONG NOTE': 'LN',
      'CHARGE NOTE': 'CN',
      'HELL CHARGE NOTE': 'HCN',
    },
  );
  trackPlayOption(
    this.longNoteModeController.on('change', ({ value }) => this.setPlayOptions({ longNoteMode: value })),
  );
  // LR2's mania option GAMBOL: part of LR2's judge rules, so it is offered under them only.
  this.lr2GambolController = trackPlayOption(
    selectBinding(this.place('lr2Gambol'), this.guiState, 'lr2Gambol', 'GAMBOL (LR2)', {
      OFF: 0,
      'LEVEL 1': 1,
      'LEVEL 2': 2,
    }).on('change', ({ value }) => this.setPlayOptions({ lr2Gambol: value })),
  );
  this.customJudgeController = trackPlayOption(
    this.place('customJudge')
      .addBinding(this.guiState, 'customJudge', { label: 'CUSTOM JUDGE (beatoraja)' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ customJudge: value });
        this.refreshRulesetChoices();
      }),
  );
  // PlayerConfig.validate: PGREAT 25..400 %, every other rate 0..400 %.
  this.customJudgeRateControllers = (
    [
      ['customJudgeKeyPerfectGreat', 'Key PGREAT %', 25],
      ['customJudgeKeyGreat', 'Key GREAT %', 0],
      ['customJudgeKeyGood', 'Key GOOD %', 0],
      ['customJudgeScratchPerfectGreat', 'Scratch PGREAT %', 25],
      ['customJudgeScratchGreat', 'Scratch GREAT %', 0],
      ['customJudgeScratchGood', 'Scratch GOOD %', 0],
      ['customJudgeLongNoteMargin', 'LN margin %', 0],
    ] as const
  ).map(([key, label, min]) =>
    trackPlayOption(
      this.place(key)
        .addBinding(this.guiState, key, { label, min, max: 400, step: 1 })
        .on('change', ({ value }) => this.setPlayOptions({ [key]: value })),
    ),
  );
  // PRACTICE (beatoraja's PracticeConfiguration), under every ruleset (#933): the bars to loop are picked on the chart's
  // score as the chart starts (`practice-bars.ts`); a 0 JUDGERANK / TOTAL is the chart's.
  this.practiceControllers = [
    trackPlayOption(
      this.place('practice')
        .addBinding(this.guiState, 'practice', { label: 'PRACTICE' })
        .on('change', ({ value }) => {
          this.setPlayOptions({ practice: value });
          this.refreshRulesetChoices();
        }),
    ),
  ];
  const addPracticeNumbers = (
    entries: readonly (readonly [
      'practiceStartGauge' | 'practiceJudgeRank' | 'practiceTotal' | 'practiceRestBefore' | 'practiceRestAfter',
      string,
      number,
      number,
      number,
    ])[],
  ): void => {
    for (const [key, label, min, max, step] of entries) {
      this.practiceControllers.push(
        trackPlayOption(
          this.place(key)
            .addBinding(this.guiState, key, { label, min, max, step })
            .on('change', ({ value }) => this.setPlayOptions({ [key]: value })),
        ),
      );
    }
  };
  addPracticeNumbers([
    ['practiceStartGauge', 'GAUGE VALUE', 1, 120, 1],
    ['practiceJudgeRank', 'JUDGERANK (0 = chart)', 0, 400, 1],
    ['practiceTotal', 'TOTAL (0 = chart)', 0, 5000, 1],
    ['practiceRestBefore', 'REST BEFORE (bars)', 0, 8, 1],
    ['practiceRestAfter', 'REST AFTER (bars)', 0, 8, 1],
  ]);
  // A long note held into the bars from before them is kept and played from its head (a Be-Music extension).
  this.practiceControllers.push(
    trackPlayOption(
      this.place('practiceCarriedLongNotes')
        .addBinding(this.guiState, 'practiceCarriedLongNotes', { label: 'Keep LNs held into the bars' })
        .on('change', ({ value }) => this.setPlayOptions({ practiceCarriedLongNotes: value })),
    ),
  );
  // The judge ruleset's own gauges, then the other sources' (ADR 0019); refreshRulesetChoices relists them when the
  // ruleset changes.
  const practiceGauge = selectBinding(
    this.place('practiceGauge'),
    this.guiState,
    'practiceGauge',
    'GAUGE TYPE',
    Object.fromEntries(
      practiceGaugeItems(this.guiState.judgeRuleset, this.guiState.practiceGauge).map((item) => [
        item.text,
        item.value,
      ]),
    ),
  );
  this.practiceGaugeController = practiceGauge;
  trackPlayOption(
    practiceGauge.on('change', ({ value }) => {
      this.setPlayOptions({ practiceGauge: value });
      // GAUGE CATEGORY follows a beatoraja gauge.
      this.refreshRulesetChoices();
    }),
  );
  const practiceCategory = selectBinding(
    this.place('practiceGaugeCategory'),
    this.guiState,
    'practiceGaugeCategory',
    'GAUGE CATEGORY',
    {
      'Play mode': 'MODE',
      FIVEKEYS: 'FIVEKEYS',
      SEVENKEYS: 'SEVENKEYS',
      PMS: 'PMS',
      KEYBOARD: 'KEYBOARD',
      LR2: 'LR2',
    },
  );
  trackPlayOption(practiceCategory.on('change', ({ value }) => this.setPlayOptions({ practiceGaugeCategory: value })));
  this.practiceGaugeCategoryController = practiceCategory;
  // JUDGERANK and TOTAL, after GAUGE VALUE.
  this.practiceJudgeRankAndTotalControllers = this.practiceControllers.slice(2, 4);
  this.practiceControllers.push(practiceGauge);
  this.extraNoteDepthController = trackPlayOption(
    this.place('extraNoteDepth')
      .addBinding(this.guiState, 'extraNoteDepth', { label: 'EXTRA depth (beatoraja)', min: 0, max: 100, step: 1 })
      .on('change', ({ value }) => this.setPlayOptions({ extraNoteDepth: value })),
  );
  this.extraNoteScratchController = trackPlayOption(
    this.place('extraNoteScratch')
      .addBinding(this.guiState, 'extraNoteScratch', { label: 'EXTRA scratch (beatoraja)' })
      .on('change', ({ value }) => this.setPlayOptions({ extraNoteScratch: value })),
  );
  this.longNoteRateController = trackPlayOption(
    this.place('longNoteRate')
      .addBinding(this.guiState, 'longNoteRate', {
        label: 'Long-note add rate (beatoraja)',
        min: 0,
        max: 1,
        step: 0.01,
      })
      .on('change', ({ value }) => this.setPlayOptions({ longNoteRate: value })),
  );
  // nanasigroove's CRAZY gameplay options (#1177, #1184, #1185), which no LR2 or beatoraja option matches, kept apart
  // in their own folder at the end of the Modifiers page. A chart's own `774:CRAZY_*` / `774:NOTES_*` wins within each
  // family.
  trackPlayOption(
    selectBinding(this.place('crazyJudge'), this.guiState, 'crazyJudge', 'GOOD2BAD / GREAT2BAD', {
      OFF: 'OFF',
      GOOD2BAD: 'GOOD2BAD',
      GREAT2BAD: 'GREAT2BAD',
    }).on('change', ({ value }) => this.setPlayOptions({ crazyJudge: value })),
  );
  trackPlayOption(
    this.place('crazyHellJudge')
      .addBinding(this.guiState, 'crazyHellJudge', { label: 'HELLJUDGE' })
      .on('change', ({ value }) => this.setPlayOptions({ crazyHellJudge: value })),
  );
  trackPlayOption(
    this.place('crazyAddMine')
      .addBinding(this.guiState, 'crazyAddMine', { label: 'ADDMINE' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ crazyAddMine: value });
        this.refreshRulesetChoices();
      }),
  );
  // A course bar dims COPY and DBLCOPY (`refreshCourseBarChoices`).
  this.crazyNotesController = this.place('crazyNotes')
    .addBinding(this.guiState, 'crazyNotes', { label: 'NOTES', options: crazyNotesItems(false) })
    .on('change', ({ value }) => this.setPlayOptions({ crazyNotes: value }));
  trackPlayOption(this.crazyNotesController);
  // The built-in and LR2 select screens' sort and filters (an LR2 skin's buttons change them too); the list keeps
  // the bar under the cursor. A play does not read them, so they stay enabled during one.
  selectBinding(this.place('sort'), this.guiState, 'sort', 'Sort', [...SORT_CYCLE]).on('change', ({ value }) => {
    this.setPlayOptions({ sort: value });
  });
  selectBinding(this.place('keysFilter'), this.guiState, 'keysFilter', 'Key filter', [...KEYS_FILTER_CYCLE]).on(
    'change',
    ({ value }) => {
      this.setPlayOptions({ keysFilter: value });
    },
  );
  selectBinding(this.place('difficultyFilter'), this.guiState, 'difficultyFilter', 'Difficulty filter', [
    ...DIFFICULTY_FILTER_CYCLE,
  ]).on('change', ({ value }) => {
    this.setPlayOptions({ difficultyFilter: value });
  });
  this.hsFixController = selectBinding(
    this.place('hsFix'),
    this.guiState,
    'hsFix',
    'HS-FIX',
    PLAY_OPTION_CHOICES.hsFix!,
  );
  trackPlayOption(this.hsFixController.on('change', ({ value }) => this.setPlayOptions({ hsFix: value })));
  // beatoraja's WINDOW HOLD: a play takes START as held until its last note (#1131). Read as the play starts.
  trackPlayOption(
    this.place('windowHold')
      .addBinding(this.guiState, 'windowHold', { label: 'WINDOW HOLD (beatoraja)' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ windowHold: value });
      }),
  );
  trackPlayOption(
    selectBinding(this.place('displayAreaInfo'), this.guiState, 'displayAreaInfo', 'Display area info', {
      OFF: 'OFF',
      ON: 'ON',
      'SUDDEN+ ONLY': 'SUDDEN_ONLY',
      'HID+/LIFT ONLY': 'HIDDEN_LIFT_ONLY',
    }).on('change', ({ value }) => {
      this.setPlayOptions({ displayAreaInfo: value });
    }),
  );
  // SUDDEN+ / HIDDEN+, the switch and the height stay enabled during a play and move its covers live, as LIFT does.
  const setCovers = (changes: Partial<PlayOptions>): void => this.setCoverOptions(changes);
  for (const key of ['hiddenSudden1P', 'hiddenSudden2P'] as const) {
    selectBinding(
      this.place(key),
      this.guiState,
      key,
      key === 'hiddenSudden1P' ? 'Effect 1P' : 'Effect 2P',
      PLAY_OPTION_CHOICES[key]!,
    ).on('change', ({ value }) => setCovers({ [key]: value }));
  }
  this.place('laneCover')
    .addBinding(this.guiState, 'laneCover', { label: 'Lane cover' })
    .on('change', ({ value }) => setCovers({ laneCover: value }));
  this.place('shutter')
    .addBinding(this.guiState, 'shutter', { label: 'Cover height', min: 0, max: 1, step: 0.01 })
    .on('change', ({ value }) => setCovers({ shutter: value }));
  // BGA, its frame size and the score graph: LR2's select buttons 72, 73 and 70, offered here for every skin.
  trackPlayOption(
    selectBinding(this.place('bga'), this.guiState, 'bga', 'BGA', {
      OFF: 'OFF',
      ON: 'ON',
      'AUTOPLAY ONLY': 'AUTOPLAY_ONLY',
    }).on('change', ({ value }) => this.setPlayOptions({ bga: value })),
  );
  trackPlayOption(
    selectBinding(this.place('bgaSize'), this.guiState, 'bgaSize', 'BGA size', {
      NORMAL: 'NORMAL',
      EXTEND: 'EXTEND',
    }).on('change', ({ value }) => this.setPlayOptions({ bgaSize: value })),
  );
  trackPlayOption(
    this.place('scoreGraph')
      .addBinding(this.guiState, 'scoreGraph', { label: 'Score graph' })
      .on('change', ({ value }) => this.setPlayOptions({ scoreGraph: value })),
  );
  // The guides on the lanes. Guide: BPM is beatoraja's BPM GUIDE, a play option (a light assist on a chart whose BPM
  // changes), read as a play starts. STOP, SCROLL and SPEED are viewing preferences: live, and they change no record.
  trackPlayOption(
    this.place('bpmGuide')
      .addBinding(this.guiState, 'bpmGuide', { label: 'Guide: BPM' })
      .on('change', ({ value }) => this.setPlayOptions({ bpmGuide: value })),
  );
  for (const [key, label] of [
    ['guideStop', 'Guide: STOP'],
    ['guideScroll', 'Guide: SCROLL'],
    ['guideSpeed', 'Guide: SPEED'],
  ] as const) {
    this.place(key)
      .addBinding(this.guiState, key, { label })
      .on('change', ({ value }) => {
        this.guiState[key] = value;
        this.gameplayView?.setBPMGuideKinds(resolveBPMGuideKinds(this.guiState));
      });
  }
  trackPlayOption(
    this.place('bpmChangeWarning')
      .addBinding(this.guiState, 'bpmChangeWarning', { label: 'BPM change warning (AC)' })
      .on('change', ({ value }) => this.setPlayOptions({ bpmChangeWarning: value })),
  );
  for (const side of ['1P', '2P'] as const) {
    const heightKey = side === '1P' ? 'lift1P' : 'lift2P';
    const enabledKey = side === '1P' ? 'liftOn1P' : 'liftOn2P';
    this.place(enabledKey)
      .addBinding(this.guiState, enabledKey, { label: `LIFT ${side} (beatoraja)` })
      .on('change', ({ value }) => {
        this.setPlayOptions({ [enabledKey]: value });
        this.gameplayView?.controller.dispatch({
          type: 'cover',
          command: { type: 'cover-set', covers: [{ side, liftOn: value, lift: this.guiState[heightKey] }], side },
        });
      });
    this.place(heightKey)
      .addBinding(this.guiState, heightKey, { label: `LIFT height ${side}`, min: 0, max: 1, step: 0.001 })
      .on('change', ({ value }) => {
        this.setPlayOptions({ [heightKey]: value });
        this.gameplayView?.controller.dispatch({
          type: 'cover',
          command: { type: 'cover-set', covers: [{ side, lift: value }], side },
        });
      });
  }
  trackPlayOption(
    this.place('visualConstant')
      .addBinding(this.guiState, 'visualConstant', { label: 'Visual CONSTANT (beatoraja)' })
      .on('change', ({ value }) => this.setPlayOptions({ visualConstant: value })),
  );
  this.place('noteDurationMs')
    .addBinding(this.guiState, 'noteDurationMs', { label: 'Note duration (ms)', min: 1, max: 10000, step: 1 })
    .on('change', ({ value }) => {
      this.setPlayOptions({ noteDurationMs: value });
      this.gameplayView?.controller.dispatch({ type: 'constant-visibility', durationMs: value });
    });
  this.place('constantFadeMs')
    .addBinding(this.guiState, 'constantFadeMs', { label: 'CONSTANT fade (ms)', min: -1000, max: 1000, step: 1 })
    .on('change', ({ value }) => {
      this.setPlayOptions({ constantFadeMs: value });
      this.gameplayView?.controller.dispatch({ type: 'constant-visibility', fadeMs: value });
    });
  this.judgeTimingAutoAdjustController = trackPlayOption(
    selectBinding(this.place('judgeTimingAutoAdjust'), this.guiState, 'judgeTimingAutoAdjust', 'Auto judge timing', {
      OFF: 'OFF',
      beatoraja: 'BEATORAJA',
      'LR2 ON': 'LR2-ON',
      'LR2 SILENT': 'LR2-SILENT',
    }).on('change', ({ value }) => this.setPlayOptions({ judgeTimingAutoAdjust: value })),
  );
  this.judgeTimingController = this.place('judgeTimingMs')
    .addBinding(this.guiState, 'judgeTimingMs', { label: 'Judge timing (ms)', min: -500, max: 500, step: 1 })
    .on('change', ({ value }) => {
      this.setPlayOptions({ judgeTimingMs: value });
      this.gameplayView?.setJudgeTimingMs(value);
    });
  const state = this.guiState;
  const defaultNormalLevel = optionDefault<number>('normalHiSpeedLevel');
  const normal = {
    get enabled() {
      return state.normalHiSpeedLevel > 0;
    },
    set enabled(value: boolean) {
      state.normalHiSpeedLevel = value ? state.normalHiSpeedLevel || defaultNormalLevel : 0;
    },
    get level() {
      return state.normalHiSpeedLevel || defaultNormalLevel;
    },
    set level(value: number) {
      if (state.normalHiSpeedLevel > 0) state.normalHiSpeedLevel = value;
    },
  };
  this.normalHiSpeedController = trackPlayOption(
    this.place('normalHiSpeed')
      .addBinding(normal, 'enabled', { label: 'Normal HI-SPEED (AC 32 measured)' })
      .on('change', ({ value }) => {
        if (value) {
          state.classicHiSpeed = false;
          state.hsFix = 'OFF';
        }
        this.setPlayOptions({
          normalHiSpeedLevel: state.normalHiSpeedLevel,
          ...(value ? { classicHiSpeed: false, hsFix: 'OFF' } : {}),
        });
        this.refreshRulesetChoices();
        this.refreshPlayOptionControllers();
      }),
  );
  this.normalHiSpeedLevelController = trackPlayOption(
    selectBinding(
      this.place('normalHiSpeedLevel'),
      normal,
      'level',
      'Normal HS level',
      NORMAL_HI_SPEED_GREEN_NUMBERS.map((_, index) => index + 1),
    ).on('change', ({ value }) => this.setPlayOptions({ normalHiSpeedLevel: value })),
  );
  this.fixedDisplayAreaController = trackPlayOption(
    this.place('fixedDisplayArea')
      .addBinding(this.guiState, 'fixedDisplayArea', { label: 'Fixed display area (AC 34)' })
      .on('change', ({ value }) => this.setPlayOptions({ fixedDisplayArea: value })),
  );
  this.floatingHiSpeedController = trackPlayOption(
    this.place('floatingHiSpeed')
      .addBinding(this.guiState, 'floatingHiSpeed', { label: 'FLOATING HI-SPEED (AC 32 measured)' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ floatingHiSpeed: value, ...(value ? { hsFix: 'OFF' } : {}) });
        this.refreshRulesetChoices();
        this.refreshPlayOptionControllers();
      }),
  );
  const remember = (value: number): void => this.deps.rememberHiSpeed(value, 'menu');
  this.floatingSpeedController = this.place('floatingSpeed').addBinding(
    hiSpeedControl(this.guiState, () => this.guiState.floatingHiSpeed, onGrid(0.01), remember),
    'hiSpeed',
    { label: 'Floating speed', min: 0.5, max: 10, step: 0.01 },
  );
  this.classicHiSpeedController = trackPlayOption(
    this.place('classicHiSpeed')
      .addBinding(this.guiState, 'classicHiSpeed', { label: 'CLASSIC HI-SPEED' })
      .on('change', ({ value }) => {
        this.setPlayOptions({ classicHiSpeed: value, ...(value ? { hsFix: 'OFF', normalHiSpeedLevel: 0 } : {}) });
        if (value) {
          this.guiState.hsFix = 'OFF';
          this.guiState.normalHiSpeedLevel = 0;
          this.deps.rememberHiSpeed(snapClassicHiSpeed(this.guiState.hiSpeed)!, 'menu');
        }
        this.refreshRulesetChoices();
        this.refreshPlayOptionControllers();
      }),
  );
  this.classicSpeedController = selectBinding(
    this.place('classicSpeed'),
    hiSpeedControl(
      this.guiState,
      () => this.guiState.classicHiSpeed,
      (value) => snapClassicHiSpeed(value) ?? CLASSIC_HI_SPEED_STEPS[0]!,
      remember,
    ),
    'hiSpeed',
    'Classic speed',
    CLASSIC_HI_SPEED_STEPS,
  );
  // Hi-speed — the same range and step as the in-game `ArrowUp` / `ArrowDown` keys. Unlike the options above it is
  // visual only, so it stays enabled during a play and applies to it live.
  const regular = (): boolean =>
    !this.guiState.classicHiSpeed && !this.guiState.floatingHiSpeed && !(this.guiState.normalHiSpeedLevel > 0);
  this.hiSpeedController = this.place('hiSpeed').addBinding(
    hiSpeedControl(this.guiState, regular, onGrid(HISPEED_STEP), remember),
    'hiSpeed',
    { label: 'Hi-speed', min: HISPEED_MIN, max: HISPEED_MAX, step: HISPEED_STEP },
  );
  buildNoteDisplayRows.call(this);
  buildLR2ManiaRows.call(this);
  this.refreshRulesetChoices();
}
 
/**
 * The View folder's rows about how the lanes draw: AC 34's lane brightness and judge area, mark processed notes, and
 * the chart's invisible notes. They apply to a running play live.
 */
function buildNoteDisplayRows(this: OptionsDialog): void {
  // AC 34's detail options. Live: the views read both at each frame.
  this.place('laneBrightness')
    .addBinding(this.guiState, 'laneBrightness', { label: 'Lane brightness (AC)', min: 0, max: 100, step: 10 })
    .on('change', ({ value }) => this.setPlayOptions({ laneBrightness: value }));
  // The built-in skins' judge detail and judgment counts. AC 34 lists the timing display, its keys / scratch split and
  // the realtime judgment counts; a beatoraja skin has the first and the last as its own options.
  selectBinding(this.place('judgeDetail'), this.guiState, 'judgeDetail', 'Judge detail (built-in skins)', {
    OFF: 'OFF',
    'FAST / SLOW': 'FAST_SLOW',
    '±ms': 'MS',
  }).on('change', ({ value }) => this.setPlayOptions({ judgeDetail: value }));
  this.place('judgeDetailSplit')
    .addBinding(this.guiState, 'judgeDetailSplit', { label: 'Judge detail: keys and scratch apart' })
    .on('change', ({ value }) => this.setPlayOptions({ judgeDetailSplit: value }));
  this.place('judgeCounts')
    .addBinding(this.guiState, 'judgeCounts', { label: 'Judgment counts (built-in skins)' })
    .on('change', ({ value }) => this.setPlayOptions({ judgeCounts: value }));
  // The built-in skins' judgment and combo, moved up (-) or down (+) the lanes. LR2 and beatoraja skins place their own.
  this.place('judgePosition')
    .addBinding(this.guiState, 'judgePosition', {
      label: 'Judgment position (built-in skins, %)',
      min: -JUDGE_POSITION_LIMIT,
      max: JUDGE_POSITION_LIMIT,
      step: 5,
    })
    .on('change', ({ value }) => this.setPlayOptions({ judgePosition: value }));
  selectBinding(this.place('judgeDisplay'), this.guiState, 'judgeDisplay', 'Judgment display (AC)', {
    'Skin default': 'SKIN',
    OFF: 'OFF',
  }).on('change', ({ value }) => this.setPlayOptions({ judgeDisplay: value }));
  // beatoraja's judge area and mark processed note. Live: the playfield reads both at each frame.
  this.place('showJudgeArea')
    .addBinding(this.guiState, 'showJudgeArea', { label: 'Show judge area (beatoraja)' })
    .on('change', ({ value }) => this.setPlayOptions({ showJudgeArea: value }));
  this.place('markProcessedNotes')
    .addBinding(this.guiState, 'markProcessedNotes', { label: 'Mark processed notes (beatoraja)' })
    .on('change', ({ value }) => this.setPlayOptions({ markProcessedNotes: value }));
  // AC 34's オートスクラッチ表示. Live: the playfield reads the option at each frame.
  selectBinding(this.place('autoScratchNotes'), this.guiState, 'autoScratchNotes', 'Auto scratch notes (AC)', {
    Show: 'SHOW',
    Hide: 'HIDE',
  }).on('change', ({ value }) => this.setPlayOptions({ autoScratchNotes: value }));
  // Chart-authoring overlay — paints invisible / keysound notes (BMS channels `3x` / `4x`) as thin green bars in their
  // playable lane. Live: the gameplay view always extracts the invisible notes and preloads the green sprite, so the
  // flag flips the per-frame render branch on the very next paint.
  this.place('showInvisibleNotes')
    .addBinding(this.guiState, 'showInvisibleNotes', { label: 'Show invisible notes' })
    .on('change', ({ value }) => {
      this.guiState.showInvisibleNotes = value;
      this.gameplayView?.setShowInvisibleNotes(value);
    });
}
/**
 * Replay / ghost: which of what a replay recorded the player seeing a replay shows (the tempo, the hi-speed,
 * SUDDEN+ / HIDDEN+ and LIFT), the rest staying the player's own; and the ghost shown beside a play. Read when a play
 * starts, so disabled during one.
 */
export function buildReplayViewFolder(this: OptionsDialog): void {
  const remember = () => storeReplayView(this.guiState.replayView);
  for (const [key, id, label] of [
    ['tempo', 'replayViewTempo', 'Tempo'],
    ['hiSpeed', 'replayViewHiSpeed', 'Hi-speed'],
    ['covers', 'replayViewCovers', 'SUDDEN+ / HIDDEN+'],
    ['lift', 'replayViewLift', 'LIFT'],
  ] as const) {
    this.trackPlayOption(this.place(id).addBinding(this.guiState.replayView, key, { label }).on('change', remember));
  }
  // The ghost with the play (`services/ghost.ts`): which replay it plays and how it shows. Disabled during a play like
  // the other options, and on a course bar; "Ghost status" says whether the bar under the cursor would show it.
  // The score graph's fixed target, in beatoraja's names. It paces a play that runs no ghost; live.
  selectBinding(
    this.place('scoreTarget'),
    this.guiState,
    'scoreTarget',
    'Target (beatoraja)',
    Object.fromEntries(SCORE_TARGET_IDS.map((id) => [scoreTargetLabel(id), id])),
  ).on('change', ({ value }) => this.setPlayOptions({ scoreTarget: value }));
  // The rate the SCORE RATE target paces towards (beatoraja's `RATE_<n>`); live.
  this.place('scoreTargetRate')
    .addBinding(this.guiState, 'scoreTargetRate', { label: 'Target score rate (%)', min: 0, max: 100, step: 0.5 })
    .on('change', ({ value }) => this.setPlayOptions({ scoreTargetRate: value }));
  const refresh = () => this.refreshGhostAvailability();
  this.ghostController = selectBinding(this.place('ghost'), this.guiState, 'ghost', 'Ghost', {
    OFF: 'OFF',
    'OWN BEST': 'OWN_BEST',
    'REPLAY SLOT 1': 'REPLAY_SLOT_1',
    'REPLAY SLOT 2': 'REPLAY_SLOT_2',
    'REPLAY SLOT 3': 'REPLAY_SLOT_3',
    'REPLAY SLOT 4': 'REPLAY_SLOT_4',
    'LEADERBOARD TOP': 'LEADERBOARD_TOP',
    'REPLAY FILE': 'REPLAY_FILE',
  });
  this.ghostController.on('change', refresh);
  this.ghostModeController = selectBinding(this.place('ghostMode'), this.guiState, 'ghostMode', 'Ghost mode', {
    'SECOND PLAYFIELD': 'PLAYFIELD',
    PACEMAKER: 'PACEMAKER',
    'PACEMAKER + LANES': 'LANE_OVERLAY',
  });
  this.ghostModeController.on('change', refresh);
  this.ghostStatusController = this.place('ghostStatus').addBinding(this.ghostStatus, 'text', {
    label: 'Ghost status',
    readonly: true,
  });
  const fileButton = this.place('ghostReplayFile').addButton({ title: 'Ghost replay file…' });
  fileButton.on('click', () => {
    void pickReplayFile().then(async (file) => {
      if (file === undefined) return;
      try {
        this.deps.ghostReplayFile.set(parseReplay(await file.text()), file.name);
        fileButton.title = `Ghost file: ${file.name}`;
        this.setStatus(`Ghost replay file: ${file.name}`);
      } catch (error) {
        this.setStatus(`Ghost replay file could not be read: ${(error as Error).message}`);
      }
      refresh();
    });
  });
  const menu = this;
  this.trackPlayOption({
    get disabled(): boolean {
      return menu.ghostLocked;
    },
    set disabled(locked: boolean) {
      menu.ghostLocked = locked;
      menu.refreshGhostAvailability();
    },
  });
  refresh();
}
 
/** Asks the player for one replay file (`*.bmplay.json`); `undefined` when none is picked. */
function pickReplayFile(): Promise<File | undefined> {
  return new Promise((resolve) => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json,application/json';
    input.addEventListener('change', () => resolve(input.files?.[0]), { once: true });
    input.addEventListener('cancel', () => resolve(undefined), { once: true });
    input.click();
  });
}
 
/**
 * The hi-speed as one of the menu's hi-speed controls binds it. The controls share the one hi-speed, which a play also
 * changes (its keys, a floating hi-speed following the covers), so each shows it on its own grid (`show`) and takes only
 * an edit made on it: `onEdit` runs, and the hi-speed changes, when the control sets a value other than the one it shows
 * while its mode is in use (`active`). A control left to write back its own rounding would undo the play's change — a
 * floating 2.2458 as 2.25 — or set another mode's hi-speed (a classic list's first step for a play's 2.1).
 */
export function hiSpeedControl(
  guiState: { hiSpeed: number },
  active: () => boolean,
  show: (value: number) => number,
  onEdit: (value: number) => void,
): { hiSpeed: number } {
  return {
    get hiSpeed(): number {
      return show(guiState.hiSpeed);
    },
    set hiSpeed(value: number) {
      if (!active() || value === show(guiState.hiSpeed)) return;
      guiState.hiSpeed = value;
      onEdit(value);
    },
  };
}
 
/** A value on the grid of `step`, as a slider of that step shows it. */
export function onGrid(step: number): (value: number) => number {
  return (value) => Math.round(Math.round(value / step) * step * 1000) / 1000;
}
 
/** A score target's name in the dialog: beatoraja's own, with SCORE RATE's rate left to its slider. */
export function scoreTargetLabel(id: PlayOptions['scoreTarget']): string {
  if (id === 'SCORE_RATE') return 'SCORE RATE';
  return parseRankingScoreTarget(id)?.label ?? resolveScoreTarget(id, { totalNotes: 1 })?.label ?? id;
}