mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-04-10 04:19:25 -07:00
* chore(backlog): add mining workflow milestone and tasks
* refactor: split character dictionary runtime modules
* refactor: split shared type entrypoints
* refactor: use bun serve for stats server
* feat: add repo-local subminer workflow plugin
* fix: add stats server node fallback
* refactor: split immersion tracker query modules
* chore: update backlog task records
* refactor: migrate shared type imports
* refactor: compose startup and setup window wiring
* Add backlog tasks and launcher time helper tests
- Track follow-up cleanup work in Backlog.md
- Replace Date.now usage with shared nowMs helper
- Add launcher args/parser and core regression tests
* test: increase launcher test timeout for CI stability
* fix: address CodeRabbit review feedback
* refactor(main): extract remaining inline runtime logic from main
* chore(backlog): update task notes and changelog fragment
* refactor: split main boot phases
* test: stabilize bun coverage reporting
* Switch plausible endpoint and harden coverage lane parsing
- update docs-site tracking to use the Plausible capture endpoint
- tighten coverage lane argument and LCOV parsing checks
- make script entrypoint use CommonJS main guard
* Restrict docs analytics and build coverage input
- limit Plausible init to docs.subminer.moe
- build Yomitan before src coverage lane
* fix(ci): normalize Windows shortcut paths for cross-platform tests
* Fix verification and immersion-tracker grouping
- isolate verifier artifacts and lease handling
- switch weekly/monthly tracker cutoffs to calendar boundaries
- tighten boot lifecycle and zip writer tests
* fix: resolve CI type failures in boot and immersion query tests
* fix: remove strict spread usage in Date mocks
* fix: use explicit super args for MockDate constructors
* Factor out mock date helper in tracker tests
- reuse a shared `withMockDate` helper for date-sensitive query tests
- make monthly rollup assertions key off `videoId` instead of row order
* fix: use variadic array type for MockDate constructor args
TS2367: fixed-length tuple made args.length === 0 unreachable.
* refactor: remove unused createMainBootRuntimes/Handlers aggregate functions
These functions were never called by production code — main.ts imports
the individual composeBoot* re-exports directly.
* refactor: remove boot re-export alias layer
main.ts now imports directly from the runtime/composers and runtime/domains
modules, eliminating the intermediate boot/ indirection.
* refactor: consolidate 3 near-identical setup window factories
Extract shared createSetupWindowHandler with a config parameter.
Public API unchanged.
* refactor: parameterize duplicated getAffected*Ids query helpers
Four structurally identical functions collapsed into two parameterized
helpers while preserving the existing public API.
* refactor: inline identity composers (stats-startup, overlay-window)
composeStatsStartupRuntime was a no-op that returned its input.
composeOverlayWindowHandlers was a 1-line delegation.
Both removed in favor of direct usage.
* chore: remove unused token/queue file path constants from main.ts
* fix: replace any types in boot services with proper signatures
* refactor: deduplicate ensureDir into shared/fs-utils
5 copies of mkdir-p-if-not-exists consolidated into one shared module
with ensureDir (directory path) and ensureDirForFile (file path) variants.
* fix: tighten type safety in boot services
- Add AppLifecycleShape and OverlayModalInputStateShape constraints
so TAppLifecycleApp and TOverlayModalInputState generics are bounded
- Remove unsafe `as { handleModalInputStateChange? }` cast — now
directly callable via the constraint
- Use `satisfies AppLifecycleShape` for structural validation on the
appLifecycleApp object literal
- Document Electron App.on incompatibility with simple signatures
* refactor: inline subtitle-prefetch-runtime-composer
The composer was a pure pass-through that destructured an object and
reassembled it with the same fields. Inlined at the call site.
* chore: consolidate duplicate import paths in main.ts
* test: extract mpv composer test fixture factory to reduce duplication
* test: add behavioral assertions to composer tests
Upgrade 8 composer test files from shape-only typeof checks to behavioral
assertions that invoke returned handlers and verify injected dependencies are
actually called, following the mpv-runtime-composer pattern.
* refactor: normalize import extensions in query modules
* refactor: consolidate toDbMs into query-shared.ts
* refactor: remove Node.js fallback from stats-server, use Bun only
* Fix monthly rollup test expectations
- Preserve multi-arg Date construction in mock helper
- Align rollup assertions with the correct videoId
* fix: address PR 36 CodeRabbit follow-ups
* fix: harden coverage lane cleanup
* fix(stats): fallback to node server when Bun.serve unavailable
* fix(ci): restore coverage lane compatibility
* chore(backlog): close TASK-242
* fix: address latest CodeRabbit review round
* fix: guard disabled immersion retention windows
* fix: migrate discord rpc wrapper
* fix(ci): add changelog fragment for PR 36
* fix: stabilize macOS visible overlay toggle
* fix: pin installed mpv plugin to current binary
* fix: strip inline subtitle markup from sidebar cues
* fix(renderer): restore subtitle sidebar mpv passthrough
* feat(discord): add configurable presence style presets
Replace the hardcoded "Mining and crafting (Anki cards)" meme message
with a preset system. New `discordPresence.presenceStyle` option
supports four presets: "default" (clean bilingual), "meme" (the OG
Minecraft joke), "japanese" (fully JP), and "minimal". The default
preset shows "Sentence Mining" with 日本語学習中 as the small image
tooltip. Existing users can set presenceStyle to "meme" to keep the
old behavior.
* fix: finalize v0.10.0 release prep
* docs: add subtitle sidebar guide and release note
* chore(backlog): mark docs task done
* fix: lazily resolve youtube playback socket path
* chore(release): build v0.10.0 changelog
* Revert "chore(release): build v0.10.0 changelog"
This reverts commit 9741c0f020.
291 lines
11 KiB
TypeScript
291 lines
11 KiB
TypeScript
import type { YoutubePickerOpenPayload } from '../../types';
|
|
import type { ModalStateReader, RendererContext } from '../context';
|
|
import { YOMITAN_POPUP_COMMAND_EVENT } from '../yomitan-popup.js';
|
|
|
|
function createOption(value: string, label: string): HTMLOptionElement {
|
|
const option = document.createElement('option');
|
|
option.value = value;
|
|
option.textContent = label;
|
|
return option;
|
|
}
|
|
|
|
function payloadHasTracks(payload: YoutubePickerOpenPayload | null): boolean {
|
|
return (payload?.tracks.length ?? 0) > 0;
|
|
}
|
|
|
|
export function createYoutubeTrackPickerModal(
|
|
ctx: RendererContext,
|
|
options: {
|
|
modalStateReader: Pick<ModalStateReader, 'isAnyModalOpen'>;
|
|
restorePointerInteractionState: () => void;
|
|
syncSettingsModalSubtitleSuppression: () => void;
|
|
},
|
|
) {
|
|
const OPEN_KEY_GUARD_MS = 200;
|
|
let resolveSelectionInFlight = false;
|
|
let keyboardSubmitEnabledAtMs = 0;
|
|
|
|
function setStatus(message: string, isError = false): void {
|
|
ctx.state.youtubePickerStatus = message;
|
|
ctx.dom.youtubePickerStatus.textContent = message;
|
|
ctx.dom.youtubePickerStatus.style.color = isError ? '#ed8796' : '#a5adcb';
|
|
}
|
|
|
|
function getTrackLabel(trackId: string): string {
|
|
return (
|
|
ctx.state.youtubePickerPayload?.tracks.find((track) => track.id === trackId)?.label ?? ''
|
|
);
|
|
}
|
|
|
|
function renderTrackList(): void {
|
|
ctx.dom.youtubePickerTracks.replaceChildren();
|
|
const payload = ctx.state.youtubePickerPayload;
|
|
if (!payload || !payloadHasTracks(payload)) {
|
|
const li = document.createElement('li');
|
|
const left = document.createElement('span');
|
|
left.textContent = 'No subtitle tracks found';
|
|
const right = document.createElement('span');
|
|
right.className = 'youtube-picker-track-meta';
|
|
right.textContent = 'Continue without subtitles';
|
|
li.append(left, right);
|
|
ctx.dom.youtubePickerTracks.appendChild(li);
|
|
return;
|
|
}
|
|
|
|
for (const track of payload.tracks) {
|
|
const li = document.createElement('li');
|
|
const left = document.createElement('span');
|
|
left.textContent = track.label;
|
|
const right = document.createElement('span');
|
|
right.className = 'youtube-picker-track-meta';
|
|
right.textContent = `${track.kind} · ${track.language}`;
|
|
li.append(left, right);
|
|
ctx.dom.youtubePickerTracks.appendChild(li);
|
|
}
|
|
}
|
|
|
|
function setResolveControlsDisabled(disabled: boolean): void {
|
|
ctx.dom.youtubePickerPrimarySelect.disabled = disabled;
|
|
ctx.dom.youtubePickerSecondarySelect.disabled = disabled;
|
|
ctx.dom.youtubePickerContinueButton.disabled = disabled;
|
|
ctx.dom.youtubePickerCloseButton.disabled = disabled;
|
|
}
|
|
|
|
function syncSecondaryOptions(): void {
|
|
const payload = ctx.state.youtubePickerPayload;
|
|
const primaryTrackId = ctx.dom.youtubePickerPrimarySelect.value || null;
|
|
ctx.dom.youtubePickerSecondarySelect.replaceChildren();
|
|
ctx.dom.youtubePickerSecondarySelect.appendChild(createOption('', 'None'));
|
|
if (!payload) return;
|
|
|
|
for (const track of payload.tracks) {
|
|
if (track.id === primaryTrackId) continue;
|
|
ctx.dom.youtubePickerSecondarySelect.appendChild(createOption(track.id, track.label));
|
|
}
|
|
if (primaryTrackId && ctx.dom.youtubePickerSecondarySelect.value === primaryTrackId) {
|
|
ctx.dom.youtubePickerSecondarySelect.value = '';
|
|
}
|
|
}
|
|
|
|
function setSelection(primaryTrackId: string | null, secondaryTrackId: string | null): void {
|
|
ctx.state.youtubePickerPrimaryTrackId = primaryTrackId;
|
|
ctx.state.youtubePickerSecondaryTrackId = secondaryTrackId;
|
|
ctx.dom.youtubePickerPrimarySelect.value = primaryTrackId ?? '';
|
|
syncSecondaryOptions();
|
|
ctx.dom.youtubePickerSecondarySelect.value = secondaryTrackId ?? '';
|
|
}
|
|
|
|
function applyPayload(payload: YoutubePickerOpenPayload): void {
|
|
ctx.state.youtubePickerPayload = payload;
|
|
ctx.dom.youtubePickerTitle.textContent = `Select YouTube subtitles for ${payload.url}`;
|
|
ctx.dom.youtubePickerPrimarySelect.replaceChildren();
|
|
ctx.dom.youtubePickerSecondarySelect.replaceChildren();
|
|
|
|
if (!payloadHasTracks(payload)) {
|
|
ctx.dom.youtubePickerPrimarySelect.appendChild(createOption('', 'No tracks available'));
|
|
ctx.dom.youtubePickerPrimarySelect.disabled = true;
|
|
ctx.dom.youtubePickerSecondarySelect.disabled = true;
|
|
ctx.dom.youtubePickerContinueButton.textContent = 'Continue without subtitles';
|
|
setSelection(null, null);
|
|
setStatus('No subtitle tracks were found. Playback will continue without subtitles.');
|
|
renderTrackList();
|
|
return;
|
|
}
|
|
|
|
ctx.dom.youtubePickerPrimarySelect.disabled = false;
|
|
ctx.dom.youtubePickerSecondarySelect.disabled = false;
|
|
ctx.dom.youtubePickerContinueButton.textContent = 'Use selected subtitles';
|
|
for (const track of payload.tracks) {
|
|
ctx.dom.youtubePickerPrimarySelect.appendChild(createOption(track.id, track.label));
|
|
}
|
|
setSelection(payload.defaultPrimaryTrackId, payload.defaultSecondaryTrackId);
|
|
renderTrackList();
|
|
setStatus('Select the subtitle tracks to download.');
|
|
}
|
|
|
|
async function resolveSelection(
|
|
action: 'use-selected' | 'continue-without-subtitles',
|
|
): Promise<void> {
|
|
if (resolveSelectionInFlight) {
|
|
return;
|
|
}
|
|
const payload = ctx.state.youtubePickerPayload;
|
|
if (!payload) return;
|
|
const hasTracks = payloadHasTracks(payload);
|
|
if (action === 'use-selected' && hasTracks && !ctx.dom.youtubePickerPrimarySelect.value) {
|
|
setStatus('Primary subtitle selection is required.', true);
|
|
return;
|
|
}
|
|
|
|
resolveSelectionInFlight = true;
|
|
setResolveControlsDisabled(true);
|
|
try {
|
|
const response =
|
|
action === 'use-selected'
|
|
? await window.electronAPI.youtubePickerResolve({
|
|
sessionId: payload.sessionId,
|
|
action: 'use-selected',
|
|
primaryTrackId: ctx.dom.youtubePickerPrimarySelect.value || null,
|
|
secondaryTrackId: ctx.dom.youtubePickerSecondarySelect.value || null,
|
|
})
|
|
: await window.electronAPI.youtubePickerResolve({
|
|
sessionId: payload.sessionId,
|
|
action: 'continue-without-subtitles',
|
|
primaryTrackId: null,
|
|
secondaryTrackId: null,
|
|
});
|
|
if (!response.ok) {
|
|
setStatus(response.message, true);
|
|
return;
|
|
}
|
|
closeYoutubePickerModal();
|
|
} catch (error) {
|
|
setStatus(error instanceof Error ? error.message : String(error), true);
|
|
} finally {
|
|
resolveSelectionInFlight = false;
|
|
const shouldKeepDisabled =
|
|
ctx.state.youtubePickerModalOpen && !payloadHasTracks(ctx.state.youtubePickerPayload);
|
|
setResolveControlsDisabled(shouldKeepDisabled);
|
|
}
|
|
}
|
|
|
|
function openYoutubePickerModal(payload: YoutubePickerOpenPayload): void {
|
|
keyboardSubmitEnabledAtMs = Date.now() + OPEN_KEY_GUARD_MS;
|
|
if (ctx.state.youtubePickerModalOpen) {
|
|
options.syncSettingsModalSubtitleSuppression();
|
|
applyPayload(payload);
|
|
window.electronAPI.notifyOverlayModalOpened('youtube-track-picker');
|
|
return;
|
|
}
|
|
ctx.state.youtubePickerModalOpen = true;
|
|
options.syncSettingsModalSubtitleSuppression();
|
|
applyPayload(payload);
|
|
ctx.dom.overlay.classList.add('interactive');
|
|
ctx.dom.youtubePickerModal.classList.remove('hidden');
|
|
ctx.dom.youtubePickerModal.setAttribute('aria-hidden', 'false');
|
|
window.electronAPI.notifyOverlayModalOpened('youtube-track-picker');
|
|
}
|
|
|
|
function closeYoutubePickerModal(): void {
|
|
if (!ctx.state.youtubePickerModalOpen) return;
|
|
ctx.state.youtubePickerModalOpen = false;
|
|
options.syncSettingsModalSubtitleSuppression();
|
|
ctx.state.youtubePickerPayload = null;
|
|
ctx.state.youtubePickerPrimaryTrackId = null;
|
|
ctx.state.youtubePickerSecondaryTrackId = null;
|
|
ctx.state.youtubePickerStatus = '';
|
|
ctx.dom.youtubePickerModal.classList.add('hidden');
|
|
ctx.dom.youtubePickerModal.setAttribute('aria-hidden', 'true');
|
|
window.electronAPI.notifyOverlayModalClosed('youtube-track-picker');
|
|
window.dispatchEvent(
|
|
new CustomEvent(YOMITAN_POPUP_COMMAND_EVENT, {
|
|
detail: {
|
|
type: 'refreshOptions',
|
|
},
|
|
}),
|
|
);
|
|
if (!options.modalStateReader.isAnyModalOpen()) {
|
|
ctx.dom.overlay.classList.remove('interactive');
|
|
}
|
|
options.restorePointerInteractionState();
|
|
void window.electronAPI.focusMainWindow();
|
|
if (typeof ctx.dom.overlay.focus === 'function') {
|
|
ctx.dom.overlay.focus({ preventScroll: true });
|
|
}
|
|
if (ctx.platform.shouldToggleMouseIgnore) {
|
|
if (!ctx.state.isOverSubtitle && !options.modalStateReader.isAnyModalOpen()) {
|
|
window.electronAPI.setIgnoreMouseEvents(true, { forward: true });
|
|
} else {
|
|
window.electronAPI.setIgnoreMouseEvents(false);
|
|
}
|
|
}
|
|
window.focus();
|
|
}
|
|
|
|
function handleYoutubePickerKeydown(e: KeyboardEvent): boolean {
|
|
if (!ctx.state.youtubePickerModalOpen) return false;
|
|
|
|
if (e.key === 'Escape') {
|
|
e.preventDefault();
|
|
void resolveSelection('continue-without-subtitles');
|
|
return true;
|
|
}
|
|
|
|
if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
if (Date.now() < keyboardSubmitEnabledAtMs) {
|
|
return true;
|
|
}
|
|
void resolveSelection(
|
|
payloadHasTracks(ctx.state.youtubePickerPayload)
|
|
? 'use-selected'
|
|
: 'continue-without-subtitles',
|
|
);
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
function wireDomEvents(): void {
|
|
ctx.dom.youtubePickerPrimarySelect.addEventListener('change', () => {
|
|
const primaryTrackId = ctx.dom.youtubePickerPrimarySelect.value || null;
|
|
if (ctx.dom.youtubePickerSecondarySelect.value === primaryTrackId) {
|
|
ctx.dom.youtubePickerSecondarySelect.value = '';
|
|
}
|
|
setSelection(primaryTrackId, ctx.dom.youtubePickerSecondarySelect.value || null);
|
|
});
|
|
|
|
ctx.dom.youtubePickerSecondarySelect.addEventListener('change', () => {
|
|
const primaryTrackId = ctx.dom.youtubePickerPrimarySelect.value || null;
|
|
const secondaryTrackId = ctx.dom.youtubePickerSecondarySelect.value || null;
|
|
if (primaryTrackId && secondaryTrackId === primaryTrackId) {
|
|
ctx.dom.youtubePickerSecondarySelect.value = '';
|
|
setStatus('Primary and secondary subtitles must be different.', true);
|
|
return;
|
|
}
|
|
setSelection(primaryTrackId, secondaryTrackId);
|
|
setStatus('Select the subtitle tracks to download.');
|
|
});
|
|
|
|
ctx.dom.youtubePickerContinueButton.addEventListener('click', () => {
|
|
void resolveSelection(
|
|
payloadHasTracks(ctx.state.youtubePickerPayload)
|
|
? 'use-selected'
|
|
: 'continue-without-subtitles',
|
|
);
|
|
});
|
|
|
|
ctx.dom.youtubePickerCloseButton.addEventListener('click', () => {
|
|
void resolveSelection('continue-without-subtitles');
|
|
});
|
|
}
|
|
|
|
return {
|
|
closeYoutubePickerModal,
|
|
handleYoutubePickerKeydown,
|
|
openYoutubePickerModal,
|
|
wireDomEvents,
|
|
};
|
|
}
|