All files / player-terminal/src/cli music-select-state.ts

90.9% Statements 60/66
79.48% Branches 31/39
100% Functions 10/10
90.32% Lines 56/62

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                                                                                  2x 2x 2x 2x   2x 4x 18x 18x 4x 4x 4x 11x   4x 9x   4x         18x           2x 4x 4x       4x 4x 4x 4x 8x   4x 3x 3x     1x     1x     2x   2x                           6x 2x     4x   4x   4x 20x     20x 8x 8x   12x 7x   5x 5x 5x   5x 5x     4x 3x   4x       11x     11x 2x   9x 9x           14x    
import { computed, signal } from 'alien-signals';
import type { ChartSelectionEntry } from './chart-selection.ts';
import type { PlayMode } from './config.ts';
import { normalizeHighSpeedValue } from './config.ts';
import type { MusicSelectDifficultyFilter } from './music-select-navigation.ts';
 
type WritableSignal<T> = {
  (): T;
  (value: T): void;
};
 
export interface MusicSelectViewState {
  entries: ChartSelectionEntry[];
  selectableIndexes: number[];
  chartIndexes: number[];
  chartCount: number;
  chartFiles: string[];
  selectableIndexByEntryIndex: Map<number, number>;
  chartIndexByEntryIndex: Map<number, number>;
}
 
export interface MusicSelectState {
  readonly difficultyFilter: WritableSignal<MusicSelectDifficultyFilter | undefined>;
  readonly playMode: WritableSignal<PlayMode>;
  readonly highSpeed: WritableSignal<number>;
  readonly selectedIndex: WritableSignal<number>;
  readonly view: () => MusicSelectViewState;
  ensureSelectedIndex: (preferredFocusKey?: string) => void;
}
 
export interface CreateMusicSelectStateOptions {
  initialDifficultyFilter?: MusicSelectDifficultyFilter;
  initialPlayMode?: PlayMode;
  initialHighSpeed?: number;
  initialFocusKey?: string;
}
 
export function createMusicSelectState(
  allEntries: ChartSelectionEntry[],
  options: CreateMusicSelectStateOptions = {},
): MusicSelectState {
  const difficultyFilter = signal<MusicSelectDifficultyFilter | undefined>(options.initialDifficultyFilter);
  const playMode = signal<PlayMode>(options.initialPlayMode ?? 'manual');
  const highSpeed = signal(normalizeHighSpeedValue(options.initialHighSpeed));
  const selectedIndex = signal(0);
 
  const view = computed(() => {
    const entries = filterChartSelectionEntries(allEntries, difficultyFilter());
    const selectableIndexes = entries.flatMap((entry, index) => (entry.kind === 'group' ? [] : [index]));
    const chartIndexes = entries.flatMap((entry, index) => (entry.kind === 'chart' ? [index] : []));
    const selectableIndexByEntryIndex = new Map<number, number>();
    const chartIndexByEntryIndex = new Map<number, number>();
    for (let index = 0; index < selectableIndexes.length; index += 1) {
      selectableIndexByEntryIndex.set(selectableIndexes[index]!, index);
    }
    for (let index = 0; index < chartIndexes.length; index += 1) {
      chartIndexByEntryIndex.set(chartIndexes[index]!, index);
    }
    return {
      entries,
      selectableIndexes,
      chartIndexes,
      chartCount: chartIndexes.length,
      chartFiles: entries.flatMap((entry) => (entry.kind === 'chart' ? [entry.filePath] : [])),
      selectableIndexByEntryIndex,
      chartIndexByEntryIndex,
    } satisfies MusicSelectViewState;
  });
 
  const ensureSelectedIndex = (preferredFocusKey?: string): void => {
    const resolvedView = view();
    Iif (resolvedView.entries.length === 0) {
      selectedIndex(0);
      return;
    }
    let nextSelectedIndex = Math.max(0, Math.min(selectedIndex(), resolvedView.entries.length - 1));
    const focusKey = preferredFocusKey ?? getEntryFocusKey(resolvedView.entries[nextSelectedIndex]);
    Eif (focusKey) {
      const found = resolvedView.selectableIndexes.find(
        (index) => getEntryFocusKey(resolvedView.entries[index]) === focusKey,
      );
      if (typeof found === 'number') {
        selectedIndex(found);
        return;
      }
    }
    Iif (resolvedView.selectableIndexes.length > 0 && !resolvedView.selectableIndexByEntryIndex.has(nextSelectedIndex)) {
      nextSelectedIndex = resolvedView.selectableIndexes[0]!;
    }
    selectedIndex(nextSelectedIndex);
  };
 
  ensureSelectedIndex(options.initialFocusKey);
 
  return {
    difficultyFilter,
    playMode,
    highSpeed,
    selectedIndex,
    view,
    ensureSelectedIndex,
  };
}
 
export function filterChartSelectionEntries(
  entries: readonly ChartSelectionEntry[],
  difficultyFilter: MusicSelectDifficultyFilter | undefined,
): ChartSelectionEntry[] {
  if (typeof difficultyFilter !== 'number') {
    return [...entries];
  }
 
  const filtered: ChartSelectionEntry[] = [];
  let pendingGroup: Extract<ChartSelectionEntry, { kind: 'group' }> | undefined;
  let hasVisibleCharts = false;
 
  for (const entry of entries) {
    Iif (entry.kind === 'random') {
      continue;
    }
    if (entry.kind === 'group') {
      pendingGroup = entry;
      continue;
    }
    if (entry.difficulty !== difficultyFilter) {
      continue;
    }
    Eif (pendingGroup) {
      filtered.push(pendingGroup);
      pendingGroup = undefined;
    }
    filtered.push(entry);
    hasVisibleCharts = true;
  }
 
  if (hasVisibleCharts) {
    filtered.unshift({ kind: 'random', label: '[Random] Select a chart randomly' });
  }
  return filtered;
}
 
export function getEntryFocusKey(entry: ChartSelectionEntry | undefined): string | undefined {
  Iif (!entry) {
    return undefined;
  }
  if (entry.kind === 'random') {
    return 'random';
  }
  Eif (entry.kind === 'chart') {
    return createChartFocusKey(entry.filePath);
  }
  return undefined;
}
 
export function createChartFocusKey(filePath: string): string {
  return `chart:${filePath}`;
}