feat(config): add configuration window (#70)

This commit is contained in:
2026-05-21 04:16:21 -07:00
committed by GitHub
parent a54f03f0cd
commit dc52bc2fba
287 changed files with 14507 additions and 8134 deletions
+42 -408
View File
@@ -1,7 +1,17 @@
import type { Keybinding } from '../../types';
import type { ShortcutsConfig } from '../../types';
import { SPECIAL_COMMANDS } from '../../config/definitions';
import type { ModalStateReader, RendererContext } from '../context';
import {
buildSessionHelpSections,
type SessionHelpSection,
type SessionHelpTabId,
} from './session-help-sections';
import { createSessionHelpSectionNode } from './session-help-render';
import { buildVisibleSessionHelpSections, createSessionHelpTabBar } from './session-help-tabs';
export {
buildSessionHelpSections,
describeSessionHelpCommand,
formatSessionHelpKeybinding,
} from './session-help-sections';
type SessionHelpBindingInfo = {
bindingKey: 'KeyH' | 'KeyK';
@@ -9,314 +19,6 @@ type SessionHelpBindingInfo = {
fallbackUnavailable: boolean;
};
type SessionHelpItem = {
shortcut: string;
action: string;
color?: string;
};
type SessionHelpSection = {
title: string;
rows: SessionHelpItem[];
};
type RuntimeShortcutConfig = Omit<Required<ShortcutsConfig>, 'multiCopyTimeoutMs'>;
const HEX_COLOR_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
// Fallbacks mirror the session overlay's default subtitle/word color scheme.
const FALLBACK_COLORS = {
knownWordColor: '#a6da95',
nPlusOneColor: '#c6a0f6',
nameMatchColor: '#f5bde6',
jlptN1Color: '#ed8796',
jlptN2Color: '#f5a97f',
jlptN3Color: '#f9e2af',
jlptN4Color: '#a6e3a1',
jlptN5Color: '#8aadf4',
};
const KEY_NAME_MAP: Record<string, string> = {
Space: 'Space',
ArrowUp: '↑',
ArrowDown: '↓',
ArrowLeft: '←',
ArrowRight: '→',
Escape: 'Esc',
Tab: 'Tab',
Enter: 'Enter',
BracketLeft: '[',
BracketRight: ']',
CommandOrControl: 'Cmd/Ctrl',
Ctrl: 'Ctrl',
Control: 'Ctrl',
Command: 'Cmd',
Cmd: 'Cmd',
Shift: 'Shift',
Alt: 'Alt',
Super: 'Meta',
Meta: 'Meta',
Backspace: 'Backspace',
};
function normalizeColor(value: unknown, fallback: string): string {
if (typeof value !== 'string') return fallback;
const next = value.trim();
return HEX_COLOR_RE.test(next) ? next : fallback;
}
function normalizeKeyToken(token: string): string {
if (KEY_NAME_MAP[token]) return KEY_NAME_MAP[token];
if (token.startsWith('Key')) return token.slice(3);
if (token.startsWith('Digit')) return token.slice(5);
if (token.startsWith('Numpad')) return token.slice(6);
return token;
}
function formatKeybinding(rawBinding: string): string {
const parts = rawBinding.split('+');
const key = parts.pop();
if (!key) return rawBinding;
const normalized = [...parts, normalizeKeyToken(key)];
return normalized.join(' + ');
}
const OVERLAY_SHORTCUTS: Array<{
key: keyof RuntimeShortcutConfig;
label: string;
}> = [
{ key: 'copySubtitle', label: 'Copy subtitle' },
{ key: 'copySubtitleMultiple', label: 'Copy subtitle (multi)' },
{
key: 'updateLastCardFromClipboard',
label: 'Update last card from clipboard',
},
{ key: 'triggerFieldGrouping', label: 'Trigger field grouping' },
{ key: 'triggerSubsync', label: 'Open subtitle sync controls' },
{ key: 'mineSentence', label: 'Mine sentence' },
{ key: 'mineSentenceMultiple', label: 'Mine sentence (multi)' },
{ key: 'toggleSecondarySub', label: 'Toggle secondary subtitle mode' },
{ key: 'markAudioCard', label: 'Mark audio card' },
{ key: 'openCharacterDictionary', label: 'Open character dictionary anime selector' },
{ key: 'openRuntimeOptions', label: 'Open runtime options' },
{ key: 'openJimaku', label: 'Open jimaku' },
{ key: 'openSessionHelp', label: 'Open session help' },
{ key: 'openControllerSelect', label: 'Open controller select' },
{ key: 'openControllerDebug', label: 'Open controller debug' },
{ key: 'toggleSubtitleSidebar', label: 'Toggle subtitle sidebar' },
{ key: 'toggleVisibleOverlayGlobal', label: 'Show/hide visible overlay' },
];
function buildOverlayShortcutSections(shortcuts: RuntimeShortcutConfig): SessionHelpSection[] {
const rows: SessionHelpItem[] = [];
for (const shortcut of OVERLAY_SHORTCUTS) {
const keybind = shortcuts[shortcut.key];
rows.push({
shortcut:
typeof keybind === 'string' && keybind.trim().length > 0
? formatKeybinding(keybind)
: 'Unbound',
action: shortcut.label,
});
}
if (rows.length === 0) return [];
return [{ title: 'Overlay shortcuts', rows }];
}
function describeCommand(command: (string | number)[]): string {
const first = command[0];
if (typeof first !== 'string') return 'Unknown action';
if (first === 'cycle' && command[1] === 'pause') return 'Toggle playback';
if (first === 'seek' && typeof command[1] === 'number') {
return `Seek ${command[1] > 0 ? '+' : ''}${command[1]} second(s)`;
}
if (first === 'sub-seek' && typeof command[1] === 'number') {
if (command[1] > 0) return 'Jump to next subtitle';
if (command[1] < 0) return 'Jump to previous subtitle';
return 'Reload current subtitle timing';
}
if (first === SPECIAL_COMMANDS.SUBSYNC_TRIGGER) return 'Open subtitle sync controls';
if (first === SPECIAL_COMMANDS.RUNTIME_OPTIONS_OPEN) return 'Open runtime options';
if (first === SPECIAL_COMMANDS.JIMAKU_OPEN) return 'Open jimaku';
if (first === SPECIAL_COMMANDS.PLAYLIST_BROWSER_OPEN) return 'Open playlist browser';
if (first === SPECIAL_COMMANDS.REPLAY_SUBTITLE) return 'Replay current subtitle';
if (first === SPECIAL_COMMANDS.PLAY_NEXT_SUBTITLE) return 'Play next subtitle';
if (first === SPECIAL_COMMANDS.SHIFT_SUB_DELAY_TO_NEXT_SUBTITLE_START) {
return 'Shift subtitle delay to next cue';
}
if (first === SPECIAL_COMMANDS.SHIFT_SUB_DELAY_TO_PREVIOUS_SUBTITLE_START) {
return 'Shift subtitle delay to previous cue';
}
if (first.startsWith(SPECIAL_COMMANDS.RUNTIME_OPTION_CYCLE_PREFIX)) {
const [, rawId, rawDirection] = first.split(':');
return `Cycle runtime option ${rawId || 'option'} ${rawDirection === 'prev' ? 'previous' : 'next'}`;
}
return `MPV command: ${command.map((entry) => String(entry)).join(' ')}`;
}
export {
describeCommand as describeSessionHelpCommand,
formatKeybinding as formatSessionHelpKeybinding,
};
function sectionForCommand(command: (string | number)[]): string {
const first = command[0];
if (typeof first !== 'string') return 'Other shortcuts';
if (
first === 'cycle' ||
first === 'seek' ||
first === 'sub-seek' ||
first === SPECIAL_COMMANDS.REPLAY_SUBTITLE ||
first === SPECIAL_COMMANDS.PLAY_NEXT_SUBTITLE
) {
return 'Playback and navigation';
}
if (first === 'show-text' || first === 'show-progress' || first.startsWith('osd')) {
return 'Visual feedback';
}
if (first === SPECIAL_COMMANDS.SUBSYNC_TRIGGER) {
return 'Subtitle sync';
}
if (
first === SPECIAL_COMMANDS.RUNTIME_OPTIONS_OPEN ||
first === SPECIAL_COMMANDS.JIMAKU_OPEN ||
first === SPECIAL_COMMANDS.PLAYLIST_BROWSER_OPEN ||
first.startsWith(SPECIAL_COMMANDS.RUNTIME_OPTION_CYCLE_PREFIX)
) {
return 'Runtime settings';
}
if (first === 'quit') return 'System actions';
return 'Other shortcuts';
}
function buildBindingSections(keybindings: Keybinding[]): SessionHelpSection[] {
const grouped = new Map<string, SessionHelpItem[]>();
for (const binding of keybindings) {
const section = sectionForCommand(binding.command ?? []);
const row: SessionHelpItem = {
shortcut: formatKeybinding(binding.key),
action: describeCommand(binding.command ?? []),
};
grouped.set(section, [...(grouped.get(section) ?? []), row]);
}
const sectionOrder = [
'Playback and navigation',
'Visual feedback',
'Subtitle sync',
'Runtime settings',
'System actions',
'Other shortcuts',
];
const sectionEntries = Array.from(grouped.entries()).sort((a, b) => {
const aIdx = sectionOrder.indexOf(a[0]);
const bIdx = sectionOrder.indexOf(b[0]);
if (aIdx === -1 && bIdx === -1) return a[0].localeCompare(b[0]);
if (aIdx === -1) return 1;
if (bIdx === -1) return -1;
return aIdx - bIdx;
});
return sectionEntries.map(([title, rows]) => ({ title, rows }));
}
function buildColorSection(style: {
knownWordColor?: unknown;
nPlusOneColor?: unknown;
nameMatchColor?: unknown;
jlptColors?: {
N1?: unknown;
N2?: unknown;
N3?: unknown;
N4?: unknown;
N5?: unknown;
};
}): SessionHelpSection {
return {
title: 'Color legend',
rows: [
{
shortcut: 'Known words',
action: normalizeColor(style.knownWordColor, FALLBACK_COLORS.knownWordColor),
color: normalizeColor(style.knownWordColor, FALLBACK_COLORS.knownWordColor),
},
{
shortcut: 'N+1 words',
action: normalizeColor(style.nPlusOneColor, FALLBACK_COLORS.nPlusOneColor),
color: normalizeColor(style.nPlusOneColor, FALLBACK_COLORS.nPlusOneColor),
},
{
shortcut: 'Character names',
action: normalizeColor(style.nameMatchColor, FALLBACK_COLORS.nameMatchColor),
color: normalizeColor(style.nameMatchColor, FALLBACK_COLORS.nameMatchColor),
},
{
shortcut: 'JLPT N1',
action: normalizeColor(style.jlptColors?.N1, FALLBACK_COLORS.jlptN1Color),
color: normalizeColor(style.jlptColors?.N1, FALLBACK_COLORS.jlptN1Color),
},
{
shortcut: 'JLPT N2',
action: normalizeColor(style.jlptColors?.N2, FALLBACK_COLORS.jlptN2Color),
color: normalizeColor(style.jlptColors?.N2, FALLBACK_COLORS.jlptN2Color),
},
{
shortcut: 'JLPT N3',
action: normalizeColor(style.jlptColors?.N3, FALLBACK_COLORS.jlptN3Color),
color: normalizeColor(style.jlptColors?.N3, FALLBACK_COLORS.jlptN3Color),
},
{
shortcut: 'JLPT N4',
action: normalizeColor(style.jlptColors?.N4, FALLBACK_COLORS.jlptN4Color),
color: normalizeColor(style.jlptColors?.N4, FALLBACK_COLORS.jlptN4Color),
},
{
shortcut: 'JLPT N5',
action: normalizeColor(style.jlptColors?.N5, FALLBACK_COLORS.jlptN5Color),
color: normalizeColor(style.jlptColors?.N5, FALLBACK_COLORS.jlptN5Color),
},
],
};
}
function filterSections(sections: SessionHelpSection[], query: string): SessionHelpSection[] {
const normalize = (value: string): string =>
value
.toLowerCase()
.replace(/commandorcontrol/gu, 'ctrl')
.replace(/cmd\/ctrl/gu, 'ctrl')
.replace(/[\s+\-_/]/gu, '');
const normalized = normalize(query);
if (!normalized) return sections;
return sections
.map((section) => {
if (normalize(section.title).includes(normalized)) {
return section;
}
const rows = section.rows.filter(
(row) =>
normalize(row.shortcut).includes(normalized) ||
normalize(row.action).includes(normalized),
);
if (rows.length === 0) return null;
return { ...section, rows };
})
.filter((section): section is SessionHelpSection => section !== null)
.filter((section) => section.rows.length > 0);
}
function formatBindingHint(info: SessionHelpBindingInfo): string {
if (info.bindingKey === 'KeyK' && info.fallbackUsed) {
return info.fallbackUnavailable ? 'Y-K (fallback and conflict noted)' : 'Y-K (fallback)';
@@ -324,79 +26,6 @@ function formatBindingHint(info: SessionHelpBindingInfo): string {
return 'Y-H';
}
function createShortcutRow(row: SessionHelpItem, globalIndex: number): HTMLButtonElement {
const button = document.createElement('button');
button.type = 'button';
button.className = 'session-help-item';
button.tabIndex = -1;
button.dataset.sessionHelpIndex = String(globalIndex);
const left = document.createElement('div');
left.className = 'session-help-item-left';
const shortcut = document.createElement('span');
shortcut.className = 'session-help-key';
shortcut.textContent = row.shortcut;
left.appendChild(shortcut);
const right = document.createElement('div');
right.className = 'session-help-item-right';
const action = document.createElement('span');
action.className = 'session-help-action';
action.textContent = row.action;
right.appendChild(action);
if (row.color) {
const dot = document.createElement('span');
dot.className = 'session-help-color-dot';
dot.style.backgroundColor = row.color;
right.insertBefore(dot, action);
}
button.appendChild(left);
button.appendChild(right);
return button;
}
const SECTION_ICON: Record<string, string> = {
'MPV shortcuts': '⚙',
'Playback and navigation': '▶',
'Visual feedback': '◉',
'Subtitle sync': '⟲',
'Runtime settings': '⚙',
'System actions': '◆',
'Other shortcuts': '…',
'Overlay shortcuts (configurable)': '✦',
'Overlay shortcuts': '✦',
'Color legend': '◈',
};
function createSectionNode(
section: SessionHelpSection,
sectionIndex: number,
globalIndexMap: number[],
): HTMLElement {
const sectionNode = document.createElement('section');
sectionNode.className = 'session-help-section';
const title = document.createElement('h3');
title.className = 'session-help-section-title';
const icon = SECTION_ICON[section.title] ?? '•';
title.textContent = `${icon} ${section.title}`;
sectionNode.appendChild(title);
const list = document.createElement('div');
list.className = 'session-help-item-list';
section.rows.forEach((row, rowIndex) => {
const globalIndex = (globalIndexMap[sectionIndex] ?? 0) + rowIndex;
const button = createShortcutRow(row, globalIndex);
list.appendChild(button);
});
sectionNode.appendChild(list);
return sectionNode;
}
export function createSessionHelpModal(
ctx: RendererContext,
options: {
@@ -412,6 +41,7 @@ export function createSessionHelpModal(
};
let helpFilterValue = '';
let helpSections: SessionHelpSection[] = [];
let activeTabId: SessionHelpTabId = 'essentials';
let focusGuard: ((event: FocusEvent) => void) | null = null;
let windowFocusGuard: (() => void) | null = null;
let modalPointerFocusGuard: ((event: Event) => void) | null = null;
@@ -497,7 +127,7 @@ export function createSessionHelpModal(
}
function applyFilterAndRender(): void {
const sections = filterSections(helpSections, helpFilterValue);
const sections = buildVisibleSessionHelpSections(helpSections, activeTabId, helpFilterValue);
const indexOffsets: number[] = [];
let running = 0;
for (const section of sections) {
@@ -506,8 +136,16 @@ export function createSessionHelpModal(
}
ctx.dom.sessionHelpContent.innerHTML = '';
if (!helpFilterValue.trim()) {
ctx.dom.sessionHelpContent.appendChild(
createSessionHelpTabBar(helpSections, activeTabId, (tabId) => {
activeTabId = tabId;
applyFilterAndRender();
}),
);
}
sections.forEach((section, sectionIndex) => {
const sectionNode = createSectionNode(section, sectionIndex, indexOffsets);
const sectionNode = createSessionHelpSectionNode(section, sectionIndex, indexOffsets);
ctx.dom.sessionHelpContent.appendChild(sectionNode);
});
@@ -515,7 +153,7 @@ export function createSessionHelpModal(
ctx.dom.sessionHelpContent.classList.add('session-help-content-no-results');
ctx.dom.sessionHelpContent.textContent = helpFilterValue
? 'No matching shortcuts found.'
: 'No active session shortcuts found.';
: 'No active shortcuts in this tab.';
ctx.state.sessionHelpSelectedIndex = 0;
return;
}
@@ -572,6 +210,7 @@ export function createSessionHelpModal(
function showRenderError(message: string): void {
helpSections = [];
helpFilterValue = '';
activeTabId = 'essentials';
ctx.dom.sessionHelpFilter.value = '';
ctx.dom.sessionHelpContent.classList.add('session-help-content-no-results');
ctx.dom.sessionHelpContent.textContent = message;
@@ -580,28 +219,23 @@ export function createSessionHelpModal(
async function render(): Promise<boolean> {
try {
const [keybindings, styleConfig, shortcuts] = await Promise.all([
window.electronAPI.getKeybindings(),
window.electronAPI.getSubtitleStyle(),
window.electronAPI.getConfiguredShortcuts(),
]);
const [sessionBindings, styleConfig, markWatchedKey, subtitleSidebarToggleKey] =
await Promise.all([
window.electronAPI.getSessionBindings(),
window.electronAPI.getSubtitleStyle(),
window.electronAPI.getMarkWatchedKey(),
window.electronAPI
.getSubtitleSidebarSnapshot()
.then((snapshot) => snapshot.config.toggleKey)
.catch(() => undefined),
]);
const bindingSections = buildBindingSections(keybindings);
if (bindingSections.length > 0) {
const playback = bindingSections.find(
(section) => section.title === 'Playback and navigation',
);
if (playback) {
playback.title = 'MPV shortcuts';
}
}
const shortcutSections = buildOverlayShortcutSections(shortcuts);
if (shortcutSections.length > 0) {
shortcutSections[0]!.title = 'Overlay shortcuts (configurable)';
}
const colorSection = buildColorSection(styleConfig ?? {});
helpSections = [...bindingSections, ...shortcutSections, colorSection];
helpSections = buildSessionHelpSections({
sessionBindings,
markWatchedKey,
subtitleSidebarToggleKey,
subtitleStyle: styleConfig ?? {},
});
applyFilterAndRender();
return true;
} catch (error) {