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

73.15% Statements 278/380
64.94% Branches 163/251
72.8% Functions 83/114
78.28% Lines 256/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                                                                                                                4x     45x 45x       61x 61x 61x     4x                               62x   62x 62x   62x     62x 62x 62x 62x                         12x 12x                     38x 38x 38x       50x         5x     5x 5x                 4x     4x 4x       9x 9x 9x       9x 9x           53x 53x               2x 2x 2x         20x                   23x     23x   23x                   23x 23x 23x 23x 23x 23x 23x   23x 23x 23x                   23x 23x 23x 23x 23x 20x 23x 23x                 22x 3x 19x       52x     2x 2x 2x       23x 23x       52x                                 16x 16x       23x       2x 2x 2x 2x         5x 4x 1x 1x 1x 1x   3x 2x 2x 1x         1x         4x 4x 4x 4x         52x 52x 52x 52x   52x 52x       52x 52x 3x                     6x     49x 37x             37x   12x         52x                   12x 12x                             12x   52x 6x                                                                                                                                                   4x     4x 4x 4x 4x 4x 4x 4x                               4x 4x       4x 4x         8x     8x             3x                       26x     26x   26x             23x       4x       4x 4x 4x         8x         7x                                       12x 12x                           38x 38x 38x 38x 38x 38x 38x       2x 2x 2x 2x         19x 19x       82x     163x 163x                   42x 42x 42x 42x                       15x                     15x             15x 15x 15x 15x 7x 7x 8x                 8x                 8x   8x 8x 8x   15x               7x                               16x       8x 8x       16x 16x       16x 16x                       15x 15x 15x 8x     7x 7x     7x 7x 1x 7x                 7x 6x 6x           52x 52x                   17x 14x 13x             7x   7x     7x 11x 7x 11x 11x 11x 11x 11x 11x   7x                       13x 13x 5x 2x 5x 5x 6x   2x         11x 9x       12x 12x 12x 23x 23x       12x 12x 11x 11x 12x     11x 11x 11x 11x                 7x 7x 11x                   21x       40x                 40x   1x 1x 1x 1x   1x 1x 1x 1x             40x                         11x 11x 11x 11x       4x 4x      
import { CollapsiblePanelElement } from './collapsible-panel.ts';
import { repeat } from 'lit/directives/repeat.js';
import { optionLabel, splitOptionLabelSource } from './options/labels.ts';
import { html, nothing, render, type TemplateResult } from 'lit';
import { live } from 'lit/directives/live.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { skeletonTemplate } from '@be-music/service-web-theme/client';
import type { OptionDefaultValue, OptionRowKind } from './options/layout.ts';
// The controls of the player's Options dialog and the beatoraja Skin Config panel, drawn with Basecoat: a switch for a
// boolean, a select for a choice list, a slider with a number field for a number with a range, a text field, read-only
// monitors (text, a text area, an FPS graph), buttons, collapsible folders and tabs. A control binds `object[key]`: an
// edit writes it and runs the control's change handlers, and `refresh` shows it again after a write from elsewhere.
// Every control has `hidden` and `disabled`, which the play lock (`play-lock.ts`) sets, and `omitted`, which the dialog's
// layout (`options/layout.ts`) sets for a row it leaves off the dialog.
import {
  choiceIndex,
  constrainNumber,
  displayText,
  formatNumber,
  graphPoints,
  sliderFill,
  type OptionChoice,
} from './options-values.ts';
 
export type { OptionChoice };
 
/** A user's edit of a bound control, as it reaches the folders above it (`on('change')`). */
export interface OptionChangeEvent {
  readonly key: PropertyKey;
  readonly value: unknown;
}
 
/** How a binding shows and edits its value. */
export interface OptionBindingParams<T> {
  readonly label?: string;
  /** A choice list: the binding is a select. */
  readonly options?: readonly OptionChoice<T>[];
  readonly min?: number;
  readonly max?: number;
  readonly step?: number;
  /** A monitor: shows the value, refreshed every `interval` ms while it is on screen, and takes no edit. */
  readonly readonly?: boolean;
  /** A monitor of `rows` lines. */
  readonly multiline?: boolean;
  readonly rows?: number;
  /**
   * A multiline monitor whose value is still being read: while this returns true the text area holds one blank line,
   * the height a one-line value takes (it sizes to its content), and is `aria-busy`, with a shimmering line over it.
   */
  readonly busy?: () => boolean;
  /** A number monitor drawn as a graph of its last `bufferSize` samples, from `min` to `max`. */
  readonly view?: 'graph';
  readonly interval?: number;
  readonly bufferSize?: number;
}
 
let lastId = 0;
/** An id for a control's input, so its label points at it. */
function uniqueId(prefix: string): string {
  lastId += 1;
  return `${prefix}-${lastId}`;
}
 
function element<K extends keyof HTMLElementTagNameMap>(tag: K, className?: string): HTMLElementTagNameMap[K] {
  const node = document.createElement(tag);
  Eif (className !== undefined) node.className = className;
  return node;
}
 
const CHEVRON_ICON = html`<svg
  viewBox="0 0 24 24"
  fill="none"
  stroke="currentColor"
  stroke-width="2"
  stroke-linecap="round"
  stroke-linejoin="round"
  aria-hidden="true"
>
  <path d="m6 9 6 6 6-6" />
</svg>`;
 
/** One thing in the options: a control row, a button, a folder or a set of tabs. */
export class OptionRow {
  public readonly element: HTMLElement;
  protected parent: OptionContainer | undefined;
  protected language = 'en';
  private readonly localize: ((language: string) => void) | undefined;
  private disabledState = false;
  private unavailableState = false;
  private hiddenState: boolean;
  private omittedState = false;
 
  public constructor(element: HTMLElement, parent: OptionContainer | undefined, localize?: (language: string) => void) {
    this.element = element;
    this.parent = parent;
    this.localize = localize;
    this.hiddenState = element.hidden === true;
  }
 
  /** What it is, as the dialog's layout names it: a row added as content is an `element`. */
  public get kind(): OptionRowKind | 'folder' | 'tabs' {
    return 'element';
  }
 
  /** Hidden by the code, as the other options make it meaningless (a 2P option in a one-player play). */
  public get hidden(): boolean {
    return this.hiddenState;
  }
  public set hidden(value: boolean) {
    this.hiddenState = value;
    this.applyHidden();
  }
 
  /**
   * Left off the dialog by its layout (`"hidden": true` in `options-layout.json`): never shown, whatever {@link hidden}
   * says, and never found by the search. Its value and its handlers stay.
   */
  public get omitted(): boolean {
    return this.omittedState;
  }
  public set omitted(value: boolean) {
    this.omittedState = value;
    this.element.toggleAttribute('data-option-omitted', value);
    this.applyHidden();
  }
 
  private applyHidden(): void {
    this.element.hidden = this.hiddenState || this.omittedState;
  }
 
  /** Disables every input, select and button in it; a disabled row is dimmed. A play's lock sets it. */
  public get disabled(): boolean {
    return this.disabledState;
  }
  public set disabled(value: boolean) {
    this.disabledState = value;
    this.applyDisabled();
  }
 
  /**
   * Whether the other options make it meaningless (a hi-speed mode's own speed while another mode is on): it stays in
   * place, dimmed and disabled like a {@link disabled} row, so the options never move under the player. Apart from
   * {@link disabled}, so a play's lock and this never undo each other.
   */
  public get unavailable(): boolean {
    return this.unavailableState;
  }
  public set unavailable(value: boolean) {
    this.unavailableState = value;
    this.applyDisabled();
  }
 
  private applyDisabled(): void {
    const value = this.disabledState || this.unavailableState;
    this.element.toggleAttribute('data-disabled', value);
    for (const control of this.element.querySelectorAll<
      HTMLInputElement | HTMLSelectElement | HTMLButtonElement | HTMLTextAreaElement
    >('input, select, button, textarea')) {
      // A monitor stays readable, and a help button (`options/help.ts`) stays usable.
      Iif (control.dataset.readonly !== undefined || control.classList.contains('options-help')) continue;
      control.disabled = value;
    }
  }
 
  /** Update the view's labels without mutating another renderer's children. */
  public relabel(language: string): void {
    this.language = language;
    this.localize?.(language);
  }
 
  /** Shows the bound values again. */
  public refresh(): void {}
 
  /** Takes it out of the options. */
  public dispose(): void {
    this.element.remove();
    this.parent?.removeChild(this);
    this.parent = undefined;
  }
 
  /** An edit below it, passed up to the folders that listen. */
  public receiveChange(event: OptionChangeEvent): void {
    this.parent?.receiveChange(event);
  }
}
 
/** A control bound to `object[key]`. */
export class OptionBinding<T = unknown> extends OptionRow {
  private readonly object: Record<PropertyKey, unknown>;
  private readonly key: PropertyKey;
  private readonly params: OptionBindingParams<T>;
  private labelText: string;
  private readonly id = uniqueId('option');
  private readonly controlKind: 'select' | 'toggle' | 'number' | 'text' | 'monitor';
  /** The change handlers, typed loosely so a binding of any value type stores as `OptionBinding<unknown>`. */
  private readonly handlers: ((event: { value: unknown }) => void)[] = [];
  private choices: OptionChoice<T>[];
  private readonly samples: number[] = [];
  private field: HTMLInputElement | undefined;
  private timer: number | undefined;
 
  public constructor(
    parent: OptionContainer,
    object: Record<PropertyKey, unknown>,
    key: PropertyKey,
    params: OptionBindingParams<T>,
  ) {
    const row = element('div', 'field options-row');
    super(row, parent);
    this.object = object;
    this.key = key;
    this.params = params;
    this.choices = [...(params.options ?? [])];
    this.labelText = params.label ?? String(key);
    // The original label names the row's help and remembered settings, independently of localization.
    row.dataset.optionLabel = params.label ?? String(key);
    const value = object[key];
    this.controlKind =
      params.readonly === true
        ? 'monitor'
        : params.options !== undefined
          ? 'select'
          : typeof value === 'boolean'
            ? 'toggle'
            : typeof value === 'number'
              ? 'number'
              : 'text';
    const slider = this.controlKind === 'number' && params.min !== undefined && params.max !== undefined;
    row.classList.toggle('options-toggle-row', this.controlKind === 'toggle');
    row.classList.toggle('options-slider-row', slider);
    row.classList.toggle('options-monitor-row', this.controlKind === 'monitor');
    if (!slider && !(this.controlKind === 'monitor' && (params.view === 'graph' || params.multiline === true)))
      row.dataset.orientation = 'horizontal';
    this.refresh();
    Iif (this.controlKind === 'monitor') {
      // A hidden monitor does no sampling or rendering.
      this.timer = window.setInterval(() => {
        if (this.element.isConnected && this.element.offsetParent !== null) this.refresh();
      }, params.interval ?? 200);
    }
  }
 
  public override get kind(): OptionRowKind {
    if (this.controlKind === 'number' && this.params.min !== undefined && this.params.max !== undefined)
      return 'slider';
    return this.controlKind;
  }
 
  public get label(): string {
    return optionLabel(this.labelText, this.language);
  }
  public set label(value: string) {
    this.labelText = value;
    this.element.dataset.optionLabel = value;
    this.render(false);
  }
 
  public override relabel(language: string): void {
    super.relabel(language);
    this.render(false);
  }
 
  private labelTemplate(): TemplateResult {
    return html`<span class="options-label-wrap"
      ><label class="label options-label" id=${`${this.id}-label`} for=${this.id}
        >${optionLabelContent(this.label)}</label
      ><span data-option-help-host></span
    ></span>`;
  }
 
  /** Replacing choices keeps the select, its focus and its event handlers. */
  public get options(): OptionChoice<T>[] {
    return this.choices;
  }
  public set options(choices: OptionChoice<T>[]) {
    this.choices = [...choices];
    this.refresh();
  }
 
  public on(_event: 'change', handler: (event: { value: T }) => void): this {
    this.handlers.push(handler as (event: { value: unknown }) => void);
    return this;
  }
 
  public override refresh(): void {
    this.render(false);
  }
 
  public override dispose(): void {
    Iif (this.timer !== undefined) window.clearInterval(this.timer);
    this.timer = undefined;
    render(nothing, this.element);
    super.dispose();
  }
 
  /** Applies a section reset through the same change handlers as a manual edit. */
  public resetToDefault(value: OptionDefaultValue): void {
    if (!this.parent || this.disabled || this.unavailable || this.controlKind === 'monitor') return;
    if (this.controlKind === 'select') {
      const choice = this.choices[choiceIndex(this.choices, value)];
      Iif (choice === undefined || choice.disabled === true) return;
      Eif (!Object.is(this.object[this.key], choice.value)) this.commit(choice.value);
      return;
    }
    if (this.controlKind === 'number' && typeof value === 'number') {
      const constrained = constrainNumber(value, this.params);
      Eif (constrained !== undefined && !Object.is(this.object[this.key], constrained)) this.commit(constrained as T);
    } else Eif (
      ((this.controlKind === 'text' && typeof value === 'string') ||
        (this.controlKind === 'toggle' && typeof value === 'boolean')) &&
      !Object.is(this.object[this.key], value)
    ) {
      this.commit(value as T);
    }
  }
 
  private commit(value: T): void {
    this.object[this.key] = value;
    for (const handler of this.handlers) handler({ value });
    this.receiveChange({ key: this.key, value });
    this.render(true);
  }
 
  /** Updating a field being typed in preserves its unfinished text until the edit is committed. */
  private render(force: boolean): void {
    const value = this.object[this.key];
    const typing = !force && this.field !== undefined && document.activeElement === this.field;
    render(this.control(value, typing), this.element);
    this.field = this.element.querySelector<HTMLInputElement>('.options-number, .options-text') ?? undefined;
    // A select whose bound value has no choice must have no selection, including after choices change.
    const select = this.element.querySelector('select');
    if (select !== null) select.selectedIndex = choiceIndex(this.choices, value);
  }
 
  private control(value: unknown, typing: boolean): TemplateResult {
    Iif (this.controlKind === 'monitor') return this.monitor(value);
    if (this.controlKind === 'select')
      return html`${this.labelTemplate()}
        <select
          class="select options-select"
          id=${this.id}
          @change=${(event: Event) => {
            const choice = this.choices[(event.currentTarget as HTMLSelectElement).selectedIndex];
            if (choice !== undefined) this.commit(choice.value);
          }}
        >
          ${this.choices.map(
            (choice, index) =>
              html`<option value=${index} ?disabled=${choice.disabled === true}>${choice.text}</option>`,
          )}
        </select>`;
    if (this.controlKind === 'toggle')
      return html`${this.labelTemplate()}
        <input
          class="input"
          id=${this.id}
          type="checkbox"
          role="switch"
          .checked=${live(value === true)}
          @change=${(event: Event) => this.commit((event.currentTarget as HTMLInputElement).checked as T)}
        />`;
    const text = typing
      ? this.field!.value
      : this.controlKind === 'number' && typeof value === 'number'
        ? formatNumber(value, this.params.step)
        : displayText(value);
    Iif (this.controlKind === 'text')
      return html`${this.labelTemplate()}
        <input
          class="input options-text"
          id=${this.id}
          type="text"
          .spellcheck=${false}
          .value=${live(text)}
          @change=${(event: Event) => this.commit((event.currentTarget as HTMLInputElement).value as T)}
        />`;
    const { min, max, step } = this.params;
    const field = html`<input
      class="input options-number"
      type="number"
      id=${this.id}
      inputmode=${step !== undefined && Number.isInteger(step) && (min ?? 0) >= 0 ? 'numeric' : 'decimal'}
      min=${ifDefined(min)}
      max=${ifDefined(max)}
      step=${step ?? 'any'}
      .value=${live(text)}
      @change=${(event: Event) => {
        const field = event.currentTarget as HTMLInputElement;
        const next = constrainNumber(Number(field.value), this.params);
        if (next === undefined || field.value.trim() === '') this.refresh();
        else this.commit(next as T);
      }}
      @blur=${() => this.refresh()}
    />`;
    if (min === undefined || max === undefined) return html`${this.labelTemplate()}${field}`;
    return html`<div class="options-slider-head">${this.labelTemplate()}${field}</div>
      <input
        class="input options-range"
        type="range"
        min=${min}
        max=${max}
        step=${step ?? 'any'}
        aria-labelledby=${`${this.id}-label`}
        .value=${live(String(value))}
        style=${`--slider-value: ${sliderFill(typeof value === 'number' ? value : min, min, max)}`}
        @input=${(event: Event) => {
          const next = constrainNumber(Number((event.currentTarget as HTMLInputElement).value), this.params);
          if (next !== undefined) this.commit(next as T);
        }}
      />`;
  }
 
  private monitor(value: unknown): TemplateResult {
    if (this.params.view === 'graph') {
      const sample = typeof value === 'number' ? value : Number.NaN;
      const size = this.params.bufferSize ?? 60;
      this.samples.push(sample);
      if (this.samples.length > size) this.samples.splice(0, this.samples.length - size);
      return html`<div class="options-slider-head">
          ${this.labelTemplate()}
          <output class="options-monitor-value" id=${this.id}
            >${Number.isFinite(sample) ? sample.toFixed(1) : '-'}</output
          >
        </div>
        <svg viewBox="0 0 100 32" preserveAspectRatio="none" class="options-graph" aria-hidden="true">
          <polyline
            vector-effect="non-scaling-stroke"
            points=${graphPoints(
              this.samples,
              { min: this.params.min ?? 0, max: this.params.max ?? 100, width: 100, height: 32 },
              size,
            )}
          ></polyline>
        </svg>`;
    }
    if (this.params.multiline === true) {
      const busy = this.params.busy?.() === true;
      const rows = this.params.rows ?? 3;
      return html`${this.labelTemplate()}
        <div class="options-monitor-box">
          <textarea
            class="textarea options-monitor"
            id=${this.id}
            readonly
            data-readonly
            rows=${rows}
            aria-busy=${ifDefined(busy ? 'true' : undefined)}
            .value=${live(busy ? '\u00a0' : displayText(value))}
          ></textarea>
          ${
            busy
              ? html`<span class="options-monitor-skeleton" aria-hidden="true"
                  >${skeletonTemplate({ shape: 'line', width: '60%' })}</span
                >`
              : nothing
          }
        </div>`;
    }
    return html`${this.labelTemplate()}<output class="options-monitor-value" id=${this.id}
        >${displayText(value)}</output
      >`;
  }
}
 
/** A button whose title may be replaced by a live action status. */
export class OptionButton extends OptionRow {
  public readonly button: HTMLButtonElement;
  private titleText: string;
  private readonly originalTitle: string;
  private readonly handlers: (() => void)[] = [];
 
  public constructor(parent: OptionContainer, params: { title: string }) {
    const row = element('div', 'options-row options-button-row');
    super(row, parent);
    this.titleText = params.title;
    this.originalTitle = params.title;
    row.dataset.optionLabel = params.title;
    this.paint();
    this.button = row.querySelector('button')!;
  }
 
  public override get kind(): OptionRowKind {
    return 'button';
  }
 
  public get title(): string {
    return this.button.textContent ?? '';
  }
  public set title(value: string) {
    this.titleText = value;
    this.paint();
  }
 
  public on(_event: 'click', handler: () => void): this {
    this.handlers.push(handler);
    return this;
  }
 
  public override relabel(language: string): void {
    super.relabel(language);
    this.paint();
  }
 
  private paint(): void {
    const title =
      this.titleText === this.originalTitle || this.titleText === optionLabel(this.originalTitle, 'ja')
        ? optionLabel(this.originalTitle, this.language)
        : this.titleText;
    render(
      html`<button
        class="btn options-button"
        type="button"
        data-variant="outline"
        data-size="sm"
        @click=${() => {
          for (const handler of this.handlers) handler();
        }}
      >
        ${title}<span data-option-help-host></span>
      </button>`,
      this.element,
    );
  }
}
 
/** Something that holds rows: a folder, a tab page or the dialog. */
export abstract class OptionContainer extends OptionRow {
  public readonly children: OptionRow[] = [];
  /** Where its rows go. */
  protected abstract readonly content: HTMLElement;
  private readonly changeListeners: ((event: OptionChangeEvent) => void)[] = [];
  /** Each row's place among the others, as the dialog's layout gives it; a row without one goes last. */
  private readonly ranks = new WeakMap<OptionRow, number>();
 
  public addBinding<O extends object, K extends keyof O>(
    object: O,
    key: K,
    params: OptionBindingParams<O[K]> = {},
  ): OptionBinding<O[K]> {
    return this.add(new OptionBinding<O[K]>(this, object as Record<PropertyKey, unknown>, key, params));
  }
 
  public addButton(params: { title: string }): OptionButton {
    return this.add(new OptionButton(this, params));
  }
 
  public addSectionReset(reset: () => void): void {
    const row = this.addButton({ title: 'Reset section to defaults' }).on('click', reset).element;
    row.classList.add('options-section-reset');
    row.removeAttribute('data-option-label');
  }
 
  /** A folder: a section with a heading, which is always open. */
  public addFolder(params: { title: string }): OptionFolder {
    return this.add(new OptionFolder(this, { title: params.title, expanded: true, kind: 'section' }));
  }
 
  /** Tabs, one page per title; the first is selected. */
  public addTab(params: { pages: readonly { title: string }[] }): OptionTabs {
    return this.add(new OptionTabs(this, params.pages));
  }
 
  /** A row holding `content`, laid out, hidden and disabled like the others. */
  public addElement(content: HTMLElement, localize?: (language: string) => void): OptionRow {
    const row = element('div', 'options-row options-element-row');
    render(content, row);
    return this.add(new OptionRow(row, this, localize));
  }
 
  /** Runs `listener` after an edit of any control in it. */
  public on(event: 'change', listener: (event: OptionChangeEvent) => void): this;
  public on(event: 'fold', listener: (event: { expanded: boolean }) => void): this;
  public on(event: 'change' | 'fold', listener: (event: never) => void): this {
    if (event === 'change') this.changeListeners.push(listener as (event: OptionChangeEvent) => void);
    else this.onFold(listener as (event: { expanded: boolean }) => void);
    return this;
  }
 
  public override receiveChange(event: OptionChangeEvent): void {
    for (const listener of this.changeListeners) listener(event);
    super.receiveChange(event);
  }
 
  public override refresh(): void {
    for (const child of this.children) child.refresh();
  }
 
  public override dispose(): void {
    for (const child of this.children.slice()) child.dispose();
    super.dispose();
  }
 
  /** Moves `row`, one of its rows, to the place of `rank`: after every row of a rank up to it, before the others. */
  public placeAt(row: OptionRow, rank: number): void {
    const at = this.children.indexOf(row);
    Iif (at < 0) return;
    this.children.splice(at, 1);
    this.ranks.set(row, rank);
    const index = this.children.findIndex((child) => (this.ranks.get(child) ?? Infinity) > rank);
    this.children.splice(index < 0 ? this.children.length : index, 0, row);
    this.paintChildren();
  }
 
  public removeChild(child: OptionRow): void {
    const index = this.children.indexOf(child);
    Eif (index >= 0) {
      this.children.splice(index, 1);
      this.paintChildren();
    }
  }
 
  public override relabel(language: string): void {
    super.relabel(language);
    for (const child of this.children) child.relabel(language);
  }
 
  private paintChildren(): void {
    render(
      repeat(
        this.children,
        (child) => child,
        (child) => child.element,
      ),
      this.content,
    );
  }
 
  /** Reports its opening and closing; a container that does neither never calls `listener`. */
  protected onFold(_listener: (event: { expanded: boolean }) => void): void {}
 
  private add<R extends OptionRow>(row: R): R {
    this.children.push(row);
    row.relabel(this.language);
    this.paintChildren();
    return row;
  }
}
 
/** How a folder shows: collapsible, a section that is always open, or the Options dialog itself. */
type FolderKind = 'details' | 'section' | 'dialog' | 'panel';
 
/** A folder of rows. Its `title` and `expanded` are what `folders.ts` remembers. */
export class OptionFolder extends OptionContainer {
  protected readonly content: HTMLElement;
  private readonly folderKind: FolderKind;
  private readonly titleText: string;
  private readonly foldListeners: ((event: { expanded: boolean }) => void)[] = [];
  /** The open state last reported, so a programmatic change is not reported as the user's. */
  private reportedOpen: boolean;
 
  public constructor(
    parent: OptionContainer | undefined,
    params:
      | { title: string; expanded: boolean; kind: 'details' | 'section' | 'panel' }
      | { title: string; kind: 'dialog'; dialog: HTMLDialogElement; content: HTMLElement },
  ) {
    const root =
      params.kind === 'dialog'
        ? params.dialog
        : params.kind === 'panel'
          ? element('be-music-collapsible-panel', 'options-panel')
          : params.kind === 'details'
            ? element('details', 'options-folder')
            : element('section', 'options-section');
    super(root, parent);
    this.folderKind = params.kind;
    this.titleText = params.title;
    if (params.kind === 'dialog') {
      this.content = params.content;
      root.addEventListener('close', () => this.reportFold(false));
    } else Iif (root instanceof CollapsiblePanelElement && params.kind === 'panel') {
      root.position = 'inline';
      root.dataset.optionsFolder = '';
      root.dataset.optionTitle = params.title;
      this.content = element('div', 'options-folder-content');
      root.append(this.content);
      this.paintHeading();
      root.open = params.expanded;
      root.addEventListener('panel-toggle', () => this.reportFold(root.open));
    } else Iif (root instanceof HTMLDetailsElement && params.kind === 'details') {
      root.dataset.optionsFolder = '';
      // The English title, which names the folder whatever language it shows in (`options/labels.ts`).
      root.dataset.optionTitle = params.title;
      this.content = element('div', 'options-folder-content');
      this.paintHeading();
      root.open = params.expanded;
      root.addEventListener('toggle', () => this.reportFold(root.open));
    } else {
      root.dataset.optionsFolder = '';
      // The English title, which names the folder whatever language it shows in (`options/labels.ts`).
      root.dataset.optionTitle = params.title;
      this.content = element('div', 'options-folder-content');
      this.paintHeading();
    }
    this.reportedOpen = this.expanded;
  }
 
  /**
   * The Options dialog as the root folder: `content` holds its rows, and `expanded` opens and closes the dialog. Its
   * title is not part of the remembered folder paths.
   */
  public static dialog(dialog: HTMLDialogElement, content: HTMLElement, title: string): OptionFolder {
    return new OptionFolder(undefined, { title, kind: 'dialog', dialog, content });
  }
 
  /** A floating collapsible panel in `container`, such as the beatoraja Skin Config panel. */
  public static panel(container: HTMLElement, params: { title: string; expanded: boolean }): OptionFolder {
    const folder = new OptionFolder(undefined, { ...params, kind: 'panel' });
    folder.element.classList.add('options-panel');
    container.append(folder.element);
    return folder;
  }
 
  public override get kind(): 'folder' {
    return 'folder';
  }
 
  public get title(): string {
    return optionLabel(this.titleText, this.language);
  }
 
  public override relabel(language: string): void {
    super.relabel(language);
    this.paintHeading();
  }
 
  private paintHeading(): void {
    Iif (this.folderKind === 'dialog') return;
    Iif (this.element instanceof CollapsiblePanelElement) {
      this.element.heading = this.title;
      return;
    }
    const title = html`<span class="options-folder-title">${this.title}</span><span data-option-help-host></span>`;
    render(
      this.folderKind === 'details'
        ? html`<summary class="options-folder-summary">${title}${CHEVRON_ICON}</summary>
            ${this.content}`
        : html`<h3 class="options-section-heading">${title}</h3>
            ${this.content}`,
      this.element,
    );
  }
 
  /** Whether it is open: a section always is. */
  public get expanded(): boolean {
    const root = this.element;
    Iif (root instanceof HTMLDetailsElement || root instanceof CollapsiblePanelElement) return root.open;
    if (root instanceof HTMLDialogElement) return root.open;
    return true;
  }
  public set expanded(value: boolean) {
    const root = this.element;
    Iif (root instanceof HTMLDetailsElement || root instanceof CollapsiblePanelElement) {
      this.reportedOpen = value;
      root.open = value;
    } else Eif (root instanceof HTMLDialogElement) {
      if (value && !root.open) root.showModal();
      else Iif (!value && root.open) root.close();
      this.reportFold(root.open);
    }
  }
 
  protected override onFold(listener: (event: { expanded: boolean }) => void): void {
    if (this.folderKind !== 'section') this.foldListeners.push(listener);
  }
 
  private reportFold(open: boolean): void {
    if (open === this.reportedOpen) return;
    this.reportedOpen = open;
    for (const listener of this.foldListeners) listener({ expanded: open });
  }
}
 
/** A label's text with the source at its end as a badge (`splitOptionLabelSource`). */
export function optionLabelContent(label: string): TemplateResult {
  const { text, source } = splitOptionLabelSource(label);
  return source === undefined
    ? html`${text}`
    : html`${text}<span class="badge options-source" data-variant="outline">${source}</span>`;
}
 
/**
 * How far to scroll a tab bar sideways to show a tab whose edges are `left`..`right` in a bar showing `viewLeft`..
 * `viewRight`: negative to the left, `0` when it is already in view. A tab wider than the bar shows from its start.
 */
export function tabRevealScroll(left: number, right: number, viewLeft: number, viewRight: number): number {
  if (left < viewLeft || right - left > viewRight - viewLeft) return left - viewLeft;
  if (right > viewRight) return right - viewRight;
  return 0;
}
 
/** Basecoat tabs: one page per title, the first selected. */
export class OptionTabs extends OptionRow {
  public readonly pages: OptionPage[];
  private readonly tabIds: string[];
  private selected = -1;
  /** The pages the dialog's layout leaves off, by index. */
  private readonly omittedPages = new Set<number>();
 
  public constructor(parent: OptionContainer, pages: readonly { title: string }[]) {
    super(element('section', 'tabs options-tabs'), parent);
    this.tabIds = pages.map(() => uniqueId('options-tab'));
    this.pages = pages.map(({ title }, index) => {
      const panel = element('div', 'options-tab-panel');
      panel.id = uniqueId('options-panel');
      panel.setAttribute('role', 'tabpanel');
      panel.setAttribute('aria-labelledby', this.tabIds[index]!);
      panel.tabIndex = -1;
      return new OptionPage(this, title, panel);
    });
    this.select(0);
  }
 
  public override get kind(): 'tabs' {
    return 'tabs';
  }
 
  /**
   * Leaves a page off (its tab is not shown, and the search skips its rows) or brings it back. When the page selected is
   * left off, the first page shown is selected instead.
   */
  public omitPage(index: number, omitted: boolean): void {
    const page = this.pages[index];
    if (page === undefined || this.omittedPages.has(index) === omitted) return;
    if (omitted) this.omittedPages.add(index);
    else this.omittedPages.delete(index);
    page.element.toggleAttribute('data-option-omitted', omitted);
    if (this.selected === -1 || this.omittedPages.has(this.selected)) {
      this.showPage(this.pages.findIndex((_, at) => !this.omittedPages.has(at)));
    } else {
      this.paint();
    }
  }
 
  public select(index: number): void {
    if (this.pages[index] === undefined || this.omittedPages.has(index)) return;
    this.showPage(index);
  }
 
  private showPage(index: number): void {
    this.selected = index;
    this.paint();
    this.pages.forEach((page, at) => {
      page.element.hidden = at !== index;
      page.element.setAttribute('aria-selected', String(at === index));
    });
    // On a screen too narrow for the tab bar, it scrolls sideways: keep the selected tab in view. Only the bar
    // scrolls, so selecting a nested tab never moves the panel around it.
    const id = this.tabIds[index];
    if (id === undefined) return;
    const tab = this.element.querySelector<HTMLElement>(`#${id}`);
    const bar = tab?.parentElement;
    if (tab && bar) {
      // Layout offsets, not client rects: the dialog's open animation scales it, and `scrollLeft` is unscaled. The
      // bar's padding is kept in view around the tab.
      const padding = Number.parseFloat(getComputedStyle(bar).paddingLeft) || 0;
      const left = tab.offsetLeft - bar.offsetLeft - padding;
      const right = left + tab.offsetWidth + 2 * padding;
      bar.scrollLeft += tabRevealScroll(left, right, bar.scrollLeft, bar.scrollLeft + bar.clientWidth);
    }
  }
 
  public override refresh(): void {
    for (const page of this.pages) page.refresh();
  }
 
  public override relabel(language: string): void {
    super.relabel(language);
    this.paint();
    for (const page of this.pages) page.relabel(language);
  }
 
  public override dispose(): void {
    for (const page of this.pages) page.dispose();
    render(nothing, this.element);
    super.dispose();
  }
 
  private paint(): void {
    render(
      html`<nav role="tablist" aria-orientation="horizontal">
          ${this.pages.map(
            (page, index) =>
              html` <button
                type="button"
                role="tab"
                id=${this.tabIds[index]}
                ?hidden=${this.omittedPages.has(index)}
                data-option-title=${page.title}
                aria-controls=${page.element.id}
                aria-selected=${String(this.selected === index)}
                tabindex=${this.selected === index ? 0 : -1}
                @click=${() => this.select(index)}
                @keydown=${(event: KeyboardEvent) => {
                  const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;
                  Iif (step === 0) return;
                  event.preventDefault();
                  let next = (index + step + this.pages.length) % this.pages.length;
                  // A page left off is passed over.
                  while (this.omittedPages.has(next) && next !== index)
                    next = (next + step + this.pages.length) % this.pages.length;
                  this.select(next);
                  this.element.querySelector<HTMLButtonElement>(`#${this.tabIds[next]}`)?.focus();
                }}
              >
                ${optionLabel(page.title, this.language)}
              </button>`,
          )}
        </nav>
        ${this.pages.map((page) => page.element)}`,
      this.element,
    );
  }
}
 
/** One page of tabs. Its title names the tab, not a remembered folder path. */
export class OptionPage extends OptionContainer {
  public readonly title: string;
  protected readonly content: HTMLElement;
  private readonly tabs: OptionTabs;
 
  public constructor(tabs: OptionTabs, title: string, panel: HTMLElement) {
    super(panel, undefined);
    this.tabs = tabs;
    this.title = title;
    this.content = panel;
  }
 
  public override receiveChange(event: OptionChangeEvent): void {
    super.receiveChange(event);
    this.tabs.receiveChange(event);
  }
}