feat(stats): separate YouTube channels in the Library

- Store YouTube channels as a distinct media kind and migrate legacy entries safely
- Add All Titles, Anime, and YouTube filters with channel-specific stats views
This commit is contained in:
2026-09-18 23:53:26 -07:00
parent 026d495fac
commit d71aab37dc
30 changed files with 475 additions and 47 deletions
@@ -7,6 +7,7 @@ test('AnimeCard includes linked AniList id in cover URLs to avoid stale library
const markup = renderToStaticMarkup(
<AnimeCard
anime={{
mediaKind: 'anime',
animeId: 42,
canonicalTitle: 'Test Anime',
anilistId: 21699,
+2 -1
View File
@@ -48,7 +48,8 @@ export function AnimeCard({
<div className="p-3">
<div className="text-sm font-medium text-ctp-text truncate">{anime.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-1">
{anime.episodeCount} episode{anime.episodeCount !== 1 ? 's' : ''}
{anime.episodeCount} {anime.mediaKind === 'youtube' ? 'video' : 'episode'}
{anime.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2">
{formatDuration(anime.totalActiveMs)} · {formatNumber(anime.totalCards)} cards
@@ -16,6 +16,7 @@ test('AnimeHeader uses the linked AniList id to avoid stale cached cover art', (
const markup = renderToStaticMarkup(
<AnimeHeader
detail={{
mediaKind: 'anime',
animeId: 42,
canonicalTitle: 'Test Anime',
anilistId: 21699,
@@ -168,7 +168,7 @@ export function AnimeDetailView({
if (loading) return <div className="text-ctp-overlay2 p-4">Loading...</div>;
if (error) return <div className="text-ctp-red p-4">Error: {error}</div>;
if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Anime not found</div>;
if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Library entry not found</div>;
const { detail, episodes, anilistEntries } = data;
@@ -226,6 +226,7 @@ export function AnimeDetailView({
<AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} />
<EpisodeList
episodes={episodes}
isYoutube={detail.mediaKind === 'youtube'}
animeId={animeId}
onEpisodeMoved={(removedPreviousAnime) => {
onEpisodeMoved?.();
@@ -237,7 +238,7 @@ export function AnimeDetailView({
/>
<AnimeWatchChart animeId={animeId} />
<AnimeWordList animeId={animeId} onNavigateToWord={onNavigateToWord} />
{showAnilistSelector && (
{detail.mediaKind === 'anime' && showAnilistSelector && (
<AnilistSelector
animeId={animeId}
initialQuery={detail.canonicalTitle}
@@ -46,6 +46,7 @@ function installDom(): () => void {
function libraryItem(animeId: number, title: string): AnimeLibraryItem {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: title,
anilistId: null,
@@ -6,6 +6,7 @@ import { confirmAnimeDelete, setDeleteConfirmPresenter } from '../../lib/delete-
import type { AnimeDetailData } from '../../types/stats';
const DETAIL: AnimeDetailData['detail'] = {
mediaKind: 'anime',
animeId: 3,
canonicalTitle: 'Project Radio Noise Season 2',
anilistId: 20661,
@@ -69,3 +70,16 @@ test('confirmAnimeDelete spells out how much data the entry deletion removes', a
assert.match(seen[1] ?? '', /3 episodes/);
assert.match(seen[0] ?? '', /every session and stat/);
});
test('YouTube channel headers show videos and omit all AniList controls', () => {
const markup = renderToStaticMarkup(
<AnimeHeader
detail={{ ...DETAIL, mediaKind: 'youtube' }}
anilistEntries={[{ anilistId: 20661, titleRomaji: null, titleEnglish: null, season: null }]}
onChangeAnilist={() => {}}
/>,
);
assert.match(markup, /YouTube channel/);
assert.match(markup, /video/);
assert.doesNotMatch(markup, /AniList|anilist\.co|episode/);
});
+22 -18
View File
@@ -37,6 +37,7 @@ export function AnimeHeader({
onDeleteAnime,
isDeletingAnime = false,
}: AnimeHeaderProps) {
const isYoutube = detail.mediaKind === 'youtube';
const altTitles = [detail.titleRomaji, detail.titleEnglish, detail.titleNative].filter(
(t): t is string => t != null && t !== detail.canonicalTitle,
);
@@ -61,33 +62,36 @@ export function AnimeHeader({
</div>
)}
<div className="text-sm text-ctp-subtext0 mt-2">
{detail.episodeCount} episode{detail.episodeCount !== 1 ? 's' : ''}
{isYoutube ? 'YouTube channel · ' : ''}
{detail.episodeCount} {isYoutube ? 'video' : 'episode'}
{detail.episodeCount !== 1 ? 's' : ''}
</div>
<div className="flex flex-wrap gap-1.5 mt-2">
{anilistEntries.length > 0 ? (
hasMultipleEntries ? (
anilistEntries.map((entry) => <AnilistButton key={entry.anilistId} entry={entry} />)
) : (
{!isYoutube &&
(anilistEntries.length > 0 ? (
hasMultipleEntries ? (
anilistEntries.map((entry) => <AnilistButton key={entry.anilistId} entry={entry} />)
) : (
<a
href={`https://anilist.co/anime/${anilistEntries[0]!.anilistId}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-blue hover:bg-ctp-surface2 hover:text-ctp-sapphire transition-colors"
>
View on AniList <span className="text-[10px]">{'\u2197'}</span>
</a>
)
) : detail.anilistId ? (
<a
href={`https://anilist.co/anime/${anilistEntries[0]!.anilistId}`}
href={`https://anilist.co/anime/${detail.anilistId}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-blue hover:bg-ctp-surface2 hover:text-ctp-sapphire transition-colors"
>
View on AniList <span className="text-[10px]">{'\u2197'}</span>
</a>
)
) : detail.anilistId ? (
<a
href={`https://anilist.co/anime/${detail.anilistId}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-blue hover:bg-ctp-surface2 hover:text-ctp-sapphire transition-colors"
>
View on AniList <span className="text-[10px]">{'\u2197'}</span>
</a>
) : null}
{onChangeAnilist && (
) : null)}
{!isYoutube && onChangeAnilist && (
<button
type="button"
onClick={onChangeAnilist}
@@ -45,6 +45,7 @@ function installDom(): () => void {
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: title,
anilistId: null,
@@ -68,7 +69,7 @@ function findButton(container: Element, label: string): HTMLElement {
/** Library cards only expose aria-pressed while selection mode is on. */
function cardButtons(container: Element): HTMLButtonElement[] {
return [...container.querySelectorAll('button[aria-pressed]')] as unknown as HTMLButtonElement[];
return [...container.querySelectorAll('.grid button[aria-pressed]')] as unknown as HTMLButtonElement[];
}
function mergeButton(container: Element): HTMLButtonElement {
@@ -53,19 +53,19 @@ export function AnimeOverviewStats({ detail, knownWordsSummary }: AnimeOverviewS
label="Watch Time"
value={formatDuration(detail.totalActiveMs)}
color="text-ctp-blue"
tooltip="Total active watch time for this anime"
tooltip="Total active watch time for this title"
/>
<Metric
label="Sessions"
value={String(detail.totalSessions)}
color="text-ctp-peach"
tooltip="Number of immersion sessions on this anime"
tooltip="Number of immersion sessions on this title"
/>
<Metric
label="Episodes"
label={detail.mediaKind === 'youtube' ? 'Videos' : 'Episodes'}
value={String(detail.episodeCount)}
color="text-ctp-yellow"
tooltip="Number of completed episodes for this anime"
tooltip={`Number of tracked ${detail.mediaKind === 'youtube' ? 'videos' : 'episodes'} for this title`}
/>
<Metric
label="Words Seen"
@@ -81,7 +81,7 @@ export function AnimeOverviewStats({ detail, knownWordsSummary }: AnimeOverviewS
label="Cards Mined"
value={formatNumber(detail.totalCards)}
color="text-ctp-cards-mined"
tooltip="Anki cards created from subtitle lines in this anime"
tooltip="Anki cards created from subtitle lines in this title"
/>
<Metric
label="Lookups"
@@ -109,7 +109,7 @@ export function AnimeOverviewStats({ detail, knownWordsSummary }: AnimeOverviewS
label="Known Words"
value={`${knownPct}%`}
color="text-ctp-green"
tooltip={`${formatNumber(knownWordsSummary!.knownWordCount)} known out of ${formatNumber(knownWordsSummary!.totalUniqueWords)} unique words in this anime`}
tooltip={`${formatNumber(knownWordsSummary!.knownWordCount)} known out of ${formatNumber(knownWordsSummary!.totalUniqueWords)} unique words in this title`}
/>
) : (
<Metric
@@ -45,6 +45,7 @@ function installDom(): () => void {
function libraryItem(anilistId: number | null): AnimeLibraryItem {
return {
mediaKind: 'anime',
animeId: 7,
canonicalTitle: 'Test Anime Season 2',
anilistId,
@@ -61,6 +62,7 @@ function libraryItem(anilistId: number | null): AnimeLibraryItem {
function detailData(anilistId: number | null): AnimeDetailData {
return {
detail: {
mediaKind: 'anime',
animeId: 7,
canonicalTitle: 'Test Anime Season 2',
anilistId,
@@ -177,3 +179,55 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
uninstallDom();
}
});
test('Library kind filter separates YouTube channels from anime and updates totals', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
apiClient.getAnimeLibrary = async () => [
{ ...libraryItem(null), totalActiveMs: 60_000 },
{
...libraryItem(null),
animeId: 8,
mediaKind: 'youtube',
canonicalTitle: 'Language Channel',
totalActiveMs: 120_000,
},
];
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
try {
await act(async () => {
root.render(<AnimeTab />);
});
assert.match(container.textContent ?? '', /Test Anime Season 2/);
assert.match(container.textContent ?? '', /Language Channel/);
assert.match(container.textContent ?? '', /2 titles · 3m/);
await act(async () => {
findButton(container, 'YouTube').click();
});
assert.doesNotMatch(container.textContent ?? '', /Test Anime Season 2/);
assert.match(container.textContent ?? '', /Language Channel/);
assert.match(container.textContent ?? '', /1 channel · 2m/);
assert.equal(findButton(container, 'YouTube').getAttribute('aria-pressed'), 'true');
await act(async () => {
findButton(container, 'Anime').click();
});
assert.match(container.textContent ?? '', /Test Anime Season 2/);
assert.doesNotMatch(container.textContent ?? '', /Language Channel/);
await act(async () => {
findButton(container, 'All Titles').click();
});
assert.match(container.textContent ?? '', /Language Channel/);
} finally {
await act(async () => {
root.unmount();
});
Object.assign(apiClient, original);
uninstallDom();
}
});
+48 -8
View File
@@ -1,3 +1,4 @@
import { MEDIA_KINDS, type MediaKind } from '../../../../src/shared/media-kind';
import { useState, useMemo, useEffect } from 'react';
import { useAnimeLibrary } from '../../hooks/useAnimeLibrary';
import { formatDuration } from '../../lib/formatters';
@@ -67,6 +68,7 @@ export function AnimeTab({
clearRecommendation,
} = useAnimeLibrary();
const [search, setSearch] = useState('');
const [mediaKind, setMediaKind] = useState<MediaKind | 'all'>('all');
const [sortKey, setSortKey] = useState<SortKey>('lastWatched');
const [cardSize, setCardSize] = useState<LibraryCardSize>(() =>
readLibraryCardSizePreference(
@@ -108,13 +110,14 @@ export function AnimeTab({
}, [initialAnimeId, onClearInitialAnime]);
const filtered = useMemo(() => {
const entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind);
const base = search.trim()
? anime.filter((a) => a.canonicalTitle.toLowerCase().includes(search.toLowerCase()))
: anime;
? entries.filter((a) => a.canonicalTitle.toLowerCase().includes(search.toLowerCase()))
: entries;
return sortAnime(base, sortKey);
}, [anime, search, sortKey]);
}, [anime, search, sortKey, mediaKind]);
const totalMs = anime.reduce((sum, a) => sum + a.totalActiveMs, 0);
const totalMs = filtered.reduce((sum, a) => sum + a.totalActiveMs, 0);
const checkedEntries = checkedAnimeIds
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined);
@@ -125,7 +128,12 @@ export function AnimeTab({
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined),
}))
.filter((recommendation) => recommendation.entries.length >= 2);
.filter(
(recommendation) =>
recommendation.entries.length >= 2 &&
(mediaKind === 'all' ||
recommendation.entries.every((entry) => entry.mediaKind === mediaKind)),
);
const activeRecommendation = hydratedRecommendations[0] ?? null;
const reviewEntries = (reviewAnimeIds ?? [])
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
@@ -155,7 +163,31 @@ export function AnimeTab({
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<div className="flex flex-wrap items-center gap-3">
<div
className="flex bg-ctp-surface0 rounded-lg p-0.5 border border-ctp-surface1"
aria-label="Media kind"
role="group"
>
{(['all', ...MEDIA_KINDS] as const).map((kind) => (
<button
key={kind}
type="button"
aria-pressed={mediaKind === kind}
onClick={() => {
setMediaKind(kind);
exitSelectionMode();
}}
className={`px-3 py-1.5 rounded-md text-xs transition-colors ${
mediaKind === kind
? 'bg-ctp-surface2 text-ctp-text'
: 'text-ctp-overlay2 hover:text-ctp-subtext0'
}`}
>
{kind === 'all' ? 'All Titles' : kind === 'youtube' ? 'YouTube' : 'Anime'}
</button>
))}
</div>
<input
type="text"
placeholder="Search library..."
@@ -170,7 +202,7 @@ export function AnimeTab({
>
{SORT_OPTIONS.map((opt) => (
<option key={opt.key} value={opt.key}>
{opt.label}
{opt.key === 'episodes' && mediaKind === 'youtube' ? 'Videos' : opt.label}
</option>
))}
</select>
@@ -202,7 +234,15 @@ export function AnimeTab({
{selectionMode ? 'Cancel' : 'Select'}
</button>
<div className="text-xs text-ctp-overlay2 shrink-0">
{filtered.length} titles · {formatDuration(totalMs)}
{filtered.length}{' '}
{mediaKind === 'youtube'
? filtered.length === 1
? 'channel'
: 'channels'
: filtered.length === 1
? 'title'
: 'titles'}{' '}
· {formatDuration(totalMs)}
</div>
</div>
+6 -4
View File
@@ -17,6 +17,7 @@ const HOVER_REVEALED =
interface EpisodeListProps {
episodes: AnimeEpisode[];
isYoutube?: boolean;
/** Entry these episodes currently belong to; excluded from the move picker. */
animeId?: number;
onEpisodeDeleted?: () => void;
@@ -27,6 +28,7 @@ interface EpisodeListProps {
export function EpisodeList({
episodes: initialEpisodes,
isYoutube = false,
animeId,
onEpisodeDeleted,
onEpisodeMoved,
@@ -90,7 +92,7 @@ export function EpisodeList({
return (
<div className="bg-ctp-surface0 border border-ctp-surface1 rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-semibold text-ctp-text">Episodes</h3>
<h3 className="text-sm font-semibold text-ctp-text">{isYoutube ? 'Videos' : 'Episodes'}</h3>
<span className="text-xs text-ctp-overlay2">
{watchedCount}/{episodes.length} watched
</span>
@@ -178,7 +180,7 @@ export function EpisodeList({
onOpenDetail(ep.videoId);
}}
className="px-2 py-1 rounded border border-ctp-surface2 text-[11px] text-ctp-blue hover:border-ctp-blue/50 hover:bg-ctp-blue/10 transition-colors"
title="Open episode details"
title={isYoutube ? 'Open video details' : 'Open episode details'}
>
Details
</button>
@@ -218,8 +220,8 @@ export function EpisodeList({
void handleDeleteEpisode(ep.videoId, ep.canonicalTitle);
}}
className={`w-5 h-5 rounded border border-ctp-surface2 text-transparent hover:border-ctp-red/50 hover:text-ctp-red focus-visible:text-ctp-red hover:bg-ctp-red/10 transition-colors text-xs flex items-center justify-center ${HOVER_REVEALED}`}
title="Delete episode"
aria-label="Delete episode"
title={isYoutube ? 'Delete video' : 'Delete episode'}
aria-label={isYoutube ? 'Delete video' : 'Delete episode'}
>
{'\u2715'}
</button>
@@ -63,6 +63,7 @@ function episode(videoId: number, title: string): AnimeEpisode {
function libraryItem(animeId: number, title: string): AnimeLibraryItem {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: title,
anilistId: null,
+1
View File
@@ -116,6 +116,7 @@ test('AnimeOverviewStats renders aggregate Yomitan lookup metrics', () => {
detail={{
animeId: 1,
canonicalTitle: 'Anime',
mediaKind: 'anime',
anilistId: null,
titleRomaji: null,
titleEnglish: null,