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

1.2% Statements 1/83
0% Branches 0/36
0% Functions 0/19
1.38% Lines 1/72

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                                                          3x                                                                                                                                                                                                                                                          
// The key config's Screens page (the Keys tab): a row per operation of the select, decide, play and result screens with
// the keys it takes. Clicking a row's keys waits for the next key press and gives the operation that key in place of its
// defaults; Esc cancels, and a key another operation of the same screen takes is refused. An operation only one key map
// has says which; the others show the keys of the map the built-in skins read. Built with the dialog as `this`
// (`OptionsDialog`); the keys are `control-keys.ts`', read as each screen opens, so the rows are disabled during a play.
import {
  CONTROL_ACTIONS,
  controlActionKeys,
  type ControlActionDefinition,
  type ControlActionId,
  type ControlScheme,
  type ControlScreen,
} from '@be-music/player-browser/host';
import { html, render } from 'lit';
import { playerLang } from '../../player-copy.ts';
import { optionLabel } from './labels.ts';
import {
  ACTION_LABELS_JA,
  ACTION_SCREEN_TITLES,
  actionKeyConfigLabel,
  actionKeyLabel,
  keyCodeLabel,
  schemesOf,
} from './action-labels.ts';
import { optionLabelContent, type OptionContainer } from '../options-controls.ts';
import type { OptionsDialog } from './index.ts';
 
export { ACTION_LABELS_JA, ACTION_SCREEN_TITLES, actionKeyConfigLabel, actionKeyLabel, keyCodeLabel };
 
const PROMPTS = {
  en: { waiting: 'Press a key… (Esc cancels)', refused: 'Another operation here has that key — press another' },
  ja: {
    waiting: 'キーを押してください… (Esc で取り消し)',
    refused: 'この画面のほかの操作が使っています。別のキーを押してください',
  },
} as const;
 
/** Builds the Screens page into `page`; returns what shows its keys again (after the built-in skins' key map changes). */
export function buildActionKeyPage(this: OptionsDialog, page: OptionContainer): () => void {
  const views: (() => void)[] = [];
  let waiting: { readonly id: ControlActionId; refused?: boolean } | undefined;
  const prompts = () => PROMPTS[playerLang() === 'ja' ? 'ja' : 'en'];
  const definitionOf = (id: ControlActionId) =>
    CONTROL_ACTIONS.find((action) => action.id === id)! as ControlActionDefinition;
  /** The key map a row shows: the built-in skins' when the operation is on it, else the one it is on. */
  const schemeOf = (definition: ControlActionDefinition): ControlScheme => {
    const schemes = schemesOf(definition);
    return schemes.includes(this.guiState.builtInControlScheme) ? this.guiState.builtInControlScheme : schemes[0]!;
  };
  const keysOf = (id: ControlActionId) =>
    controlActionKeys(id, schemeOf(definitionOf(id)), this.guiState.actionKeys)
      .map(actionKeyLabel)
      .join(' / ');
  const paint = (): void => {
    for (const update of views) update();
  };
  const stop = (): void => {
    document.removeEventListener('keydown', onKey, true);
    waiting = undefined;
    paint();
  };
  /** Whether another operation of `id`'s screen takes `code` on a key map both are on. */
  const takenOnScreen = (id: ControlActionId, code: string): boolean => {
    const definition = definitionOf(id);
    return CONTROL_ACTIONS.some((other) => {
      if (other.id === id || other.screen !== definition.screen) return false;
      return schemesOf(definition).some((scheme) =>
        controlActionKeys(other.id, scheme, this.guiState.actionKeys).some((key) => 'code' in key && key.code === code),
      );
    });
  };
  const onKey = (event: KeyboardEvent): void => {
    if (waiting === undefined) return;
    event.preventDefault();
    event.stopPropagation();
    if (event.repeat) return;
    if (event.code === 'Escape') {
      stop();
      return;
    }
    if (event.code === '' || takenOnScreen(waiting.id, event.code)) {
      waiting.refused = true;
      paint();
      return;
    }
    this.guiState.actionKeys = { ...this.guiState.actionKeys, [waiting.id]: [event.code] };
    this.scheduleSettingsSave();
    stop();
  };
  document.querySelector('#options-modal')?.addEventListener('close', () => {
    if (waiting !== undefined) stop();
  });
 
  // Each screen's operations sit in a section of their own, headed by the screen.
  let screen: ControlScreen | undefined;
  let section: OptionContainer = page;
  for (const action of CONTROL_ACTIONS) {
    const definition = action as ControlActionDefinition;
    if (definition.screen !== screen) {
      screen = definition.screen;
      section = page.addFolder({ title: ACTION_SCREEN_TITLES[screen] });
    }
    const label = actionKeyConfigLabel(definition);
    const content = document.createElement('div');
    content.className = 'options-key-row';
    let language = playerLang();
    const update = (): void => {
      const active = waiting?.id === definition.id;
      const text = active ? (waiting?.refused === true ? prompts().refused : prompts().waiting) : keysOf(definition.id);
      render(
        html`<span class="options-label-wrap"
            ><span class="label options-label">${optionLabelContent(optionLabel(label, language))}</span
            ><span data-option-help-host></span
          ></span>
          <button
            type="button"
            class="btn options-key"
            data-variant="outline"
            data-size="sm"
            aria-pressed=${String(active)}
            @click=${() => {
              if (waiting?.id === definition.id) {
                stop();
                return;
              }
              if (waiting === undefined) document.addEventListener('keydown', onKey, true);
              waiting = { id: definition.id };
              paint();
            }}
          >
            ${text}
          </button>`,
        content,
      );
    };
    const row = section.addElement(content, (nextLanguage) => {
      language = nextLanguage === 'ja' ? 'ja' : 'en';
      update();
    });
    row.element.dataset.optionLabel = label;
    this.trackPlayOption(row);
    views.push(update);
  }
  this.trackPlayOption(
    page.addButton({ title: 'Reset screen keys to defaults' }).on('click', () => {
      if (waiting !== undefined) stop();
      this.guiState.actionKeys = {};
      this.scheduleSettingsSave();
      paint();
    }),
  );
  paint();
  return paint;
}