feat(stats): group library seasons, movies and OVAs into franchise cards

The stats library now lists each anime once. Grouping is a view over
imm_anime rows computed from a cached AniList relation graph; no rows are
merged and identity keys are unchanged.

- Schema 27: imm_anilist_media + imm_anilist_relations cache every AniList
  entry reached from the library and all its anime edges. A background
  refresher walks from owned AniList ids (depth 6, 250 fetches per run,
  7-day staleness) through the shared AniList rate limiter; a failed fetch
  leaves cached rows untouched.
- FRANCHISE_RELATION_TYPES (PREQUEL, SEQUEL, PARENT, SIDE_STORY, SUMMARY,
  COMPILATION, CONTAINS) joins entries; an entry that names the other only
  through an excluded type (a spin-off's original) vetoes the join.
- GET /api/stats/anime/groups returns cards with summed totals, the root
  entry's title, and parts in release order. Entries without cached
  relations stay single cards identical to before.
- imm_anime.group_override (NULL = AniList, 0 = on its own, positive =
  join the franchise containing that AniList id) with
  PUT /api/stats/anime/:id/group and Move to Another Anime / Show On Its
  Own / Put Back Where AniList Has It on the title page.
- SSH sync merges the override last-writer-wins on
  group_override_updated_at and skips the rebuildable relation cache.
This commit is contained in:
sudacode committed 2026-11-22 02:33:44 -08:00
1 parent 0ae70b4ab2
commit 2edf56541c
41 files changed
+2230 -109

No files matched your search

+9 -3
View File
@@ -1,9 +1,9 @@
import { AnimeCoverImage } from './AnimeCoverImage';
import { formatDuration, formatNumber } from '../../lib/formatters';
import type { AnimeLibraryItem } from '../../types/stats';
import type { AnimeCardData } from '../../lib/anime-groups';
interface AnimeCardProps {
anime: AnimeLibraryItem;
anime: AnimeCardData;
onClick: () => void;
/** While selecting, clicking the card toggles it instead of opening it. */
selectable?: boolean;
@@ -16,6 +16,7 @@ export function AnimeCard({
selectable = false,
selected = false,
}: AnimeCardProps) {
const unit = anime.mediaKind === 'youtube' ? 'video' : 'episode';
return (
<button
type="button"
@@ -44,11 +45,16 @@ export function AnimeCard({
{'✓'}
</span>
)}
{anime.partCount ? (
<span className="absolute top-2 right-2 px-1.5 py-0.5 rounded text-[10px] font-medium bg-ctp-crust/80 text-ctp-text border border-ctp-surface2">
{anime.partCount} parts
</span>
) : null}
</div>
<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} {anime.mediaKind === 'youtube' ? 'video' : 'episode'}
{anime.episodeCount} {unit}
{anime.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2">
+70 -3
View File
@@ -9,13 +9,16 @@ import { AnimeWordList } from './AnimeWordList';
import { AnilistSelector } from './AnilistSelector';
import { TmdbSelector } from './TmdbSelector';
import { AnimeOverviewStats } from './AnimeOverviewStats';
import { LibraryEntryPicker } from './LibraryEntryPicker';
import { CHART_THEME } from '../../lib/chart-theme';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import type { DailyRollup } from '../../types/stats';
import type { DailyRollup, StatsAnimeGroupOverrideRequest } from '../../types/stats';
interface AnimeDetailViewProps {
animeId: number;
onBack: () => void;
/** Defaults to "Back to Library"; a part opened from a franchise card returns there. */
backLabel?: string;
onNavigateToWord?: (wordId: number) => void;
onOpenEpisodeDetail?: (videoId: number) => void;
/** Called after the whole library entry is deleted, so the caller can refresh. */
@@ -28,6 +31,23 @@ interface AnimeDetailViewProps {
onProviderRelinked?: () => void;
/** Called after an episode is reassigned to another entry. */
onEpisodeMoved?: () => void;
/** Called after the entry is moved to another franchise card or back. */
onGroupChanged?: () => void;
}
/** The server explains a refused move (409) in its JSON body; show that text. */
function describeGroupError(err: unknown): string {
const message = err instanceof Error ? err.message : '';
const refused = /^Stats API error: 409 (.*)$/s.exec(message);
if (refused) {
try {
const body = JSON.parse(refused[1]!) as { error?: unknown };
if (typeof body.error === 'string') return body.error;
} catch {
// Fall through to the raw message.
}
}
return message || 'Failed to move this title.';
}
type Range = 14 | 30 | 90;
@@ -149,11 +169,13 @@ function useAnimeKnownWords(animeId: number) {
export function AnimeDetailView({
animeId,
onBack,
backLabel = 'Back to Library',
onNavigateToWord,
onOpenEpisodeDetail,
onAnimeDeleted,
onProviderRelinked,
onEpisodeMoved,
onGroupChanged,
}: AnimeDetailViewProps) {
const { data, loading, error, reload } = useAnimeDetail(animeId);
const [showAnilistSelector, setShowAnilistSelector] = useState(false);
@@ -162,6 +184,9 @@ export function AnimeDetailView({
const [isDeletingAnime, setIsDeletingAnime] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
const isDeletingAnimeRef = useRef(false);
const [showGroupPicker, setShowGroupPicker] = useState(false);
const [groupBusyTargetId, setGroupBusyTargetId] = useState<number | null>(null);
const [groupError, setGroupError] = useState<string | null>(null);
const knownWordsSummary = useAnimeKnownWords(animeId);
useEffect(() => {
@@ -172,7 +197,23 @@ export function AnimeDetailView({
if (error) return <div className="text-ctp-red p-4">Error: {error}</div>;
if (!data?.detail) return <div className="text-ctp-overlay2 p-4">Library entry not found</div>;
const { detail, episodes, anilistEntries } = data;
const { detail, episodes, anilistEntries, group } = data;
// `busyId` marks which picker row shows progress; the entry's own id for header actions.
const applyGroupOverride = async (request: StatsAnimeGroupOverrideRequest, busyId: number) => {
setGroupBusyTargetId(busyId);
setGroupError(null);
try {
await getStatsClient().setAnimeGroupOverride(animeId, request);
setShowGroupPicker(false);
reload();
onGroupChanged?.();
} catch (err) {
setGroupError(describeGroupError(err));
} finally {
setGroupBusyTargetId(null);
}
};
const handleDeleteAnime = async () => {
if (isDeletingAnimeRef.current) return;
@@ -214,11 +255,18 @@ export function AnimeDetailView({
onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
>
&larr; Back to Library
&larr; {backLabel}
</button>
<AnimeHeader
detail={detail}
anilistEntries={anilistEntries ?? []}
group={group}
groupBusy={groupBusyTargetId !== null}
onMoveToGroup={() => {
setGroupError(null);
setShowGroupPicker(true);
}}
onSetGroupMode={(mode) => void applyGroupOverride({ mode }, animeId)}
coverRetryToken={coverRetryToken}
onChangeAnilist={() => setShowAnilistSelector(true)}
onChangeTmdb={() => setShowTmdbSelector(true)}
@@ -226,6 +274,25 @@ export function AnimeDetailView({
isDeletingAnime={isDeletingAnime}
/>
{deleteError ? <div className="text-sm text-ctp-red">{deleteError}</div> : null}
{groupError && !showGroupPicker ? (
<div role="alert" className="text-sm text-ctp-red">
{groupError}
</div>
) : null}
{showGroupPicker && (
<LibraryEntryPicker
heading="Move to another anime"
mediaKind="anime"
excludeAnimeIds={[animeId]}
filter={(entry) => entry.anilistId !== null}
busyAnimeId={groupBusyTargetId}
error={groupError}
onSelect={(entry) =>
void applyGroupOverride({ mode: 'join', targetAnimeId: entry.animeId }, entry.animeId)
}
onClose={() => setShowGroupPicker(false)}
/>
)}
<AnimeOverviewStats detail={detail} knownWordsSummary={knownWordsSummary} />
<EpisodeList
episodes={episodes}
@@ -0,0 +1,87 @@
import { describeAnimePart } from '../../lib/anime-groups';
import { formatDuration, formatNumber, formatRelativeDate } from '../../lib/formatters';
import type { AnimeLibraryGroup } from '../../types/stats';
import { AnimeCoverImage } from './AnimeCoverImage';
interface AnimeGroupViewProps {
group: AnimeLibraryGroup;
onBack: () => void;
onOpenPart: (animeId: number) => void;
}
/** A franchise card opened: its library entries in release order, each opening its own page. */
export function AnimeGroupView({ group, onBack, onOpenPart }: AnimeGroupViewProps) {
const cover = group.parts.find((part) => part.animeId === group.coverAnimeId) ?? group.parts[0]!;
return (
<div className="space-y-4">
<button
type="button"
onClick={onBack}
className="text-sm text-ctp-blue hover:text-ctp-sapphire transition-colors"
>
&larr; Back to Library
</button>
<div className="flex gap-4">
<AnimeCoverImage
animeId={cover.animeId}
title={group.title}
coverRetryToken={cover.anilistId ?? 0}
className="w-32 h-44 rounded-lg shrink-0"
/>
<div className="flex-1 min-w-0">
<h2 className="text-lg font-bold text-ctp-text truncate">{group.title}</h2>
<div className="text-sm text-ctp-subtext0 mt-2">
{group.parts.length} parts · {group.episodeCount} episode
{group.episodeCount !== 1 ? 's' : ''}
</div>
<div className="text-xs text-ctp-overlay2 mt-1">
{formatDuration(group.totalActiveMs)} · {formatNumber(group.totalCards)} cards
{group.lastWatchedMs > 0
? ` · last watched ${formatRelativeDate(group.lastWatchedMs)}`
: ''}
</div>
<p className="text-xs text-ctp-overlay2 mt-3 leading-relaxed">
Grouped by AniList&apos;s season, movie and side-story links. Open a part to move it to
another anime or show it on its own.
</p>
</div>
</div>
<div className="bg-ctp-surface0 border border-ctp-surface1 rounded-lg p-4">
<h3 className="text-sm font-semibold text-ctp-text mb-3">Seasons and Movies</h3>
<ul className="space-y-1">
{group.parts.map((part) => {
const kind = describeAnimePart(part.format, part.startDate);
return (
<li key={part.animeId}>
<button
type="button"
onClick={() => onOpenPart(part.animeId)}
className="w-full flex items-center gap-3 p-2.5 rounded-lg hover:bg-ctp-surface1 transition-colors text-left"
>
<AnimeCoverImage
animeId={part.animeId}
title={part.canonicalTitle}
coverRetryToken={part.anilistId ?? part.tmdbId ?? 0}
className="w-10 h-14 rounded shrink-0"
/>
<div className="min-w-0 flex-1">
<div className="text-sm text-ctp-text truncate">{part.canonicalTitle}</div>
<div className="text-xs text-ctp-overlay2 mt-0.5">
{kind ? `${kind} · ` : ''}
{part.episodeCount} episode{part.episodeCount !== 1 ? 's' : ''}
</div>
</div>
<div className="text-xs text-ctp-overlay2 text-right shrink-0">
<div>{formatDuration(part.totalActiveMs)}</div>
<div>{formatNumber(part.totalCards)} cards</div>
</div>
</button>
</li>
);
})}
</ul>
</div>
</div>
);
}
@@ -0,0 +1,134 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { apiClient } from '../../lib/api-client';
import type {
AnimeDetailData,
AnimeLibraryGroup,
AnimeLibraryGroupPart,
StatsAnimeGroupOverrideRequest,
} from '../../types/stats';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
function part(
animeId: number,
title: string,
format: string,
startDate: number,
): AnimeLibraryGroupPart {
return {
mediaKind: 'anime',
animeId,
canonicalTitle: title,
anilistId: animeId * 100,
tmdbId: null,
tmdbType: null,
totalSessions: 1,
totalActiveMs: 60_000,
totalCards: 2,
totalTokensSeen: 0,
episodeCount: format === 'MOVIE' ? 1 : 13,
episodesTotal: null,
lastWatchedMs: animeId,
format,
startDate,
};
}
const overlord: AnimeLibraryGroup = {
groupKey: 20832,
title: 'Overlord',
mediaKind: 'anime',
coverAnimeId: 2,
totalSessions: 2,
totalActiveMs: 120_000,
totalCards: 4,
totalTokensSeen: 0,
episodeCount: 14,
lastWatchedMs: 2,
parts: [part(2, 'The Undead King', 'MOVIE', 20170225), part(1, 'Overlord II', 'TV', 20180109)],
};
function detailData(): AnimeDetailData {
const {
format: _format,
startDate: _startDate,
episodesTotal: _total,
...item
} = part(1, 'Overlord II', 'TV', 20180109);
return {
detail: {
...item,
titleRomaji: null,
titleEnglish: null,
titleNative: null,
description: null,
totalLinesSeen: 0,
totalLookupCount: 0,
totalLookupHits: 0,
totalYomitanLookupCount: 0,
},
episodes: [],
anilistEntries: [],
group: { groupKey: 20832, title: 'Overlord', partCount: 2, overrideMode: 'anilist' },
};
}
function findButton(container: Element, label: string): HTMLElement {
const match = [...container.querySelectorAll('button')].find((button) =>
(button.textContent ?? '').includes(label),
);
assert.ok(match, `expected a "${label}" button`);
return match as unknown as HTMLElement;
}
test('a franchise card opens its parts in release order, and a part can stand alone', async () => {
const uninstallDom = installDom();
const original = { ...apiClient };
const overrides: Array<[number, StatsAnimeGroupOverrideRequest]> = [];
let libraryFetches = 0;
apiClient.getAnimeLibraryGroups = async () => {
libraryFetches += 1;
return [overlord];
};
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
apiClient.getAnimeDetail = async () => detailData();
apiClient.getAnimeWords = async () => [];
apiClient.getAnimeRollups = async () => [];
apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 });
apiClient.setAnimeGroupOverride = async (animeId, request) => {
overrides.push([animeId, request]);
};
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
try {
await act(async () => root.render(<AnimeTab />));
// One card for the franchise, counted once, with the first-released part's cover.
assert.match(container.textContent ?? '', /1 title/);
assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/);
assert.match(container.querySelector('img')?.getAttribute('src') ?? '', /anime\/2\/cover/);
await act(async () => findButton(container, 'Overlord').click());
const rows = [...container.querySelectorAll('li button')].map((row) => row.textContent ?? '');
assert.equal(rows.length, 2);
assert.match(rows[0]!, /The Undead King.*Movie · 2017/);
assert.match(rows[1]!, /Overlord II.*TV · 2018/);
await act(async () => findButton(container, 'Overlord II').click());
assert.match(container.textContent ?? '', /Listed under Overlord with 1 other part/);
await act(async () => findButton(container, 'Show On Its Own').click());
assert.deepEqual(overrides, [[1, { mode: 'standalone' }]]);
assert.equal(libraryFetches, 2);
await act(async () => findButton(container, 'Back to Overlord').click());
assert.match(container.textContent ?? '', /Seasons and Movies/);
} finally {
await act(async () => root.unmount());
Object.assign(apiClient, original);
uninstallDom();
}
});
+57 -1
View File
@@ -1,9 +1,17 @@
import { AnimeCoverImage } from './AnimeCoverImage';
import type { AnimeDetailData, AnilistEntry } from '../../types/stats';
import type { AnimeDetailData, AnimeGroupPlacement, AnilistEntry } from '../../types/stats';
const SECONDARY_BUTTON_CLASS =
'inline-flex items-center gap-1 px-2 py-1 text-xs rounded bg-ctp-surface1 text-ctp-overlay2 hover:bg-ctp-surface2 hover:text-ctp-subtext0 transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
interface AnimeHeaderProps {
detail: AnimeDetailData['detail'];
anilistEntries: AnilistEntry[];
/** The franchise card this entry is listed under; null hides the grouping actions. */
group?: AnimeGroupPlacement | null;
onMoveToGroup?: () => void;
onSetGroupMode?: (mode: 'standalone' | 'anilist') => void;
groupBusy?: boolean;
coverRetryToken?: number;
onChangeAnilist?: () => void;
onChangeTmdb?: () => void;
@@ -33,6 +41,10 @@ function AnilistButton({ entry }: { entry: AnilistEntry }) {
export function AnimeHeader({
detail,
anilistEntries,
group = null,
onMoveToGroup,
onSetGroupMode,
groupBusy = false,
coverRetryToken = 0,
onChangeAnilist,
onChangeTmdb,
@@ -52,6 +64,9 @@ export function AnimeHeader({
? `https://www.themoviedb.org/${detail.tmdbType}/${detail.tmdbId}`
: null;
const coverCacheToken = (detail.anilistId ?? detail.tmdbId ?? 0) * 1_000_000 + coverRetryToken;
// Only anime entries are grouped by AniList relations.
const placement = detail.mediaKind === 'anime' ? group : null;
const otherParts = placement ? placement.partCount - 1 : 0;
return (
<div className="flex gap-4">
@@ -80,6 +95,11 @@ export function AnimeHeader({
</span>
)}
</div>
{placement && otherParts > 0 && (
<div className="text-xs text-ctp-overlay2 mt-1">
Listed under {placement.title} with {otherParts} other part{otherParts !== 1 ? 's' : ''}
</div>
)}
<div className="flex flex-wrap gap-1.5 mt-2">
{tmdbUrl && (
<a
@@ -138,6 +158,42 @@ export function AnimeHeader({
{tmdbUrl ? 'Change TMDB Title' : 'Link to TMDB'}
</button>
)}
{placement && onMoveToGroup && (
<button
type="button"
onClick={onMoveToGroup}
disabled={groupBusy}
title="List this entry with another anime's seasons and movies"
className={SECONDARY_BUTTON_CLASS}
>
{'Move to Another Anime\u2026'}
</button>
)}
{placement && onSetGroupMode && placement.overrideMode !== 'anilist' && (
<button
type="button"
onClick={() => onSetGroupMode('anilist')}
disabled={groupBusy}
title="Undo a manual move and group this entry by its AniList relations"
className={SECONDARY_BUTTON_CLASS}
>
Put Back Where AniList Has It
</button>
)}
{placement &&
onSetGroupMode &&
placement.overrideMode === 'anilist' &&
otherParts > 0 && (
<button
type="button"
onClick={() => onSetGroupMode('standalone')}
disabled={groupBusy}
title="List this entry as its own card instead of with its franchise"
className={SECONDARY_BUTTON_CLASS}
>
Show On Its Own
</button>
)}
{onDeleteAnime && (
<button
type="button"
@@ -7,6 +7,7 @@ import type { AnimeLibraryItem, StatsMergeAnimeResponse } from '../../types/stat
import { AnimeMergeDialog } from './AnimeMergeDialog';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(animeId: number, title: string, episodeCount: number): AnimeLibraryItem {
return {
@@ -52,7 +53,7 @@ function mergeButton(container: Element): HTMLButtonElement {
test('AnimeTab merges the selected duplicate entries into the chosen keeper', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
mergeAnime: apiClient.mergeAnime,
};
@@ -61,10 +62,10 @@ test('AnimeTab merges the selected duplicate entries into the chosen keeper', as
let libraryFetches = 0;
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return entries;
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.mergeAnime = (async (targetAnimeId: number, sourceAnimeIds: number[]) => {
mergeCall = { targetAnimeId, sourceAnimeIds };
entries = [libraryItem(1, 'Show', 3)];
@@ -181,7 +182,7 @@ test('AnimeMergeDialog refuses to merge an AniList entry with a TMDB entry', asy
test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merged', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
mergeAnime: apiClient.mergeAnime,
@@ -191,7 +192,7 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] }];
let mergeCall: { targetAnimeId: number; sourceAnimeIds: number[] } | null = null;
apiClient.getAnimeLibrary = (async () => entries) as typeof apiClient.getAnimeLibrary;
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => entries);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations,
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -252,16 +253,16 @@ test('AnimeTab keeps a suggested duplicate visible until it is reviewed and merg
test('AnimeTab dismisses a false-positive duplicate recommendation', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
let dismissedId: number | null = null;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Different Show', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 73, animeIds: [1, 2] }],
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -291,16 +292,16 @@ test('AnimeTab dismisses a false-positive duplicate recommendation', async () =>
test('AnimeTab refreshes the library and recommendations when the window regains focus', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let entries = [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
let libraryFetches = 0;
let recommendationFetches = 0;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return entries;
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeMergeRecommendations = (async () => {
recommendationFetches += 1;
return { recommendations: [] };
@@ -330,14 +331,14 @@ test('AnimeTab refreshes the library and recommendations when the window regains
test('AnimeTab keeps a recommendation visible through a transient refresh failure', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let failRecommendations = false;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => {
if (failRecommendations) throw new Error('temporary failure');
return { recommendations: [{ recommendationId: 41, animeIds: [1, 2] }] };
@@ -364,14 +365,14 @@ test('AnimeTab keeps a recommendation visible through a transient refresh failur
test('AnimeTab retains a recommendation and reports a failed dismissal', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [{ recommendationId: 41, animeIds: [1, 2] }],
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -399,14 +400,14 @@ test('AnimeTab retains a recommendation and reports a failed dismissal', async (
test('AnimeTab keeps an open recommendation review stable during background refresh', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let recommendations = [{ recommendationId: 41, animeIds: [1, 2] as [number, number] }];
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations,
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -434,14 +435,14 @@ test('AnimeTab keeps an open recommendation review stable during background refr
test('AnimeTab keeps the library visible through a transient background refresh failure', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
let failLibrary = false;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
if (failLibrary) throw new Error('temporary failure');
return [libraryItem(1, 'Show', 2), libraryItem(2, 'Show Season 1', 1)];
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeMergeRecommendations = (async () => ({
recommendations: [],
})) as typeof apiClient.getAnimeMergeRecommendations;
@@ -470,7 +471,7 @@ test('AnimeTab keeps the library visible through a transient background refresh
test('AnimeTab does not resurrect a dismissed recommendation from a stale in-flight refresh', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
dismissAnimeMergeRecommendation: apiClient.dismissAnimeMergeRecommendation,
};
@@ -479,10 +480,10 @@ test('AnimeTab does not resurrect a dismissed recommendation from a stale in-fli
};
let holdNextFetch = false;
let releaseHeldFetch: (() => void) | null = null;
apiClient.getAnimeLibrary = (async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
libraryItem(1, 'Show', 2),
libraryItem(2, 'Show Season 1', 1),
]) as typeof apiClient.getAnimeLibrary;
]);
apiClient.getAnimeMergeRecommendations = ((): Promise<typeof payload> => {
if (!holdNextFetch) return Promise.resolve(payload);
holdNextFetch = false;
+12 -10
View File
@@ -6,6 +6,7 @@ import { apiClient } from '../../lib/api-client';
import type { AnimeDetailData, AnimeLibraryItem } from '../../types/stats';
import { AnimeTab } from './AnimeTab';
import { installDom } from '../../test-utils/dom';
import { singleGroupLibrary } from '../../test-utils/library';
function libraryItem(anilistId: number | null): AnimeLibraryItem {
return {
@@ -51,6 +52,7 @@ function detailData(anilistId: number | null): AnimeDetailData {
},
episodes: [],
anilistEntries: [],
group: null,
};
}
@@ -65,7 +67,7 @@ function findButton(container: Element, label: string): HTMLElement {
test('AnimeTab refetches the library after the AniList entry is relinked', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeDetail: apiClient.getAnimeDetail,
getAnimeWords: apiClient.getAnimeWords,
getAnimeRollups: apiClient.getAnimeRollups,
@@ -79,10 +81,10 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
let anilistId: number | null = 14813;
let libraryFetches = 0;
apiClient.getAnimeLibrary = (async () => {
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => {
libraryFetches += 1;
return [libraryItem(anilistId)];
}) as typeof apiClient.getAnimeLibrary;
});
apiClient.getAnimeDetail = (async () => detailData(anilistId)) as typeof apiClient.getAnimeDetail;
apiClient.getAnimeWords = (async () => []) as typeof apiClient.getAnimeWords;
apiClient.getAnimeRollups = (async () => []) as typeof apiClient.getAnimeRollups;
@@ -150,8 +152,8 @@ test('AnimeTab refetches the library after the AniList entry is relinked', async
test('AnimeTab watch time follows the displayed kind filter', async () => {
const uninstallDom = installDom();
const original = apiClient.getAnimeLibrary;
apiClient.getAnimeLibrary = async () => [
const original = apiClient.getAnimeLibraryGroups;
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(42), totalActiveMs: 3600000 },
{
...libraryItem(null),
@@ -162,7 +164,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
tmdbType: 'tv',
totalActiveMs: 7200000,
},
];
]);
const container = document.createElement('div');
document.body.append(container);
const root = createRoot(container);
@@ -180,7 +182,7 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
await act(async () => {
root.unmount();
});
apiClient.getAnimeLibrary = original;
apiClient.getAnimeLibraryGroups = original;
uninstallDom();
}
});
@@ -188,10 +190,10 @@ test('AnimeTab watch time follows the displayed kind filter', async () => {
test('Library kind filter separates YouTube channels from anime and updates totals', async () => {
const uninstallDom = installDom();
const original = {
getAnimeLibrary: apiClient.getAnimeLibrary,
getAnimeLibraryGroups: apiClient.getAnimeLibraryGroups,
getAnimeMergeRecommendations: apiClient.getAnimeMergeRecommendations,
};
apiClient.getAnimeLibrary = async () => [
apiClient.getAnimeLibraryGroups = singleGroupLibrary(async () => [
{ ...libraryItem(null), totalActiveMs: 60_000 },
{
...libraryItem(null),
@@ -200,7 +202,7 @@ test('Library kind filter separates YouTube channels from anime and updates tota
canonicalTitle: 'Language Channel',
totalActiveMs: 120_000,
},
];
]);
apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] });
const container = document.createElement('div');
document.body.append(container);
+65 -9
View File
@@ -5,6 +5,7 @@ import {
} from '../../../../src/shared/media-kind';
import { useState, useMemo, useEffect } from 'react';
import { useAnimeLibrary } from '../../hooks/useAnimeLibrary';
import { groupCardData, groupMatchesSearch } from '../../lib/anime-groups';
import { formatDuration } from '../../lib/formatters';
import {
getLibraryCardSizeStorage,
@@ -14,6 +15,7 @@ import {
} from '../../lib/library-card-size';
import { AnimeCard } from './AnimeCard';
import { AnimeDetailView } from './AnimeDetailView';
import { AnimeGroupView } from './AnimeGroupView';
import { AnimeMergeDialog } from './AnimeMergeDialog';
import { DuplicateReviewStrip } from './DuplicateReviewStrip';
@@ -39,7 +41,14 @@ const SORT_OPTIONS: { key: SortKey; label: string }[] = [
{ key: 'episodes', label: 'Episodes' },
];
function sortAnime(list: ReturnType<typeof useAnimeLibrary>['anime'], key: SortKey) {
interface SortableEntry {
lastWatchedMs: number;
totalActiveMs: number;
totalCards: number;
episodeCount: number;
}
function sortAnime<T extends SortableEntry>(list: T[], key: SortKey): T[] {
return [...list].sort((a, b) => {
switch (key) {
case 'lastWatched':
@@ -68,6 +77,7 @@ export function AnimeTab({
onOpenEpisodeDetail,
}: AnimeTabProps) {
const {
groups,
anime,
loading,
error,
@@ -87,6 +97,8 @@ export function AnimeTab({
),
);
const [selectedAnimeId, setSelectedAnimeId] = useState<number | null>(null);
// Franchise card that is open, and stays the back target while one of its parts is open.
const [selectedGroupKey, setSelectedGroupKey] = useState<number | null>(null);
const [selectionMode, setSelectionMode] = useState(false);
const [checkedAnimeIds, setCheckedAnimeIds] = useState<number[]>([]);
const [showMergeDialog, setShowMergeDialog] = useState(false);
@@ -115,11 +127,14 @@ export function AnimeTab({
useEffect(() => {
if (initialAnimeId != null) {
setSelectedGroupKey(null);
setSelectedAnimeId(initialAnimeId);
onClearInitialAnime?.();
}
}, [initialAnimeId, onClearInitialAnime]);
// Merging works on individual entries, so selection mode lists every entry
// on its own; browsing lists one card per franchise.
const filtered = useMemo(() => {
const entries = anime.filter((entry) => mediaKind === 'all' || entry.mediaKind === mediaKind);
const base = search.trim()
@@ -127,8 +142,25 @@ export function AnimeTab({
: entries;
return sortAnime(base, sortKey);
}, [anime, search, sortKey, mediaKind]);
const filteredGroups = useMemo(
() =>
sortAnime(
groups.filter(
(group) =>
(mediaKind === 'all' || group.mediaKind === mediaKind) &&
groupMatchesSearch(group, search),
),
sortKey,
),
[groups, search, sortKey, mediaKind],
);
const shownCount = selectionMode ? filtered.length : filteredGroups.length;
const totalMs = filtered.reduce((sum, a) => sum + a.totalActiveMs, 0);
const totalMs = (selectionMode ? filtered : filteredGroups).reduce(
(sum, entry) => sum + entry.totalActiveMs,
0,
);
const selectedGroup = groups.find((group) => group.groupKey === selectedGroupKey) ?? null;
const checkedEntries = checkedAnimeIds
.map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined);
@@ -160,6 +192,7 @@ export function AnimeTab({
return (
<AnimeDetailView
animeId={selectedAnimeId}
backLabel={selectedGroup ? `Back to ${selectedGroup.title}` : undefined}
onBack={() => setSelectedAnimeId(null)}
onNavigateToWord={onNavigateToWord}
onOpenEpisodeDetail={
@@ -170,6 +203,17 @@ export function AnimeTab({
onAnimeDeleted={reload}
onProviderRelinked={reload}
onEpisodeMoved={reload}
onGroupChanged={reload}
/>
);
}
if (selectedGroup && selectedGroup.parts.length > 1) {
return (
<AnimeGroupView
group={selectedGroup}
onBack={() => setSelectedGroupKey(null)}
onOpenPart={setSelectedAnimeId}
/>
);
}
@@ -250,12 +294,12 @@ export function AnimeTab({
{selectionMode ? 'Cancel' : 'Select'}
</button>
<div className="text-xs text-ctp-overlay2 shrink-0">
{filtered.length}{' '}
{shownCount}{' '}
{mediaKind === 'youtube'
? filtered.length === 1
? shownCount === 1
? 'channel'
: 'channels'
: filtered.length === 1
: shownCount === 1
? 'title'
: 'titles'}{' '}
· {formatDuration(totalMs)}
@@ -298,18 +342,30 @@ export function AnimeTab({
</div>
)}
{filtered.length === 0 ? (
{shownCount === 0 ? (
<div className="text-sm text-ctp-overlay2 p-4">No titles found</div>
) : (
) : selectionMode ? (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filtered.map((item) => (
<AnimeCard
key={item.animeId}
anime={item}
selectable={selectionMode}
selectable
selected={checkedAnimeIds.includes(item.animeId)}
onClick={() => toggleChecked(item.animeId)}
/>
))}
</div>
) : (
<div className={`grid ${GRID_CLASSES[cardSize]} gap-4`}>
{filteredGroups.map((group) => (
<AnimeCard
key={group.groupKey}
anime={groupCardData(group)}
onClick={() =>
selectionMode ? toggleChecked(item.animeId) : setSelectedAnimeId(item.animeId)
group.parts.length > 1
? setSelectedGroupKey(group.groupKey)
: setSelectedAnimeId(group.parts[0]!.animeId)
}
/>
))}
@@ -12,6 +12,8 @@ interface LibraryEntryPickerProps {
excludeAnimeIds?: number[];
/** When set, only entries of this kind are offered. */
mediaKind?: MediaKind;
/** Further narrows the entries offered. */
filter?: (entry: AnimeLibraryItem) => boolean;
initialQuery?: string;
busyAnimeId?: number | null;
error?: string | null;
@@ -23,6 +25,7 @@ export function LibraryEntryPicker({
heading,
excludeAnimeIds = [],
mediaKind,
filter,
initialQuery = '',
busyAnimeId = null,
error = null,
@@ -74,9 +77,10 @@ export function LibraryEntryPicker({
return (entries ?? [])
.filter((entry) => !excluded.has(entry.animeId))
.filter((entry) => mediaKind === undefined || shareTitleNamespace(entry.mediaKind, mediaKind))
.filter((entry) => filter === undefined || filter(entry))
.filter((entry) => !term || entry.canonicalTitle.toLowerCase().includes(term))
.sort((a, b) => b.lastWatchedMs - a.lastWatchedMs);
}, [entries, excluded, mediaKind, query]);
}, [entries, excluded, mediaKind, filter, query]);
return (
<div