Implemented the new react version of the frontend

This commit is contained in:
Mohammed Abad committed 2026-03-31 01:56:38 +01:00
1 parent 236e6e06fb
commit ffe7e52527
65 files changed
+5228 -177

No files matched your search

+64
View File
@@ -1829,6 +1829,70 @@
"node": ">=14.0.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
"version": "1.8.1",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.1.0",
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "1.8.1",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
"version": "1.1.0",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.1",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "^1.7.1",
"@emnapi/runtime": "^1.7.1",
"@tybys/wasm-util": "^0.10.1"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
"version": "0.10.1",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
"version": "2.8.1",
"dev": true,
"inBundle": true,
"license": "0BSD",
"optional": true
},
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz",
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+20 -117
View File
@@ -1,121 +1,24 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './App.css'
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { TooltipProvider } from '@/components/ui/tooltip';
import { router } from './router';
function App() {
const [count, setCount] = useState(0)
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 2 * 60 * 1000,
},
},
});
export function App() {
return (
<>
<section id="center">
<div className="hero">
<img src={heroImg} className="base" width="170" height="179" alt="" />
<img src={reactLogo} className="framework" alt="React logo" />
<img src={viteLogo} className="vite" alt="Vite logo" />
</div>
<div>
<h1>Get started</h1>
<p>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
</p>
</div>
<button
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
</section>
<div className="ticks"></div>
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
</div>
</section>
<div className="ticks"></div>
<section id="spacer"></section>
</>
)
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<RouterProvider router={router} />
</TooltipProvider>
</QueryClientProvider>
);
}
export default App
+41
View File
@@ -0,0 +1,41 @@
import { api } from '@/lib/api';
import { normalizeCollection } from '@/lib/normalizers';
import type { Collection } from '@/types';
export const collectionsApi = {
getAll: () =>
api
.get<Collection[]>('/collections')
.then((r) => r.data.map(normalizeCollection)),
getById: (id: number) =>
api
.get<Collection>(`/collections/${id}`)
.then((r) => normalizeCollection(r.data)),
create: (data: Partial<Collection>) =>
api.post<Collection>('/collections', data).then((r) => r.data),
update: (id: number, data: Partial<Collection>) =>
api.put<Collection>(`/collections/${id}`, data).then((r) => normalizeCollection(r.data)),
updateWithMedia: (id: number, formData: FormData) =>
api
.put<Collection>(`/collections/${id}`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((r) => normalizeCollection(r.data)),
delete: (id: number) =>
api.delete(`/collections/${id}`).then((r) => r.data),
addEntry: (collectionId: number, entryId: number) =>
api
.post(`/collections/${collectionId}/entries`, { entry_id: entryId })
.then((r) => r.data),
removeEntry: (collectionId: number, entryId: number) =>
api
.delete(`/collections/${collectionId}/entries/${entryId}`)
.then((r) => r.data),
};
+58
View File
@@ -0,0 +1,58 @@
import { api } from '@/lib/api';
import { normalizeEntry } from '@/lib/normalizers';
import type { Entry } from '@/types';
export const entriesApi = {
getAll: () =>
api.get<Entry[]>('/entries').then((r) => r.data.map(normalizeEntry)),
getById: (id: number) =>
api.get<Entry>(`/entries/${id}`).then((r) => normalizeEntry(r.data)),
create: (tmdb_id: number, is_tvserie: boolean) =>
api.post<Entry>('/entries', { tmdb_id, is_tvserie }).then((r) => normalizeEntry(r.data)),
update: (id: number, data: Partial<Entry>) =>
api.put<Entry>(`/entries/${id}`, data).then((r) => normalizeEntry(r.data)),
updateRatings: (
id: number,
ratings: {
user_rating?: number | null;
tmdb_rating?: number | null;
imdb_rating?: number | null;
rotten_tomatoes_rating?: number | null;
}
) => api.put(`/entries/${id}/ratings`, ratings).then((r) => r.data),
updateIds: (
id: number,
ids: { tmdb_id?: number; imdb_id?: string; tvdb_id?: number }
) => api.put(`/entries/${id}/ids`, ids).then((r) => r.data),
delete: (id: number) => api.delete(`/entries/${id}`).then((r) => r.data),
refresh: (id: number) =>
api.put<Entry>(`/entries/${id}/refresh`).then((r) => normalizeEntry(r.data)),
fetchCollection: (id: number) =>
api.put(`/entries/${id}/fetch-collection`).then((r) => r.data),
getSeasons: (id: number) =>
api.get(`/entries/${id}/seasons`).then((r) => Array.isArray(r.data) ? r.data : []),
syncSeries: () => api.get('/entries/sync-series').then((r) => r.data),
uploadMedia: (id: number, formData: FormData) =>
api
.post(`/entries/${id}/media`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((r) => r.data),
setMediaSelected: (entryId: number, mediaId: number) =>
api.put(`/entries/${entryId}/media/${mediaId}`).then((r) => r.data),
deleteMedia: (entryId: number, mediaId: number) =>
api.delete(`/entries/${entryId}/media/${mediaId}`).then((r) => r.data),
};
+20
View File
@@ -0,0 +1,20 @@
import { api } from '@/lib/api';
import type { EntrySeen } from '@/types';
export const entrySeenApi = {
getAll: () => api.get<EntrySeen[]>('/entry-seen').then((r) => r.data),
getById: (id: number) =>
api.get<EntrySeen>(`/entry-seen/${id}`).then((r) => r.data),
getByEntry: (entryId: number) =>
api.get<EntrySeen[]>(`/entry-seen/by-entry/${entryId}`).then((r) => r.data),
create: (data: { entry_id: number; date_seen: string; seen_with?: string }) =>
api.post<EntrySeen>('/entry-seen', data).then((r) => r.data),
update: (id: number, data: Partial<EntrySeen>) =>
api.put<EntrySeen>(`/entry-seen/${id}`, data).then((r) => r.data),
delete: (id: number) => api.delete(`/entry-seen/${id}`).then((r) => r.data),
};
+27
View File
@@ -0,0 +1,27 @@
import { api } from '@/lib/api';
import type { EpisodeSeen } from '@/types';
export const episodeSeenApi = {
getAll: () => api.get<EpisodeSeen[]>('/episode-seen').then((r) => r.data),
getById: (id: number) =>
api.get<EpisodeSeen>(`/episode-seen/${id}`).then((r) => r.data),
getByEpisode: (episodeId: number) =>
api
.get<EpisodeSeen[]>(`/episode-seen/by-episode/${episodeId}`)
.then((r) => r.data),
create: (data: {
entry_id: number;
episode_id: number;
date_seen: string;
seen_with?: string;
}) => api.post<EpisodeSeen>('/episode-seen', data).then((r) => r.data),
update: (id: number, data: Partial<EpisodeSeen>) =>
api.put<EpisodeSeen>(`/episode-seen/${id}`, data).then((r) => r.data),
delete: (id: number) =>
api.delete(`/episode-seen/${id}`).then((r) => r.data),
};
+9
View File
@@ -0,0 +1,9 @@
import { api } from '@/lib/api';
import type { Episode } from '@/types';
export const episodesApi = {
getByMonth: (startDate: string, endDate: string) =>
api
.get<Episode[]>(`/episodes/month/${startDate}/${endDate}`)
.then((r) => r.data),
};
+9
View File
@@ -0,0 +1,9 @@
import { api } from '@/lib/api';
import type { People } from '@/types';
export const peopleApi = {
getAll: () => api.get<People[]>('/people').then((r) => r.data),
getById: (id: number) =>
api.get<People>(`/people/${id}`).then((r) => r.data),
};
+20
View File
@@ -0,0 +1,20 @@
import { api } from '@/lib/api';
import type { Season } from '@/types';
export const seasonsApi = {
getAll: () => api.get<Season[]>('/seasons').then((r) => r.data),
getById: (id: number) =>
api.get<Season>(`/seasons/${id}`).then((r) => r.data),
getEpisodes: (id: number) =>
api.get(`/seasons/${id}/episodes`).then((r) => r.data),
create: (data: Partial<Season>) =>
api.post<Season>('/seasons', data).then((r) => r.data),
update: (id: number, data: Partial<Season>) =>
api.put<Season>(`/seasons/${id}`, data).then((r) => r.data),
delete: (id: number) => api.delete(`/seasons/${id}`).then((r) => r.data),
};
+9
View File
@@ -0,0 +1,9 @@
import { api } from '@/lib/api';
import type { Settings } from '@/types';
export const settingsApi = {
get: () => api.get<Settings>('/settings').then((r) => r.data),
update: (data: Partial<Settings>) =>
api.put<Settings>('/settings', data).then((r) => r.data),
};
+5
View File
@@ -0,0 +1,5 @@
import { api } from '@/lib/api';
export const statisticsApi = {
get: () => api.get('/statistics').then((r) => r.data),
};
+53
View File
@@ -0,0 +1,53 @@
import { api } from '@/lib/api';
import type { TmdbEntry, TmdbPaginatedResponse, TmdbPerson } from '@/types';
export const tmdbApi = {
getPopularMovies: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/popular/movie', {
params: { page },
})
.then((r) => r.data),
getPopularTv: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/popular/tv', {
params: { page },
})
.then((r) => r.data),
getTrendingMovies: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/trending/movie', {
params: { page },
})
.then((r) => r.data),
getTrendingTv: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/trending/tv', {
params: { page },
})
.then((r) => r.data),
search: (query: string, page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/search', {
params: { query, page },
})
.then((r) => r.data),
getPopularPeople: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbPerson>>('/people/tmdb/popular', {
params: { page },
})
.then((r) => r.data),
searchPeople: (query: string, page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbPerson>>('/people/tmdb/search', {
params: { query, page },
})
.then((r) => r.data),
};
@@ -0,0 +1,71 @@
import { Link } from 'react-router-dom';
import { getCollectionPosterUrl } from '@/lib/media-utils';
import { Skeleton } from '@/components/ui/skeleton';
import type { Collection } from '@/types';
interface CollectionCardProps {
collection: Collection;
}
export function CollectionCard({ collection }: CollectionCardProps) {
return (
<Link
to={`/collections/${collection.id}`}
className="group overflow-hidden rounded-lg transition-all hover:scale-[1.02] hover:shadow-lg"
>
<div className="relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-muted">
<img
src={getCollectionPosterUrl(collection)}
alt={collection.name}
className="h-full w-full object-cover transition-transform group-hover:scale-105"
loading="lazy"
/>
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-3">
<p className="text-sm font-medium text-white line-clamp-2">
{collection.name}
</p>
</div>
</div>
</Link>
);
}
export function CollectionCardSkeleton() {
return <Skeleton className="aspect-[2/3] w-full rounded-lg" />;
}
interface CollectionsGridProps {
collections: Collection[];
isLoading?: boolean;
}
export function CollectionsGrid({
collections,
isLoading,
}: CollectionsGridProps) {
if (isLoading) {
return (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{Array.from({ length: 12 }).map((_, i) => (
<CollectionCardSkeleton key={i} />
))}
</div>
);
}
if (collections.length === 0) {
return (
<div className="flex h-40 items-center justify-center text-muted-foreground">
No collections found.
</div>
);
}
return (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{collections.map((collection) => (
<CollectionCard key={collection.id} collection={collection} />
))}
</div>
);
}
@@ -0,0 +1,81 @@
import { useState } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useCollections } from '@/hooks/useCollections';
import { collectionsApi } from '@/api/collections';
import type { Collection } from '@/types';
interface AddEntryToCollectionDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
entryId: number;
entryCollections?: Collection[];
}
export function AddEntryToCollectionDialog({
open,
onOpenChange,
entryId,
entryCollections = [],
}: AddEntryToCollectionDialogProps) {
const [search, setSearch] = useState('');
const { data: allCollections = [] } = useCollections();
const entryCollectionIds = new Set(entryCollections.map((c) => c.id));
const filtered = allCollections.filter((c) =>
c.name.toLowerCase().includes(search.toLowerCase())
);
const handleToggle = async (collectionId: number, checked: boolean) => {
if (checked) {
await collectionsApi.addEntry(collectionId, entryId);
} else {
await collectionsApi.removeEntry(collectionId, entryId);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Add to Collection</DialogTitle>
</DialogHeader>
<Input
placeholder="Search collections..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<ScrollArea className="h-64">
<div className="space-y-2 pr-4">
{filtered.map((collection) => (
<label
key={collection.id}
className="flex cursor-pointer items-center gap-3 rounded-lg p-2 hover:bg-accent/50"
>
<Checkbox
checked={entryCollectionIds.has(collection.id)}
onCheckedChange={(checked) =>
handleToggle(collection.id, !!checked)
}
/>
<span className="text-sm">{collection.name}</span>
</label>
))}
{filtered.length === 0 && (
<p className="py-4 text-center text-sm text-muted-foreground">
No collections found.
</p>
)}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,203 @@
import { useState, useRef } from 'react';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { ImageIcon } from 'lucide-react';
import { useUpdateCollection } from '@/hooks/useCollections';
import type { Collection } from '@/types';
interface CollectionEditDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
collection: Collection;
}
export function CollectionEditDialog({
open,
onOpenChange,
collection,
}: CollectionEditDialogProps) {
const [name, setName] = useState(collection.name);
const [description, setDescription] = useState(collection.description || '');
const [userRating, setUserRating] = useState(
collection.user_rating?.toString() || ''
);
const [posterFile, setPosterFile] = useState<File | null>(null);
const [backdropFile, setBackdropFile] = useState<File | null>(null);
const [posterPreview, setPosterPreview] = useState<string | null>(null);
const [backdropPreview, setBackdropPreview] = useState<string | null>(null);
const posterInputRef = useRef<HTMLInputElement>(null);
const backdropInputRef = useRef<HTMLInputElement>(null);
const updateCollection = useUpdateCollection();
const handlePosterChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setPosterFile(file);
setPosterPreview(URL.createObjectURL(file));
}
};
const handleBackdropChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setBackdropFile(file);
setBackdropPreview(URL.createObjectURL(file));
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const formData = new FormData();
formData.append('name', name);
formData.append('description', description);
formData.append('userRating', userRating || '0');
if (posterFile) {
formData.append('poster', posterFile);
}
if (backdropFile) {
formData.append('backdrop', backdropFile);
}
updateCollection.mutate(
{ id: collection.id, data: formData },
{ onSuccess: () => onOpenChange(false) }
);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg!">
<DialogHeader>
<DialogTitle>Edit Collection</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 py-2">
<div className="space-y-2">
<Label htmlFor="col-name">Name</Label>
<Input
id="col-name"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="col-desc">Description</Label>
<Textarea
id="col-desc"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
/>
</div>
<div className="space-y-2">
<Label htmlFor="col-rating">User Rating (0-10)</Label>
<Input
id="col-rating"
type="number"
min={0}
max={10}
step={0.1}
value={userRating}
onChange={(e) => setUserRating(e.target.value)}
/>
</div>
{/* Media uploads */}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Poster</Label>
<input
ref={posterInputRef}
type="file"
accept="image/*"
onChange={handlePosterChange}
className="hidden"
/>
<Button
type="button"
variant="outline"
className="w-full h-20 flex flex-col gap-1"
onClick={() => posterInputRef.current?.click()}
>
{posterPreview ? (
<img
src={posterPreview}
alt="Poster preview"
className="h-14 w-auto rounded object-cover"
/>
) : (
<>
<ImageIcon className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">
Upload Poster
</span>
</>
)}
</Button>
</div>
<div className="space-y-2">
<Label>Backdrop</Label>
<input
ref={backdropInputRef}
type="file"
accept="image/*"
onChange={handleBackdropChange}
className="hidden"
/>
<Button
type="button"
variant="outline"
className="w-full h-20 flex flex-col gap-1"
onClick={() => backdropInputRef.current?.click()}
>
{backdropPreview ? (
<img
src={backdropPreview}
alt="Backdrop preview"
className="h-14 w-auto rounded object-cover"
/>
) : (
<>
<ImageIcon className="h-5 w-5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">
Upload Backdrop
</span>
</>
)}
</Button>
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="ghost"
onClick={() => onOpenChange(false)}
>
Cancel
</Button>
<Button type="submit" disabled={updateCollection.isPending}>
{updateCollection.isPending ? 'Saving...' : 'Save'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,53 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface ConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description: string;
confirmLabel?: string;
cancelLabel?: string;
onConfirm: () => void;
variant?: 'default' | 'destructive';
}
export function ConfirmDialog({
open,
onOpenChange,
title,
description,
confirmLabel = 'Confirm',
cancelLabel = 'Cancel',
onConfirm,
variant = 'default',
}: ConfirmDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{cancelLabel}
</Button>
<Button
variant={variant === 'destructive' ? 'destructive' : 'default'}
onClick={onConfirm}
>
{confirmLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,144 @@
import { useState } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Check, Trash2, Upload } from 'lucide-react';
import { getMediaUrl } from '@/lib/api';
import { entriesApi } from '@/api/entries';
import { useUploadMedia } from '@/hooks/useEntries';
import type { Media } from '@/types';
interface EntryMediaDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
entryId: number;
medias: Media[];
}
export function EntryMediaDialog({
open,
onOpenChange,
entryId,
medias,
}: EntryMediaDialogProps) {
const [activeTab, setActiveTab] = useState<string>('poster');
const uploadMedia = useUploadMedia();
const filteredMedias = medias.filter((m) => m.type === activeTab);
const handleUpload = (type: string) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = async (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
const formData = new FormData();
formData.append(type, file);
uploadMedia.mutate({ id: entryId, formData });
};
input.click();
};
const handleSelect = async (mediaId: number) => {
await entriesApi.setMediaSelected(entryId, mediaId);
};
const handleDelete = async (mediaId: number) => {
await entriesApi.deleteMedia(entryId, mediaId);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Entry Media</DialogTitle>
</DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="poster">Posters</TabsTrigger>
<TabsTrigger value="backdrop">Backdrops</TabsTrigger>
<TabsTrigger value="logo">Logos</TabsTrigger>
</TabsList>
<TabsContent value={activeTab} className="mt-4">
<div className="flex justify-end mb-3">
<Button
size="sm"
onClick={() => handleUpload(activeTab)}
disabled={uploadMedia.isPending}
>
<Upload className="mr-2 h-4 w-4" />
Upload {activeTab}
</Button>
</div>
<ScrollArea className="h-80">
{filteredMedias.length === 0 ? (
<p className="py-8 text-center text-sm text-muted-foreground">
No {activeTab}s found.
</p>
) : (
<div className="grid grid-cols-3 gap-3">
{filteredMedias.map((media) => (
<div
key={media.id}
className={`group relative overflow-hidden rounded-lg border-2 ${
media.is_selected
? 'border-primary'
: 'border-transparent'
}`}
>
<img
src={getMediaUrl(
'entries',
`${activeTab}s`,
'preview',
media.path
)}
alt={activeTab}
className="w-full object-cover"
loading="lazy"
/>
<div className="absolute inset-0 flex items-center justify-center gap-2 bg-black/60 opacity-0 transition-opacity group-hover:opacity-100">
<Button
size="icon"
variant="secondary"
className="h-8 w-8"
onClick={() => handleSelect(media.id)}
>
<Check className="h-4 w-4" />
</Button>
<Button
size="icon"
variant="destructive"
className="h-8 w-8"
onClick={() => handleDelete(media.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
{media.is_selected && (
<div className="absolute right-1 top-1 rounded-full bg-primary p-1">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
))}
</div>
)}
</ScrollArea>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,253 @@
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { format } from 'date-fns';
import { CalendarIcon } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { useCreateEntrySeen, useUpdateEntrySeen } from '@/hooks/useEntrySeen';
import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen';
import type { Entry, Season, EntrySeen } from '@/types';
const movieSeenSchema = z.object({
date_seen: z.string().min(1, 'Date is required'),
seen_with: z.string().optional(),
});
const tvSeenSchema = z.object({
season_id: z.string().min(1, 'Season is required'),
episode_id: z.string().min(1, 'Episode is required'),
date_seen: z.string().min(1, 'Date is required'),
seen_with: z.string().optional(),
});
interface EntrySeenDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
entry: Entry;
seasons?: Season[];
mode: 'add' | 'edit';
editRecord?: EntrySeen;
}
export function EntrySeenDialog({
open,
onOpenChange,
entry,
seasons,
mode,
editRecord,
}: EntrySeenDialogProps) {
const [date, setDate] = useState<Date | undefined>(
editRecord?.date_seen ? new Date(editRecord.date_seen) : new Date()
);
const [selectedSeasonId, setSelectedSeasonId] = useState<string>('');
const isTV = entry.is_tvseries;
const schema = isTV ? tvSeenSchema : movieSeenSchema;
const seasonList = Array.isArray(seasons) ? seasons : [];
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
defaultValues: {
date_seen: editRecord?.date_seen || format(new Date(), 'yyyy-MM-dd'),
seen_with: editRecord?.seen_with || '',
season_id: '',
episode_id: '',
},
});
const createEntrySeen = useCreateEntrySeen();
const updateEntrySeen = useUpdateEntrySeen();
const createEpisodeSeen = useCreateEpisodeSeen();
const selectedSeason = seasonList.find(
(s) => s.id.toString() === selectedSeasonId
);
const onSubmit = (data: Record<string, string | undefined>) => {
if (isTV && data.episode_id) {
createEpisodeSeen.mutate(
{
entry_id: entry.id,
episode_id: parseInt(data.episode_id),
date_seen: data.date_seen!,
seen_with: data.seen_with || undefined,
},
{ onSuccess: () => onOpenChange(false) }
);
} else if (mode === 'edit' && editRecord) {
updateEntrySeen.mutate(
{
id: editRecord.id,
data: {
entry_id: entry.id,
date_seen: data.date_seen,
seen_with: data.seen_with || undefined,
},
},
{ onSuccess: () => onOpenChange(false) }
);
} else {
createEntrySeen.mutate(
{
entry_id: entry.id,
date_seen: data.date_seen!,
seen_with: data.seen_with || undefined,
},
{ onSuccess: () => onOpenChange(false) }
);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{mode === 'edit' ? 'Edit Watch Record' : 'Mark as Watched'}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
{/* TV specific fields */}
{isTV && seasonList.length > 0 && (
<>
<div className="space-y-2">
<Label>Season</Label>
<Select
value={selectedSeasonId}
onValueChange={(v) => {
setSelectedSeasonId(v);
setValue('season_id', v);
setValue('episode_id', '');
}}
>
<SelectTrigger>
<SelectValue placeholder="Select season" />
</SelectTrigger>
<SelectContent>
{seasonList.map((s) => (
<SelectItem key={s.id} value={s.id.toString()}>
{s.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.season_id && (
<p className="text-xs text-destructive">
{errors.season_id.message}
</p>
)}
</div>
{selectedSeason?.episodes && (
<div className="space-y-2">
<Label>Episode</Label>
<Select onValueChange={(v) => setValue('episode_id', v)}>
<SelectTrigger>
<SelectValue placeholder="Select episode" />
</SelectTrigger>
<SelectContent>
{selectedSeason.episodes.map((ep) => (
<SelectItem key={ep.id} value={ep.id.toString()}>
E{ep.episode_number} - {ep.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.episode_id && (
<p className="text-xs text-destructive">
{errors.episode_id.message}
</p>
)}
</div>
)}
</>
)}
{/* Date picker */}
<div className="space-y-2">
<Label>Date Seen</Label>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
'w-full justify-start text-left font-normal',
!date && 'text-muted-foreground'
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, 'PPP') : <span>Pick a date</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={date}
onSelect={(d) => {
setDate(d);
if (d) setValue('date_seen', format(d, 'yyyy-MM-dd'));
}}
initialFocus
/>
</PopoverContent>
</Popover>
{errors.date_seen && (
<p className="text-xs text-destructive">
{errors.date_seen.message}
</p>
)}
</div>
{/* Seen with */}
<div className="space-y-2">
<Label htmlFor="seen_with">Seen With (optional)</Label>
<Input id="seen_with" {...register('seen_with')} placeholder="e.g. John, Jane" />
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
Cancel
</Button>
<Button type="submit">
{mode === 'edit' ? 'Save Changes' : 'Mark as Watched'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,56 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useUpdateEntry } from '@/hooks/useEntries';
import type { Entry } from '@/types';
interface EntrySettingsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
entry: Entry;
}
export function EntrySettingsDialog({
open,
onOpenChange,
entry,
}: EntrySettingsDialogProps) {
const updateEntry = useUpdateEntry();
const handleToggle = (field: keyof Entry, value: boolean) => {
updateEntry.mutate({ id: entry.id, data: { [field]: value } });
};
const settings = [
{ field: 'favorit' as const, label: 'Favorite' },
{ field: 'hidden' as const, label: 'Hidden' },
{ field: 'watchlist' as const, label: 'Watchlist' },
];
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Entry Settings</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
{settings.map(({ field, label }) => (
<div key={field} className="flex items-center justify-between">
<Label htmlFor={field}>{label}</Label>
<Switch
id={field}
checked={!!entry[field]}
onCheckedChange={(checked) => handleToggle(field, checked)}
/>
</div>
))}
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,60 @@
import { Link } from 'react-router-dom';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { getProfileUrl } from '@/lib/media-utils';
import type { Credit } from '@/types';
interface CastListProps {
credits: Credit[];
}
export function CastList({ credits }: CastListProps) {
const castCredits = credits.filter((c) => c.cast_type === 'cast');
if (castCredits.length === 0) return null;
return (
<div className="space-y-3">
<h3 className="text-lg font-semibold">Cast</h3>
<ScrollArea className="w-full">
<div className="flex gap-4 pb-4">
{castCredits.map((credit) => (
<CastCard key={credit.id} credit={credit} />
))}
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
);
}
function CastCard({ credit }: { credit: Credit }) {
const profileUrl = credit.people?.profile_path
? getProfileUrl(credit.people.profile_path)
: undefined;
return (
<Link
to={`/people/${credit.people_id}`}
className="flex w-28 shrink-0 flex-col items-center gap-2 text-center"
>
<Avatar className="h-20 w-20">
<AvatarImage src={profileUrl} alt={credit.people?.name} />
<AvatarFallback className="text-xs">
{credit.people?.name
?.split(' ')
.map((n) => n[0])
.join('')}
</AvatarFallback>
</Avatar>
<div>
<p className="text-xs font-medium leading-tight line-clamp-2">
{credit.people?.name}
</p>
<p className="text-[10px] text-muted-foreground leading-tight line-clamp-1">
{credit.character}
</p>
</div>
</Link>
);
}
@@ -0,0 +1,176 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, Trash2, Star } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { getPosterUrl, getYear, formatRuntime } from '@/lib/media-utils';
import { useCreateEntry, useDeleteEntry } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog';
import type { Entry, TmdbEntry } from '@/types';
interface EntryCardProps {
entry?: Entry;
tmdbEntry?: TmdbEntry;
}
export function EntryCard({ entry, tmdbEntry }: EntryCardProps) {
const [showConfirm, setShowConfirm] = useState(false);
const createEntry = useCreateEntry();
const deleteEntry = useDeleteEntry();
const libraryEntry = useLibraryStore((s) => {
if (entry?.isInLibrary) return entry;
if (tmdbEntry) {
for (const e of s.entries.values()) {
if (e.entryIds?.tmdb_id === tmdbEntry.id) return e;
}
}
return null;
});
const isInLibrary = !!libraryEntry;
const displayEntry = libraryEntry || entry;
// Resolve display data
const title =
displayEntry?.title || tmdbEntry?.title || tmdbEntry?.name || 'Untitled';
const year = displayEntry
? getYear(displayEntry.release_date)
: getYear(tmdbEntry?.release_date || tmdbEntry?.first_air_date || null);
const rating =
displayEntry?.entryRatings?.user_rating ||
displayEntry?.entryRatings?.tmdb_rating ||
tmdbEntry?.vote_average;
const runtime =
displayEntry && !displayEntry.is_tvseries
? formatRuntime(displayEntry.runtime)
: '';
const isTv =
displayEntry?.is_tvseries ||
tmdbEntry?.media_type === 'tv' ||
!!tmdbEntry?.name;
const posterUrl = displayEntry
? getPosterUrl(displayEntry)
: tmdbEntry?.poster_path
? `https://image.tmdb.org/t/p/w342${tmdbEntry.poster_path}`
: '/images/default-poster.png';
const entryLink = displayEntry
? `/entry/${displayEntry.id}`
: undefined;
const handleAdd = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (!tmdbEntry) return;
createEntry.mutate({ tmdb_id: tmdbEntry.id, is_tvserie: isTv });
};
const handleRemove = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
setShowConfirm(true);
};
const confirmRemove = () => {
if (libraryEntry) {
deleteEntry.mutate(libraryEntry.id);
}
setShowConfirm(false);
};
const card = (
<div className="group relative overflow-hidden rounded-lg transition-all duration-200 hover:scale-[1.02] hover:shadow-xl">
{/* Poster */}
<div className="relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-muted">
<img
src={posterUrl}
alt={title}
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
loading="lazy"
/>
{/* Library badge – only on home / search (tmdbEntry context) */}
{isInLibrary && tmdbEntry && (
<Badge className="absolute left-2 top-2 bg-primary text-primary-foreground text-[10px] px-1.5 py-0.5">
In Library
</Badge>
)}
{/* Favorite indicator */}
{libraryEntry?.favorit && (
<Star className="absolute right-2 top-2 h-4 w-4 fill-yellow-400 text-yellow-400" />
)}
{/* Hover overlay */}
<div className="absolute inset-0 flex flex-col justify-end bg-gradient-to-t from-black/90 via-black/40 to-transparent opacity-0 transition-opacity duration-200 group-hover:opacity-100">
<div className="p-3 space-y-1">
<p className="text-sm font-semibold text-white line-clamp-2">
{title}
</p>
<div className="flex items-center gap-2 text-xs text-white/70">
{rating != null && rating > 0 && (
<span className="flex items-center gap-1">
<Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
{typeof rating === 'number' ? rating.toFixed(1) : rating}
</span>
)}
{year && <span>{year}</span>}
{runtime && <span>{runtime}</span>}
</div>
{/* Actions */}
<div className="pt-1">
{isInLibrary ? (
<Button
size="sm"
variant="destructive"
className="h-7 w-full text-xs"
onClick={handleRemove}
>
<Trash2 className="mr-1 h-3 w-3" />
Remove
</Button>
) : tmdbEntry ? (
<Button
size="sm"
className="h-7 w-full text-xs"
onClick={handleAdd}
disabled={createEntry.isPending}
>
<Plus className="mr-1 h-3 w-3" />
{createEntry.isPending ? 'Adding...' : 'Add to Library'}
</Button>
) : null}
</div>
</div>
</div>
</div>
</div>
);
return (
<>
{entryLink ? <Link to={entryLink}>{card}</Link> : card}
<ConfirmDialog
open={showConfirm}
onOpenChange={setShowConfirm}
title="Remove from Library"
description={`Are you sure you want to remove "${title}" from your library? This action cannot be undone.`}
confirmLabel="Remove"
onConfirm={confirmRemove}
variant="destructive"
/>
</>
);
}
export function EntryCardSkeleton() {
return (
<div className="space-y-2">
<Skeleton className="aspect-[2/3] w-full rounded-lg" />
</div>
);
}
@@ -0,0 +1,72 @@
import { useCallback, useRef, useEffect } from 'react';
import { EntryCard, EntryCardSkeleton } from './EntryCard';
import type { Entry } from '@/types';
interface EntryLibraryGridProps {
entries: Entry[];
isLoading?: boolean;
hasMore?: boolean;
onLoadMore?: () => void;
}
export function EntryLibraryGrid({
entries,
isLoading,
hasMore,
onLoadMore,
}: EntryLibraryGridProps) {
const observerRef = useRef<IntersectionObserver | null>(null);
const lastEntryRef = useCallback(
(node: HTMLDivElement | null) => {
if (isLoading) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && hasMore && onLoadMore) {
onLoadMore();
}
});
if (node) observerRef.current.observe(node);
},
[isLoading, hasMore, onLoadMore]
);
useEffect(() => {
return () => observerRef.current?.disconnect();
}, []);
if (isLoading && entries.length === 0) {
return (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{Array.from({ length: 21 }).map((_, i) => (
<EntryCardSkeleton key={i} />
))}
</div>
);
}
if (entries.length === 0) {
return (
<div className="flex h-40 items-center justify-center text-muted-foreground">
No entries found.
</div>
);
}
return (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{entries.map((entry, index) => (
<div
key={entry.id}
ref={index === entries.length - 1 ? lastEntryRef : undefined}
>
<EntryCard entry={entry} />
</div>
))}
{isLoading &&
Array.from({ length: 7 }).map((_, i) => (
<EntryCardSkeleton key={`loading-${i}`} />
))}
</div>
);
}
@@ -0,0 +1,80 @@
import { format } from 'date-fns';
import type { EntrySeen, EpisodeSeen } from '@/types';
import { Button } from '@/components/ui/button';
import { Pencil, Trash2 } from 'lucide-react';
interface EpisodeWatchHistoryProps {
watchHistory: (EntrySeen | EpisodeSeen)[];
onEdit?: (id: number) => void;
onDelete?: (id: number) => void;
}
export function EpisodeWatchHistory({
watchHistory,
onEdit,
onDelete,
}: EpisodeWatchHistoryProps) {
if (watchHistory.length === 0) {
return (
<p className="text-sm text-muted-foreground">No watch history yet.</p>
);
}
return (
<div className="space-y-3">
<h3 className="text-lg font-semibold">Watch History</h3>
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-muted/50">
<th className="px-4 py-2 text-left font-medium">Date</th>
<th className="px-4 py-2 text-left font-medium">Seen With</th>
<th className="px-4 py-2 text-right font-medium">Actions</th>
</tr>
</thead>
<tbody>
{watchHistory.map((record) => (
<tr
key={record.id}
className="border-b border-border last:border-0"
>
<td className="px-4 py-2">
{record.date_seen
? format(new Date(record.date_seen), 'MMM d, yyyy')
: '-'}
</td>
<td className="px-4 py-2 text-muted-foreground">
{record.seen_with || '-'}
</td>
<td className="px-4 py-2">
<div className="flex justify-end gap-1">
{onEdit && (
<Button
size="icon"
variant="ghost"
className="h-7 w-7"
onClick={() => onEdit(record.id)}
>
<Pencil className="h-3 w-3" />
</Button>
)}
{onDelete && (
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-destructive"
onClick={() => onDelete(record.id)}
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,122 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { getYear, getTmdbPosterUrl } from '@/lib/media-utils';
import type { Season } from '@/types';
interface SeasonsContainerProps {
seasons: Season[];
entryId: number;
}
export function SeasonsContainer({
seasons,
entryId,
}: SeasonsContainerProps) {
const [expanded, setExpanded] = useState(false);
// Sort: specials (season 0) at bottom, rest latest to oldest
const sorted = [...seasons].sort((a, b) => {
if (a.season_number === 0) return 1;
if (b.season_number === 0) return -1;
return b.season_number - a.season_number;
});
const display = expanded ? sorted : sorted.slice(0, 2);
return (
<div className="space-y-3">
<h3 className="text-lg font-semibold">Seasons</h3>
<div className="space-y-2">
{display.map((season) => (
<SeasonItem key={season.id} season={season} entryId={entryId} />
))}
</div>
{sorted.length > 2 && (
<Button
variant="ghost"
size="sm"
onClick={() => setExpanded(!expanded)}
className="w-full"
>
{expanded ? (
<>
<ChevronUp className="mr-1 h-4 w-4" /> Show Less
</>
) : (
<>
<ChevronDown className="mr-1 h-4 w-4" /> Show All (
{sorted.length})
</>
)}
</Button>
)}
</div>
);
}
function SeasonItem({
season,
entryId,
}: {
season: Season;
entryId: number;
}) {
const watchedCount =
season.episodes?.filter(
(ep) => ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0)
).length ?? 0;
const totalEpisodes = season.episode_count || season.episodes?.length || 0;
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0;
return (
<Link
to={`/entry/${entryId}/season/${season.id}`}
className="flex items-center gap-4 rounded-lg border border-border p-3 transition-colors hover:bg-accent/50"
>
{/* Poster thumbnail */}
<div className="h-16 w-11 shrink-0 overflow-hidden rounded bg-muted">
<img
src={getTmdbPosterUrl(season.poster_path, 'w92')}
alt={season.name}
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-sm truncate">{season.name}</span>
<span className="text-xs text-muted-foreground">
{getYear(season.air_date)}
</span>
</div>
<div className="flex items-center gap-2 mt-1">
<Progress value={progress} className="h-1.5 flex-1" />
<span className="text-xs text-muted-foreground shrink-0">
{watchedCount}/{totalEpisodes}
</span>
</div>
</div>
{/* Quick watch button */}
{watchedCount < totalEpisodes && (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
// TODO: Mark next unwatched episode as seen
}}
>
<Play className="h-4 w-4" />
</Button>
)}
</Link>
);
}
@@ -0,0 +1,71 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { EntryCard, EntryCardSkeleton } from './EntryCard';
import type { TmdbEntry } from '@/types';
interface TrendingGridProps {
title: string;
movieEntries: TmdbEntry[];
tvEntries: TmdbEntry[];
isLoading?: boolean;
moreLink: string;
}
export function TrendingGrid({
title,
movieEntries,
tvEntries,
isLoading,
moreLink,
}: TrendingGridProps) {
const [activeTab, setActiveTab] = useState<'movie' | 'tv'>('movie');
const entries = activeTab === 'movie' ? movieEntries : tvEntries;
// Limit to 2 rows (14 items for a 7-column grid)
const displayEntries = entries.slice(0, 14);
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold">{title}</h2>
<div className="flex items-center gap-3">
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as 'movie' | 'tv')}
>
<TabsList className="h-8">
<TabsTrigger value="movie" className="text-xs px-3">
Movies
</TabsTrigger>
<TabsTrigger value="tv" className="text-xs px-3">
TV Series
</TabsTrigger>
</TabsList>
</Tabs>
<Button variant="ghost" size="sm" asChild>
<Link to={moreLink}>
More <ChevronRight className="ml-1 h-4 w-4" />
</Link>
</Button>
</div>
</div>
{isLoading ? (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{Array.from({ length: 14 }).map((_, i) => (
<EntryCardSkeleton key={i} />
))}
</div>
) : (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{displayEntries.map((tmdbEntry) => (
<EntryCard key={tmdbEntry.id} tmdbEntry={tmdbEntry} />
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,15 @@
import { Outlet } from 'react-router-dom';
import { Sidebar } from './Sidebar';
export function AppLayout() {
return (
<div className="flex min-h-screen">
<Sidebar />
<main className="ml-56 flex-1 overflow-y-auto">
<div className="container mx-auto px-6 py-6">
<Outlet />
</div>
</main>
</div>
);
}
@@ -0,0 +1,136 @@
import { NavLink } from 'react-router-dom';
import {
LayoutDashboard,
Home,
Library,
ListVideo,
FolderOpen,
Image,
CalendarDays,
Users,
Settings,
Moon,
Sun,
Film,
} from 'lucide-react';
import { useThemeStore } from '@/stores/useThemeStore';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
const mainNav = [
{ to: '/dashboard', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/', icon: Home, label: 'Home' },
];
const libraryNav = [
{ to: '/library', icon: Library, label: 'Library' },
{ to: '/watchlist', icon: ListVideo, label: 'Watchlist' },
{ to: '/collections', icon: FolderOpen, label: 'Collections' },
{ to: '/media', icon: Image, label: 'Media' },
];
const otherNav = [
{ to: '/calendar', icon: CalendarDays, label: 'Calendar' },
{ to: '/people', icon: Users, label: 'People' },
];
function NavItem({
to,
icon: Icon,
label,
}: {
to: string;
icon: React.ComponentType<{ className?: string }>;
label: string;
}) {
return (
<Tooltip>
<TooltipTrigger asChild>
<NavLink
to={to}
end={to === '/'}
className={({ isActive }) =>
`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${
isActive
? 'bg-sidebar-accent text-sidebar-primary font-medium'
: 'text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground'
}`
}
>
<Icon className="h-4 w-4 shrink-0" />
<span>{label}</span>
</NavLink>
</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
</Tooltip>
);
}
export function Sidebar() {
const { theme, toggleTheme } = useThemeStore();
return (
<aside className="fixed inset-y-0 left-0 z-50 flex w-56 flex-col border-r border-sidebar-border bg-sidebar">
{/* Logo */}
<div className="flex h-14 items-center gap-2 px-4">
<Film className="h-6 w-6 text-sidebar-primary" />
<span className="text-lg font-bold text-sidebar-foreground">
Showy
</span>
</div>
<Separator className="bg-sidebar-border" />
{/* Nav */}
<nav className="flex-1 space-y-1 overflow-y-auto px-3 py-4">
<p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-sidebar-foreground/50">
Main
</p>
{mainNav.map((item) => (
<NavItem key={item.to} {...item} />
))}
<Separator className="my-3 bg-sidebar-border" />
<p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-sidebar-foreground/50">
Library
</p>
{libraryNav.map((item) => (
<NavItem key={item.to} {...item} />
))}
<Separator className="my-3 bg-sidebar-border" />
<p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-sidebar-foreground/50">
Other
</p>
{otherNav.map((item) => (
<NavItem key={item.to} {...item} />
))}
</nav>
{/* Bottom actions */}
<div className="border-t border-sidebar-border px-3 py-3 space-y-1">
<Button
variant="ghost"
size="sm"
className="w-full justify-start gap-3 text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
onClick={toggleTheme}
>
{theme === 'dark' ? (
<Sun className="h-4 w-4" />
) : (
<Moon className="h-4 w-4" />
)}
<span>{theme === 'dark' ? 'Light Mode' : 'Dark Mode'}</span>
</Button>
<NavItem to="/settings" icon={Settings} label="Settings" />
</div>
</aside>
);
}
@@ -0,0 +1,35 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { collectionsApi } from '@/api/collections';
export const collectionKeys = {
all: ['collections'] as const,
detail: (id: number) => ['collections', id] as const,
};
export function useCollections() {
return useQuery({
queryKey: collectionKeys.all,
queryFn: collectionsApi.getAll,
});
}
export function useCollection(id: number) {
return useQuery({
queryKey: collectionKeys.detail(id),
queryFn: () => collectionsApi.getById(id),
enabled: !!id,
});
}
export function useUpdateCollection() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, data }: { id: number; data: FormData }) =>
collectionsApi.updateWithMedia(id, data),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: collectionKeys.detail(variables.id) });
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
},
});
}
+111
View File
@@ -0,0 +1,111 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { entriesApi } from '@/api/entries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import type { Entry } from '@/types';
export const entryKeys = {
all: ['entries'] as const,
detail: (id: number) => ['entries', id] as const,
seasons: (id: number) => ['entries', id, 'seasons'] as const,
};
export function useLibrary() {
const setEntries = useLibraryStore((s) => s.setEntries);
return useQuery({
queryKey: entryKeys.all,
queryFn: async () => {
const data = await entriesApi.getAll();
setEntries(data);
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useEntry(id: number) {
return useQuery({
queryKey: entryKeys.detail(id),
queryFn: () => entriesApi.getById(id),
enabled: !!id,
});
}
export function useEntrySeasons(id: number) {
return useQuery({
queryKey: entryKeys.seasons(id),
queryFn: () => entriesApi.getSeasons(id),
enabled: !!id,
});
}
export function useCreateEntry() {
const queryClient = useQueryClient();
const addEntry = useLibraryStore((s) => s.addEntry);
return useMutation({
mutationFn: ({
tmdb_id,
is_tvserie,
}: {
tmdb_id: number;
is_tvserie: boolean;
}) => entriesApi.create(tmdb_id, is_tvserie),
onSuccess: (entry) => {
addEntry(entry);
queryClient.invalidateQueries({ queryKey: entryKeys.all });
},
});
}
export function useUpdateEntry() {
const queryClient = useQueryClient();
const updateEntry = useLibraryStore((s) => s.updateEntry);
return useMutation({
mutationFn: ({ id, data }: { id: number; data: Partial<Entry> }) =>
entriesApi.update(id, data),
onSuccess: (entry) => {
updateEntry(entry.id, entry);
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entry.id) });
},
});
}
export function useDeleteEntry() {
const queryClient = useQueryClient();
const removeEntry = useLibraryStore((s) => s.removeEntry);
return useMutation({
mutationFn: (id: number) => entriesApi.delete(id),
onSuccess: (_data, id) => {
removeEntry(id);
queryClient.invalidateQueries({ queryKey: entryKeys.all });
},
});
}
export function useRefreshEntry() {
const queryClient = useQueryClient();
const updateEntry = useLibraryStore((s) => s.updateEntry);
return useMutation({
mutationFn: (id: number) => entriesApi.refresh(id),
onSuccess: (entry) => {
updateEntry(entry.id, entry);
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entry.id) });
},
});
}
export function useUploadMedia() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, formData }: { id: number; formData: FormData }) =>
entriesApi.uploadMedia(id, formData),
onSuccess: (_data, { id }) => {
queryClient.invalidateQueries({ queryKey: entryKeys.detail(id) });
},
});
}
+71
View File
@@ -0,0 +1,71 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { entrySeenApi } from '@/api/entry-seen';
import { entryKeys } from './useEntries';
export const entrySeenKeys = {
all: ['entry-seen'] as const,
byEntry: (entryId: number) => ['entry-seen', 'by-entry', entryId] as const,
};
export function useEntrySeenByEntry(entryId: number) {
return useQuery({
queryKey: entrySeenKeys.byEntry(entryId),
queryFn: () => entrySeenApi.getByEntry(entryId),
enabled: !!entryId,
});
}
export function useCreateEntrySeen() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: {
entry_id: number;
date_seen: string;
seen_with?: string;
}) => entrySeenApi.create(data),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
queryKey: entrySeenKeys.byEntry(variables.entry_id),
});
queryClient.invalidateQueries({
queryKey: entryKeys.detail(variables.entry_id),
});
queryClient.invalidateQueries({ queryKey: entryKeys.all });
},
});
}
export function useUpdateEntrySeen() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
id,
data,
}: {
id: number;
data: { entry_id: number; date_seen?: string; seen_with?: string };
}) => entrySeenApi.update(id, data),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
queryKey: entrySeenKeys.byEntry(variables.data.entry_id),
});
},
});
}
export function useDeleteEntrySeen() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, entryId }: { id: number; entryId: number }) =>
entrySeenApi.delete(id),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
queryKey: entrySeenKeys.byEntry(variables.entryId),
});
queryClient.invalidateQueries({ queryKey: entryKeys.all });
},
});
}
@@ -0,0 +1,65 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { episodeSeenApi } from '@/api/episode-seen';
import { entryKeys } from './useEntries';
export const episodeSeenKeys = {
all: ['episode-seen'] as const,
byEpisode: (episodeId: number) =>
['episode-seen', 'by-episode', episodeId] as const,
};
export function useEpisodeSeenByEpisode(episodeId: number) {
return useQuery({
queryKey: episodeSeenKeys.byEpisode(episodeId),
queryFn: () => episodeSeenApi.getByEpisode(episodeId),
enabled: !!episodeId,
});
}
export function useCreateEpisodeSeen() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: {
entry_id: number;
episode_id: number;
date_seen: string;
seen_with?: string;
}) => episodeSeenApi.create(data),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
queryKey: episodeSeenKeys.byEpisode(variables.episode_id),
});
queryClient.invalidateQueries({
queryKey: entryKeys.detail(variables.entry_id),
});
queryClient.invalidateQueries({
queryKey: entryKeys.seasons(variables.entry_id),
});
},
});
}
export function useDeleteEpisodeSeen() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
id,
entryId,
episodeId,
}: {
id: number;
entryId: number;
episodeId: number;
}) => episodeSeenApi.delete(id),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
queryKey: episodeSeenKeys.byEpisode(variables.episodeId),
});
queryClient.invalidateQueries({
queryKey: entryKeys.detail(variables.entryId),
});
},
});
}
+15
View File
@@ -0,0 +1,15 @@
import { useQuery } from '@tanstack/react-query';
import { episodesApi } from '@/api/episodes';
export const episodeKeys = {
byMonth: (start: string, end: string) =>
['episodes', 'month', start, end] as const,
};
export function useEpisodesByMonth(startDate: string, endDate: string) {
return useQuery({
queryKey: episodeKeys.byMonth(startDate, endDate),
queryFn: () => episodesApi.getByMonth(startDate, endDate),
enabled: !!startDate && !!endDate,
});
}
+15
View File
@@ -0,0 +1,15 @@
import { useQuery } from '@tanstack/react-query';
import { peopleApi } from '@/api/people';
export const peopleKeys = {
all: ['people'] as const,
detail: (id: number) => ['people', id] as const,
};
export function usePerson(id: number) {
return useQuery({
queryKey: peopleKeys.detail(id),
queryFn: () => peopleApi.getById(id),
enabled: !!id,
});
}
+24
View File
@@ -0,0 +1,24 @@
import { useQuery } from '@tanstack/react-query';
import { seasonsApi } from '@/api/seasons';
export const seasonKeys = {
all: ['seasons'] as const,
detail: (id: number) => ['seasons', id] as const,
episodes: (id: number) => ['seasons', id, 'episodes'] as const,
};
export function useSeason(id: number) {
return useQuery({
queryKey: seasonKeys.detail(id),
queryFn: () => seasonsApi.getById(id),
enabled: !!id,
});
}
export function useSeasonEpisodes(id: number) {
return useQuery({
queryKey: seasonKeys.episodes(id),
queryFn: () => seasonsApi.getEpisodes(id),
enabled: !!id,
});
}
@@ -0,0 +1,9 @@
import { useQuery } from '@tanstack/react-query';
import { statisticsApi } from '@/api/statistics';
export function useStatistics() {
return useQuery({
queryKey: ['statistics'],
queryFn: statisticsApi.get,
});
}
+74
View File
@@ -0,0 +1,74 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { tmdbApi } from '@/api/tmdb';
export function usePopularMovies() {
return useInfiniteQuery({
queryKey: ['tmdb', 'popular', 'movie'],
queryFn: ({ pageParam }) => tmdbApi.getPopularMovies(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
});
}
export function usePopularTv() {
return useInfiniteQuery({
queryKey: ['tmdb', 'popular', 'tv'],
queryFn: ({ pageParam }) => tmdbApi.getPopularTv(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
});
}
export function useTrendingMovies() {
return useInfiniteQuery({
queryKey: ['tmdb', 'trending', 'movie'],
queryFn: ({ pageParam }) => tmdbApi.getTrendingMovies(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
});
}
export function useTrendingTv() {
return useInfiniteQuery({
queryKey: ['tmdb', 'trending', 'tv'],
queryFn: ({ pageParam }) => tmdbApi.getTrendingTv(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
});
}
export function useTmdbSearch(query: string) {
return useInfiniteQuery({
queryKey: ['tmdb', 'search', query],
queryFn: ({ pageParam }) => tmdbApi.search(query, pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
enabled: query.length > 0,
});
}
export function usePopularPeople() {
return useInfiniteQuery({
queryKey: ['tmdb', 'popular', 'people'],
queryFn: ({ pageParam }) => tmdbApi.getPopularPeople(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
});
}
export function useTmdbSearchPeople(query: string) {
return useInfiniteQuery({
queryKey: ['tmdb', 'search', 'people', query],
queryFn: ({ pageParam }) => tmdbApi.searchPeople(query, pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined,
enabled: query.length > 0,
});
}
+60 -60
View File
@@ -51,38 +51,38 @@
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--background: oklch(0.15 0.01 260);
--foreground: oklch(0.95 0.01 260);
--card: oklch(0.18 0.01 260);
--card-foreground: oklch(0.95 0.01 260);
--popover: oklch(0.18 0.01 260);
--popover-foreground: oklch(0.95 0.01 260);
--primary: oklch(0.65 0.18 250);
--primary-foreground: oklch(0.98 0.005 260);
--secondary: oklch(0.25 0.015 260);
--secondary-foreground: oklch(0.9 0.01 260);
--muted: oklch(0.22 0.01 260);
--muted-foreground: oklch(0.65 0.015 260);
--accent: oklch(0.25 0.02 260);
--accent-foreground: oklch(0.95 0.01 260);
--destructive: oklch(0.577 0.245 27.325);
--destructive-foreground: oklch(0.98 0.005 260);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
--border: oklch(0.28 0.015 260);
--input: oklch(0.28 0.015 260);
--ring: oklch(0.65 0.18 250);
--chart-1: oklch(0.65 0.18 250);
--chart-2: oklch(0.6 0.15 160);
--chart-3: oklch(0.7 0.15 60);
--chart-4: oklch(0.6 0.2 300);
--chart-5: oklch(0.65 0.2 30);
--sidebar: oklch(0.12 0.01 260);
--sidebar-foreground: oklch(0.95 0.01 260);
--sidebar-primary: oklch(0.65 0.18 250);
--sidebar-primary-foreground: oklch(0.98 0.005 260);
--sidebar-accent: oklch(0.2 0.02 260);
--sidebar-accent-foreground: oklch(0.95 0.01 260);
--sidebar-border: oklch(0.25 0.015 260);
--sidebar-ring: oklch(0.65 0.18 250);
}
.light {
@@ -134,35 +134,35 @@
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--background: oklch(0.15 0.01 260);
--foreground: oklch(0.95 0.01 260);
--card: oklch(0.18 0.01 260);
--card-foreground: oklch(0.95 0.01 260);
--popover: oklch(0.18 0.01 260);
--popover-foreground: oklch(0.95 0.01 260);
--primary: oklch(0.65 0.18 250);
--primary-foreground: oklch(0.98 0.005 260);
--secondary: oklch(0.25 0.015 260);
--secondary-foreground: oklch(0.9 0.01 260);
--muted: oklch(0.22 0.01 260);
--muted-foreground: oklch(0.65 0.015 260);
--accent: oklch(0.25 0.02 260);
--accent-foreground: oklch(0.95 0.01 260);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
--border: oklch(0.28 0.015 260);
--input: oklch(0.28 0.015 260);
--ring: oklch(0.65 0.18 250);
--chart-1: oklch(0.65 0.18 250);
--chart-2: oklch(0.6 0.15 160);
--chart-3: oklch(0.7 0.15 60);
--chart-4: oklch(0.6 0.2 300);
--chart-5: oklch(0.65 0.2 30);
--sidebar: oklch(0.12 0.01 260);
--sidebar-foreground: oklch(0.95 0.01 260);
--sidebar-primary: oklch(0.65 0.18 250);
--sidebar-primary-foreground: oklch(0.98 0.005 260);
--sidebar-accent: oklch(0.2 0.02 260);
--sidebar-accent-foreground: oklch(0.95 0.01 260);
--sidebar-border: oklch(0.25 0.015 260);
--sidebar-ring: oklch(0.65 0.18 250);
}
+21
View File
@@ -0,0 +1,21 @@
import axios from 'axios';
// const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:4000/api/v1';
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api/v1';
export const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
export const getMediaUrl = (
category: string,
type: string,
size: 'preview' | 'full',
file: string
) => `${API_BASE_URL}/media/${category}/${type}/${size}/${file}`;
export const getTmdbImageUrl = (path: string, size = 'w342') =>
`https://image.tmdb.org/t/p/${size}${path}`;
+103
View File
@@ -0,0 +1,103 @@
import { getMediaUrl, getTmdbImageUrl } from '@/lib/api';
import type { Entry, Collection, Media } from '@/types';
const DEFAULT_POSTER = '/images/default-poster.png';
export function getPosterUrl(entry: Entry): string {
// Not in library, use TMDB poster
if (!entry.isInLibrary) {
return entry.poster_path
? getTmdbImageUrl(entry.poster_path, 'w342')
: DEFAULT_POSTER;
}
// In library: try local selected poster
if (entry.medias) {
const selectedPoster = entry.medias.find(
(m: Media) => m.type === 'poster' && m.is_selected
);
if (selectedPoster?.path) {
return getMediaUrl('entries', 'posters', 'preview', selectedPoster.path);
}
}
// Fallback to TMDB poster
if (entry.poster_path) {
return getTmdbImageUrl(entry.poster_path, 'w300');
}
return DEFAULT_POSTER;
}
export function getBackdropUrl(entry: Entry): string {
if (entry.medias) {
const selectedBackdrop = entry.medias.find(
(m: Media) => m.type === 'backdrop' && m.is_selected
);
if (selectedBackdrop?.path) {
return getMediaUrl(
'entries',
'backdrops',
'full',
selectedBackdrop.path
);
}
}
if (entry.banner_path) {
return getTmdbImageUrl(entry.banner_path, 'w1280');
}
return '';
}
export function getTmdbPosterUrl(
posterPath: string | null,
size = 'w342'
): string {
if (!posterPath) return DEFAULT_POSTER;
return getTmdbImageUrl(posterPath, size);
}
export function getCollectionPosterUrl(collection: Collection): string {
if (collection.medias) {
const selectedPoster = collection.medias.find(
(m: Media) => m.type === 'poster' && m.is_selected
);
if (selectedPoster?.path) {
return getMediaUrl('collections', 'posters', 'preview', selectedPoster.path);
}
}
if (collection.poster_path) {
return getTmdbImageUrl(collection.poster_path, 'w342');
}
return DEFAULT_POSTER;
}
export function getProfileUrl(profilePath: string | null): string {
if (!profilePath) return '/images/default-profile.png';
return getTmdbImageUrl(profilePath, 'w185');
}
export function formatRuntime(minutes: number | null): string {
if (!minutes) return '';
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return h > 0 ? `${h}h ${m}m` : `${m}m`;
}
export function formatDate(dateStr: string | null): string {
if (!dateStr) return '';
return new Date(dateStr).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
}
export function getYear(dateStr: string | null): string {
if (!dateStr) return '';
return new Date(dateStr).getFullYear().toString();
}
+104
View File
@@ -0,0 +1,104 @@
/**
* Normalizers to transform backend Sequelize JSON responses
* into the shape our frontend TypeScript types expect.
*
* Backend quirks:
* - Entry relations use singular aliases: entryId, entryRating, entrySeen
* - Media model uses camelCase: isSelected, isLocal, isCustom, isFavorit, mediaableId
* - Collection model uses camelCase: isUserCollection, userRating, posterPath, backdropPath, isLocal, tmdbId
* - Credit → People alias is "person" (singular)
* - Genres come as string arrays from the backend mapper
*/
import type { Entry, Collection, Media, Credit, Genre } from '@/types';
/* ---------- Media ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeMedia(raw: any): Media {
return {
id: raw.id,
mediaable: raw.mediaable,
mediaable_id: raw.mediaableId ?? raw.mediaable_id,
type: raw.type,
path: raw.path,
is_local: raw.isLocal ?? raw.is_local ?? false,
is_selected: raw.isSelected ?? raw.is_selected ?? false,
is_custom: raw.isCustom ?? raw.is_custom ?? false,
is_favorit: raw.isFavorit ?? raw.is_favorit ?? false,
};
}
/* ---------- Credit ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeCredit(raw: any): Credit {
const people = raw.person ?? raw.people ?? undefined;
return {
id: raw.id,
entry_id: raw.entry_id,
people_id: raw.people_id,
character: raw.character,
cast_type: raw.cast_type,
department: raw.department,
job: raw.job,
order: raw.order,
people: people,
};
}
/* ---------- Genre ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeGenres(raw: any[]): Genre[] {
if (!Array.isArray(raw)) return [];
return raw.map((g, i) => {
if (typeof g === 'string') return { id: i, name: g };
return g as Genre;
});
}
/* ---------- Entry ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeEntry(raw: any): Entry {
return {
...raw,
// Singular → plural aliases (coerce tmdb_id to number for store comparisons)
entryIds: (() => {
const ids = raw.entryIds ?? raw.entryId;
if (!ids) return undefined;
return {
...ids,
tmdb_id: ids.tmdb_id != null ? Number(ids.tmdb_id) : null,
};
})(),
entryRatings: raw.entryRatings ?? raw.entryRating ?? undefined,
entrySeens: raw.entrySeens ?? raw.entrySeen ?? undefined,
// Normalize nested arrays
medias: raw.medias ? raw.medias.map(normalizeMedia) : undefined,
genres: raw.genres ? normalizeGenres(raw.genres) : undefined,
credits: raw.credits ? raw.credits.map(normalizeCredit) : undefined,
collections: raw.collections
? raw.collections.map(normalizeCollection)
: undefined,
// Mark as in library when loaded from the library endpoint
isInLibrary: raw.isInLibrary ?? true,
};
}
/* ---------- Collection ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeCollection(raw: any): Collection {
return {
id: raw.id,
tmdb_id: raw.tmdbId ?? raw.tmdb_id ?? null,
name: raw.name,
description: raw.description ?? raw.overview ?? null,
user_rating: raw.userRating ?? raw.user_rating ?? null,
poster_path: raw.posterPath ?? raw.poster_path ?? null,
backdrop_path: raw.backdropPath ?? raw.backdrop_path ?? null,
is_local: raw.isLocal ?? raw.is_local ?? false,
is_user_collection: raw.isUserCollection ?? raw.is_user_collection ?? false,
createdAt: raw.createdAt,
updatedAt: raw.updatedAt,
entries: raw.entries ? raw.entries.map(normalizeEntry) : undefined,
medias: raw.medias ? raw.medias.map(normalizeMedia) : undefined,
};
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+139
View File
@@ -0,0 +1,139 @@
import { useState, useMemo } from 'react';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, getDay, addMonths, subMonths, isSameDay } from 'date-fns';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useEpisodesByMonth } from '@/hooks/useEpisodes';
import { getTmdbPosterUrl } from '@/lib/media-utils';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
export function CalendarPage() {
const [currentDate, setCurrentDate] = useState(new Date());
const monthStart = startOfMonth(currentDate);
const monthEnd = endOfMonth(currentDate);
const startDateStr = format(monthStart, 'yyyy-MM-dd');
const endDateStr = format(monthEnd, 'yyyy-MM-dd');
const { data: episodes = [] } = useEpisodesByMonth(startDateStr, endDateStr);
const days = useMemo(() => eachDayOfInterval({ start: monthStart, end: monthEnd }), [monthStart, monthEnd]);
const startDayOfWeek = getDay(monthStart);
// Group episodes by date
const episodesByDate = useMemo(() => {
const map = new Map<string, typeof episodes>();
episodes.forEach((ep) => {
if (!ep.air_date) return;
const key = format(new Date(ep.air_date), 'yyyy-MM-dd');
const existing = map.get(key) || [];
existing.push(ep);
map.set(key, existing);
});
return map;
}, [episodes]);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Calendar</h1>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={() => setCurrentDate(subMonths(currentDate, 1))}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="min-w-[140px] text-center font-medium">
{format(currentDate, 'MMMM yyyy')}
</span>
<Button
variant="outline"
size="icon"
onClick={() => setCurrentDate(addMonths(currentDate, 1))}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
{/* Calendar Grid */}
<div className="rounded-lg border border-border overflow-hidden">
{/* Day headers */}
<div className="grid grid-cols-7 bg-muted/50">
{DAYS.map((day) => (
<div key={day} className="px-2 py-2 text-center text-xs font-medium text-muted-foreground">
{day}
</div>
))}
</div>
{/* Day cells */}
<div className="grid grid-cols-7">
{/* Empty cells for offset */}
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} className="min-h-24 border-t border-r border-border bg-muted/20" />
))}
{days.map((day) => {
const key = format(day, 'yyyy-MM-dd');
const dayEpisodes = episodesByDate.get(key) || [];
const isToday = isSameDay(day, new Date());
return (
<div
key={key}
className={`min-h-24 border-t border-r border-border p-1 ${
isToday ? 'bg-primary/5' : ''
}`}
>
<span
className={`inline-flex h-6 w-6 items-center justify-center rounded-full text-xs ${
isToday
? 'bg-primary text-primary-foreground font-bold'
: 'text-muted-foreground'
}`}
>
{format(day, 'd')}
</span>
<div className="mt-1 space-y-0.5">
{dayEpisodes.slice(0, 3).map((ep) => (
<Tooltip key={ep.id}>
<TooltipTrigger asChild>
<div className="flex items-center gap-1 rounded bg-accent/50 px-1 py-0.5">
{ep.still_path && (
<img
src={getTmdbPosterUrl(ep.still_path, 'w92')}
alt=""
className="h-4 w-6 rounded object-cover"
/>
)}
<span className="text-[10px] truncate">
S{ep.season_id} E{ep.episode_number}
</span>
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs font-medium">{ep.name}</p>
<p className="text-xs text-muted-foreground">
Episode {ep.episode_number}
</p>
</TooltipContent>
</Tooltip>
))}
{dayEpisodes.length > 3 && (
<span className="text-[10px] text-muted-foreground pl-1">
+{dayEpisodes.length - 3} more
</span>
)}
</div>
</div>
);
})}
</div>
</div>
</div>
);
}
@@ -0,0 +1,118 @@
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useCollection } from '@/hooks/useCollections';
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
import { getCollectionPosterUrl } from '@/lib/media-utils';
import { getTmdbImageUrl } from '@/lib/api';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Star, Pencil } from 'lucide-react';
import { CollectionEditDialog } from '@/components/dialogs/CollectionEditDialog';
export function CollectionDetailsPage() {
const { id } = useParams<{ id: string }>();
const { data: collection, isLoading } = useCollection(Number(id));
const [showEditDialog, setShowEditDialog] = useState(false);
if (isLoading) {
return (
<div className="space-y-6">
<Skeleton className="h-48 w-full rounded-xl" />
<Skeleton className="h-8 w-64" />
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-[2/3] w-full rounded-lg" />
))}
</div>
</div>
);
}
if (!collection) {
return (
<div className="flex h-40 items-center justify-center text-muted-foreground">
Collection not found.
</div>
);
}
const backdropUrl = collection.backdrop_path
? getTmdbImageUrl(collection.backdrop_path, 'w1280')
: null;
const entries = (collection.entries || []).map((e) => ({
...e,
isInLibrary: true,
}));
return (
<div className="space-y-6">
{/* Hero banner */}
<div className="relative overflow-hidden rounded-xl">
{backdropUrl ? (
<img
src={backdropUrl}
alt={collection.name}
className="h-48 w-full object-cover sm:h-64"
/>
) : (
<div className="h-48 w-full bg-muted sm:h-64" />
)}
<div className="absolute inset-0 bg-gradient-to-t from-background via-background/60 to-transparent" />
<div className="absolute bottom-0 left-0 right-0 flex items-end justify-between p-6">
<div className="flex items-end gap-4">
<img
src={getCollectionPosterUrl(collection)}
alt={collection.name}
className="h-32 w-auto rounded-lg shadow-lg sm:h-40"
/>
<div className="space-y-1">
<h1 className="text-2xl font-bold text-white sm:text-3xl">
{collection.name}
</h1>
{collection.description && (
<p className="max-w-xl text-sm text-white/80 line-clamp-3">
{collection.description}
</p>
)}
<div className="flex items-center gap-3">
<p className="text-sm text-white/60">
{entries.length} {entries.length === 1 ? 'entry' : 'entries'}
</p>
{collection.user_rating != null && collection.user_rating > 0 && (
<div className="flex items-center gap-1">
<Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
<span className="text-sm font-medium text-white">
{collection.user_rating}/10
</span>
</div>
)}
</div>
</div>
</div>
<Button
variant="secondary"
size="sm"
className="shrink-0"
onClick={() => setShowEditDialog(true)}
>
<Pencil className="mr-1 h-4 w-4" />
Edit
</Button>
</div>
</div>
{/* Entries grid */}
<EntryLibraryGrid entries={entries} isLoading={false} />
{/* Edit dialog */}
{showEditDialog && (
<CollectionEditDialog
open={showEditDialog}
onOpenChange={setShowEditDialog}
collection={collection}
/>
)}
</div>
);
}
@@ -0,0 +1,60 @@
import { useState, useMemo } from 'react';
import { useCollections } from '@/hooks/useCollections';
import { CollectionsGrid } from '@/components/collections/CollectionsGrid';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Search } from 'lucide-react';
export function CollectionsPage() {
const { data: collections = [], isLoading } = useCollections();
const [search, setSearch] = useState('');
const [filter, setFilter] = useState<'all' | 'official' | 'custom'>('all');
const filtered = useMemo(() => {
let result = collections;
if (filter === 'official') {
result = result.filter((c) => !c.is_user_collection);
} else if (filter === 'custom') {
result = result.filter((c) => c.is_user_collection);
}
if (search) {
const q = search.toLowerCase();
result = result.filter((c) => c.name.toLowerCase().includes(q));
}
return result;
}, [collections, filter, search]);
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Collections</h1>
<div className="flex flex-wrap items-center gap-3">
<Tabs
value={filter}
onValueChange={(v) => setFilter(v as 'all' | 'official' | 'custom')}
>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="official">Official</TabsTrigger>
<TabsTrigger value="custom">Custom</TabsTrigger>
</TabsList>
</Tabs>
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search collections..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
</div>
<CollectionsGrid collections={filtered} isLoading={isLoading} />
</div>
);
}
+114
View File
@@ -0,0 +1,114 @@
import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { useLibrary } from '@/hooks/useEntries';
import { useStatistics } from '@/hooks/useStatistics';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Film, Tv, Heart, ListVideo, Clock } from 'lucide-react';
import { formatRuntime, getPosterUrl } from '@/lib/media-utils';
export function DashboardPage() {
useLibrary();
const { data: stats, isLoading: statsLoading } = useStatistics();
const allEntries = useLibraryEntries();
const movies = useMemo(() => allEntries.filter((e) => !e.is_tvseries && !e.watchlist), [allEntries]);
const tvSeries = useMemo(() => allEntries.filter((e) => e.is_tvseries && !e.watchlist), [allEntries]);
const favorites = useMemo(() => allEntries.filter((e) => e.favorit && !e.watchlist), [allEntries]);
const watchlist = useMemo(() => allEntries.filter((e) => e.watchlist), [allEntries]);
const statCards = [
{
title: 'Movies',
value: movies.length,
icon: Film,
color: 'text-blue-500',
},
{
title: 'TV Series',
value: tvSeries.length,
icon: Tv,
color: 'text-green-500',
},
{
title: 'Favorites',
value: favorites.length,
icon: Heart,
color: 'text-red-500',
},
{
title: 'Watchlist',
value: watchlist.length,
icon: ListVideo,
color: 'text-purple-500',
},
{
title: 'Watch Time',
value: stats?.totalWatchTime
? formatRuntime(stats.totalWatchTime)
: '0h',
icon: Clock,
color: 'text-orange-500',
},
];
return (
<div className="space-y-8">
<h1 className="text-2xl font-bold">Dashboard</h1>
{/* Stats Grid */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
{statCards.map((stat) => (
<Card key={stat.title}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{stat.title}
</CardTitle>
<stat.icon className={`h-5 w-5 ${stat.color}`} />
</CardHeader>
<CardContent>
{statsLoading ? (
<Skeleton className="h-8 w-16" />
) : (
<p className="text-2xl font-bold">{stat.value}</p>
)}
</CardContent>
</Card>
))}
</div>
{/* Recently Watched */}
<div className="space-y-4">
<h2 className="text-lg font-semibold">Recently Watched</h2>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{allEntries
.filter((e) => e.date_last_seen)
.sort(
(a, b) =>
new Date(b.date_last_seen!).getTime() -
new Date(a.date_last_seen!).getTime()
)
.slice(0, 14)
.map((entry) => (
<Link
key={entry.id}
to={`/entry/${entry.id}`}
className="group transition-transform hover:scale-[1.02]"
>
<img
src={getPosterUrl(entry)}
alt={entry.title}
className="aspect-[2/3] w-full rounded-lg object-cover"
loading="lazy"
/>
<p className="mt-1 text-xs font-medium truncate">
{entry.title}
</p>
</Link>
))}
</div>
</div>
</div>
);
}
@@ -0,0 +1,354 @@
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useEntry, useEntrySeasons, useRefreshEntry } from '@/hooks/useEntries';
import { useEntrySeenByEntry, useDeleteEntrySeen } from '@/hooks/useEntrySeen';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Heart,
MoreHorizontal,
Eye,
EyeOff,
RefreshCw,
FolderPlus,
ImageIcon,
Settings,
Star,
} from 'lucide-react';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
import { CastList } from '@/components/entries/CastList';
import { SeasonsContainer } from '@/components/entries/SeasonsContainer';
import { EpisodeWatchHistory } from '@/components/entries/EpisodeWatchHistory';
import { CollectionsGrid } from '@/components/collections/CollectionsGrid';
import { EntrySettingsDialog } from '@/components/dialogs/EntrySettingsDialog';
import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog';
import { EntryMediaDialog } from '@/components/dialogs/EntryMediaDialog';
import { AddEntryToCollectionDialog } from '@/components/dialogs/AddEntryToCollectionDialog';
import {
getPosterUrl,
getBackdropUrl,
getYear,
formatRuntime,
formatDate,
} from '@/lib/media-utils';
import { useUpdateEntry } from '@/hooks/useEntries';
import type { Entry } from '@/types';
export function EntryDetailsPage() {
const { id } = useParams<{ id: string }>();
const entryId = parseInt(id!, 10);
const { data: entry, isLoading } = useEntry(entryId);
const { data: seasons } = useEntrySeasons(entryId);
const { data: watchHistory = [] } = useEntrySeenByEntry(entryId);
const updateEntry = useUpdateEntry();
const refreshEntry = useRefreshEntry();
const deleteEntrySeen = useDeleteEntrySeen();
// Merge library entry with detail entry so we get both library flags AND full details (credits, etc.)
const libraryEntry = useLibraryStore((s) => s.entries.get(entryId));
const displayEntry = libraryEntry && entry
? { ...libraryEntry, ...entry, isInLibrary: true }
: entry || libraryEntry;
// Dialog states
const [showSettings, setShowSettings] = useState(false);
const [showSeenDialog, setShowSeenDialog] = useState(false);
const [showMediaDialog, setShowMediaDialog] = useState(false);
const [showCollectionDialog, setShowCollectionDialog] = useState(false);
if (isLoading || !displayEntry) {
return <EntryDetailsSkeleton />;
}
const e = displayEntry;
const backdrop = getBackdropUrl(e);
const poster = getPosterUrl(e);
const director = e.credits?.find(
(c) => c.cast_type === 'crew' && c.job === 'Director'
);
const toggleFavorite = () => {
updateEntry.mutate({ id: e.id, data: { favorit: !e.favorit } });
};
return (
<div className="space-y-8">
{/* Hero Section */}
<div className="relative -mx-6 -mt-6 overflow-hidden">
{backdrop && (
<img
src={backdrop}
alt=""
className="h-72 w-full object-cover opacity-30 blur-sm"
/>
)}
<div className="absolute inset-0 bg-gradient-to-t from-background to-transparent" />
<div className="relative mx-auto flex max-w-5xl gap-6 px-6 pb-6 pt-4">
{/* Poster */}
<div className="shrink-0">
<img
src={poster}
alt={e.title}
className="h-72 w-48 rounded-lg object-cover shadow-lg"
/>
</div>
{/* Info */}
<div className="flex flex-1 flex-col justify-end space-y-3">
<div className="flex items-center gap-3">
<h1 className="text-3xl font-bold">{e.title}</h1>
{e.status && (
<Badge variant="secondary">{e.status}</Badge>
)}
</div>
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
{e.release_date && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-default underline decoration-dotted">
{getYear(e.release_date)}
</span>
</TooltipTrigger>
<TooltipContent>
<p>{formatDate(e.release_date)}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{e.runtime && !e.is_tvseries && (
<>
<span>•</span>
<span>{formatRuntime(e.runtime)}</span>
</>
)}
{director && (
<>
<span>•</span>
<span>Dir. {director.people?.name}</span>
</>
)}
</div>
{/* Genres */}
{e.genres && e.genres.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{e.genres.map((g) => (
<Badge key={g.id} variant="outline" className="text-xs">
{g.name}
</Badge>
))}
</div>
)}
{/* Ratings */}
<div className="flex items-center gap-4">
{e.entryRatings?.user_rating != null &&
e.entryRatings.user_rating > 0 && (
<div className="flex items-center gap-1">
<Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
<span className="text-sm font-medium">
{e.entryRatings.user_rating}/10
</span>
<span className="text-xs text-muted-foreground">You</span>
</div>
)}
{e.entryRatings?.tmdb_rating != null &&
e.entryRatings.tmdb_rating > 0 && (
<div className="flex items-center gap-1">
<span className="text-sm font-medium">
{e.entryRatings.tmdb_rating.toFixed(1)}
</span>
<span className="text-xs text-muted-foreground">TMDB</span>
</div>
)}
{e.entryRatings?.imdb_rating != null &&
e.entryRatings.imdb_rating > 0 && (
<div className="flex items-center gap-1">
<span className="text-sm font-medium">
{e.entryRatings.imdb_rating}
</span>
<span className="text-xs text-muted-foreground">IMDb</span>
</div>
)}
</div>
{/* Actions */}
<div className="flex items-center gap-2 pt-2">
<Button
variant={e.favorit ? 'default' : 'outline'}
size="sm"
onClick={toggleFavorite}
>
<Heart
className={`mr-1 h-4 w-4 ${
e.favorit ? 'fill-current' : ''
}`}
/>
{e.favorit ? 'Favorited' : 'Favorite'}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setShowSeenDialog(true)}
>
<Eye className="mr-1 h-4 w-4" />
Mark Watched
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon" className="h-8 w-8">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() =>
updateEntry.mutate({
id: e.id,
data: { hidden: !e.hidden },
})
}
>
<EyeOff className="mr-2 h-4 w-4" />
{e.hidden ? 'Unhide' : 'Hide'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => refreshEntry.mutate(e.id)}
>
<RefreshCw className="mr-2 h-4 w-4" />
Refresh Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setShowCollectionDialog(true)}
>
<FolderPlus className="mr-2 h-4 w-4" />
Add to Collection
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setShowMediaDialog(true)}
>
<ImageIcon className="mr-2 h-4 w-4" />
Media
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setShowSettings(true)}
>
<Settings className="mr-2 h-4 w-4" />
Settings
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</div>
{/* Storyline */}
{e.storyline && (
<div className="space-y-2">
<h3 className="text-lg font-semibold">Overview</h3>
<p className="text-sm text-muted-foreground leading-relaxed">
{e.storyline}
</p>
</div>
)}
<Separator />
{/* Cast */}
{e.credits && e.credits.length > 0 && <CastList credits={e.credits} />}
{/* Seasons (TV only) */}
{e.is_tvseries && seasons && seasons.length > 0 && (
<>
<Separator />
<SeasonsContainer seasons={seasons} entryId={e.id} />
</>
)}
{/* Watch History */}
{watchHistory.length > 0 && (
<>
<Separator />
<EpisodeWatchHistory
watchHistory={watchHistory}
onDelete={(seenId) =>
deleteEntrySeen.mutate({ id: seenId, entryId: e.id })
}
/>
</>
)}
{/* Dialogs */}
{showSettings && (
<EntrySettingsDialog
open={showSettings}
onOpenChange={setShowSettings}
entry={e}
/>
)}
{showSeenDialog && (
<EntrySeenDialog
open={showSeenDialog}
onOpenChange={setShowSeenDialog}
entry={e}
seasons={seasons}
mode="add"
/>
)}
{showMediaDialog && (
<EntryMediaDialog
open={showMediaDialog}
onOpenChange={setShowMediaDialog}
entryId={e.id}
medias={e.medias || []}
/>
)}
{showCollectionDialog && (
<AddEntryToCollectionDialog
open={showCollectionDialog}
onOpenChange={setShowCollectionDialog}
entryId={e.id}
/>
)}
</div>
);
}
function EntryDetailsSkeleton() {
return (
<div className="space-y-8">
<div className="flex gap-6">
<Skeleton className="h-72 w-48 shrink-0 rounded-lg" />
<div className="flex-1 space-y-4">
<Skeleton className="h-8 w-64" />
<Skeleton className="h-4 w-40" />
<Skeleton className="h-4 w-80" />
<div className="flex gap-2">
<Skeleton className="h-8 w-24" />
<Skeleton className="h-8 w-32" />
</div>
</div>
</div>
</div>
);
}
+146
View File
@@ -0,0 +1,146 @@
import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { seasonsApi } from '@/api/seasons';
import { useEpisodeSeenByEpisode, useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { EpisodeWatchHistory } from '@/components/entries/EpisodeWatchHistory';
import { CastList } from '@/components/entries/CastList';
import { Eye, ChevronLeft, ChevronRight, Clock } from 'lucide-react';
import { getTmdbPosterUrl, formatDate, formatRuntime } from '@/lib/media-utils';
import type { Episode } from '@/types';
export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{
entryId: string;
seasonId: string;
episodeId: string;
}>();
const { data: episodes = [] } = useQuery({
queryKey: ['seasons', parseInt(seasonId!, 10), 'episodes'],
queryFn: () => seasonsApi.getEpisodes(parseInt(seasonId!, 10)),
});
const epId = parseInt(episodeId!, 10);
const episode: Episode | undefined = episodes.find((ep: Episode) => ep.id === epId);
const { data: watchHistory = [] } = useEpisodeSeenByEpisode(epId);
const createEpisodeSeen = useCreateEpisodeSeen();
// Find prev/next episode
const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId);
const prevEpisode: Episode | undefined = currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const nextEpisode: Episode | undefined =
currentIndex < episodes.length - 1 ? episodes[currentIndex + 1] : undefined;
if (!episode) {
return (
<div className="space-y-6">
<Skeleton className="h-48 w-full rounded-lg" />
<Skeleton className="h-6 w-48" />
<Skeleton className="h-4 w-80" />
</div>
);
}
const handleMarkWatched = () => {
createEpisodeSeen.mutate({
entry_id: parseInt(entryId!, 10),
episode_id: episode.id,
date_seen: new Date().toISOString().split('T')[0],
});
};
return (
<div className="space-y-8">
{/* Thumbnail */}
{episode.still_path && (
<div className="overflow-hidden rounded-lg">
<img
src={getTmdbPosterUrl(episode.still_path, 'w780')}
alt={episode.name}
className="w-full max-h-80 object-cover"
/>
</div>
)}
{/* Info */}
<div className="space-y-3">
<div className="flex items-center gap-3">
<span className="text-sm text-muted-foreground">
Episode {episode.episode_number}
</span>
<h1 className="text-2xl font-bold">{episode.name}</h1>
</div>
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{episode.air_date && <span>{formatDate(episode.air_date)}</span>}
{episode.runtime && (
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{formatRuntime(episode.runtime)}
</span>
)}
</div>
{episode.overview && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl">
{episode.overview}
</p>
)}
<Button size="sm" onClick={handleMarkWatched}>
<Eye className="mr-1 h-4 w-4" />
Mark as Watched
</Button>
</div>
{/* Guest Stars */}
{episode.guest_stars && episode.guest_stars.length > 0 && (
<>
<Separator />
<CastList credits={episode.guest_stars} />
</>
)}
{/* Watch History */}
{watchHistory.length > 0 && (
<>
<Separator />
<EpisodeWatchHistory watchHistory={watchHistory} />
</>
)}
{/* Navigation */}
<Separator />
<div className="flex justify-between">
{prevEpisode ? (
<Button variant="outline" asChild>
<Link
to={`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`}
>
<ChevronLeft className="mr-1 h-4 w-4" />
E{prevEpisode.episode_number}: {prevEpisode.name}
</Link>
</Button>
) : (
<div />
)}
{nextEpisode ? (
<Button variant="outline" asChild>
<Link
to={`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`}
>
E{nextEpisode.episode_number}: {nextEpisode.name}
<ChevronRight className="ml-1 h-4 w-4" />
</Link>
</Button>
) : (
<div />
)}
</div>
</div>
);
}
+78
View File
@@ -0,0 +1,78 @@
import { useTrendingMovies, useTrendingTv, usePopularMovies, usePopularTv, useTmdbSearch } from '@/hooks/useTmdb';
import { useLibrary } from '@/hooks/useEntries';
import { TrendingGrid } from '@/components/entries/TrendingGrid';
import { Input } from '@/components/ui/input';
import { useState } from 'react';
import { Search } from 'lucide-react';
import { EntryCard } from '@/components/entries/EntryCard';
export function HomePage() {
const [searchQuery, setSearchQuery] = useState('');
// Pre-load library
useLibrary();
const trendingMovies = useTrendingMovies();
const trendingTv = useTrendingTv();
const popularMovies = usePopularMovies();
const popularTv = usePopularTv();
const searchResults = useTmdbSearch(searchQuery);
const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
const popularMovieEntries = popularMovies.data?.pages.flatMap((p) => p.results) ?? [];
const popularTvEntries = popularTv.data?.pages.flatMap((p) => p.results) ?? [];
const searchEntries = searchResults.data?.pages.flatMap((p) => p.results) ?? [];
const isSearching = searchQuery.length > 0;
return (
<div className="space-y-8">
{/* Search */}
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search movies & TV shows..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
{isSearching ? (
<div className="space-y-4">
<h2 className="text-xl font-semibold">
Search Results for "{searchQuery}"
</h2>
{searchEntries.length === 0 && !searchResults.isLoading ? (
<p className="text-muted-foreground">No results found.</p>
) : (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{searchEntries.map((entry) => (
<EntryCard key={entry.id} tmdbEntry={entry} />
))}
</div>
)}
</div>
) : (
<>
<TrendingGrid
title="Trending"
movieEntries={trendingMovieEntries}
tvEntries={trendingTvEntries}
isLoading={trendingMovies.isLoading || trendingTv.isLoading}
moreLink="/library"
/>
<TrendingGrid
title="Popular"
movieEntries={popularMovieEntries}
tvEntries={popularTvEntries}
isLoading={popularMovies.isLoading || popularTv.isLoading}
moreLink="/library"
/>
</>
)}
</div>
);
}
+279
View File
@@ -0,0 +1,279 @@
import { useState, useMemo, useCallback } from 'react';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Search, X, SlidersHorizontal, ArrowUpDown } from 'lucide-react';
import type { Entry } from '@/types';
type FilterTab = 'all' | 'movies' | 'tv' | 'favorites' | 'hidden';
type SortField = 'date_last_seen' | 'createdAt' | 'title' | 'release_date' | 'rating';
type SortDir = 'asc' | 'desc';
interface Filters {
genre: string;
ratingMin: string;
ratingMax: string;
yearMin: string;
yearMax: string;
}
const defaultFilters: Filters = { genre: '', ratingMin: '', ratingMax: '', yearMin: '', yearMax: '' };
const sortLabels: Record<SortField, string> = {
date_last_seen: 'Last Watched',
createdAt: 'Date Added',
title: 'Title',
release_date: 'Release Date',
rating: 'Rating',
};
function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[] {
return [...entries].sort((a, b) => {
let cmp = 0;
switch (field) {
case 'title':
cmp = a.title.localeCompare(b.title);
break;
case 'release_date':
cmp = new Date(a.release_date || '1900').getTime() - new Date(b.release_date || '1900').getTime();
break;
case 'rating':
cmp = (a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0) -
(b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0);
break;
case 'date_last_seen':
cmp = new Date(a.date_last_seen || '1900').getTime() - new Date(b.date_last_seen || '1900').getTime();
break;
case 'createdAt':
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
break;
}
return dir === 'desc' ? -cmp : cmp;
});
}
export function LibraryPage() {
const { isLoading } = useLibrary();
const [activeTab, setActiveTab] = useState<FilterTab>('all');
const [search, setSearch] = useState('');
const [sortField, setSortField] = useState<SortField>('date_last_seen');
const [sortDir, setSortDir] = useState<SortDir>('desc');
const [filters, setFilters] = useState<Filters>(defaultFilters);
const allEntries = useLibraryEntries();
// Gather unique genres from the library
const allGenres = useMemo(() => {
const set = new Set<string>();
allEntries.forEach((e) => e.genres?.forEach((g) => set.add(g.name)));
return Array.from(set).sort();
}, [allEntries]);
const hasActiveFilters = filters.genre || filters.ratingMin || filters.ratingMax || filters.yearMin || filters.yearMax;
const baseEntries = useMemo(() => {
switch (activeTab) {
case 'movies':
return allEntries.filter((e) => !e.is_tvseries && !e.watchlist);
case 'tv':
return allEntries.filter((e) => e.is_tvseries && !e.watchlist);
case 'favorites':
return allEntries.filter((e) => e.favorit && !e.watchlist);
case 'hidden':
return allEntries.filter((e) => e.hidden);
default:
return allEntries.filter((e) => !e.watchlist);
}
}, [activeTab, allEntries]);
const filteredEntries = useMemo(() => {
let result = baseEntries;
if (search) {
const q = search.toLowerCase();
result = result.filter((e) => e.title.toLowerCase().includes(q));
}
if (filters.genre) {
result = result.filter((e) => e.genres?.some((g) => g.name === filters.genre));
}
if (filters.ratingMin) {
const min = parseFloat(filters.ratingMin);
result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) >= min);
}
if (filters.ratingMax) {
const max = parseFloat(filters.ratingMax);
result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) <= max);
}
if (filters.yearMin) {
const min = parseInt(filters.yearMin);
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() >= min);
}
if (filters.yearMax) {
const max = parseInt(filters.yearMax);
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() <= max);
}
return sortEntries(result, sortField, sortDir);
}, [baseEntries, search, filters, sortField, sortDir]);
const clearFilters = useCallback(() => setFilters(defaultFilters), []);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Library</h1>
</div>
{/* Controls row: search left, sort + filter + tabs right */}
<div className="flex flex-wrap items-center gap-3">
{/* Search - far left */}
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search library..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
{search && (
<Button variant="ghost" size="sm" onClick={() => setSearch('')}>
<X className="mr-1 h-4 w-4" /> Clear
</Button>
)}
{/* Spacer */}
<div className="flex-1" />
{/* Sort */}
<div className="flex items-center gap-1">
<ArrowUpDown className="h-4 w-4 text-muted-foreground" />
<Select value={sortField} onValueChange={(v) => setSortField(v as SortField)}>
<SelectTrigger className="w-[160px] h-9">
<SelectValue>{sortLabels[sortField]}</SelectValue>
</SelectTrigger>
<SelectContent>
{Object.entries(sortLabels).map(([value, label]) => (
<SelectItem key={value} value={value}>{label}</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="ghost"
size="icon"
className="h-9 w-9"
onClick={() => setSortDir((d) => (d === 'desc' ? 'asc' : 'desc'))}
>
<span className="text-xs font-medium">{sortDir === 'desc' ? '↓' : '↑'}</span>
</Button>
</div>
{/* Filter */}
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="h-9 gap-1">
<SlidersHorizontal className="h-4 w-4" />
Filter
{hasActiveFilters && <Badge variant="secondary" className="ml-1 h-5 px-1 text-[10px]">Active</Badge>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 space-y-4" align="end">
<div className="space-y-2">
<label className="text-sm font-medium">Genre</label>
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : v }))}>
<SelectTrigger className="h-9">
<SelectValue placeholder="All genres" />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all">All genres</SelectItem>
{allGenres.map((g) => (
<SelectItem key={g} value={g}>{g}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Rating Range</label>
<div className="flex items-center gap-2">
<Input
type="number"
placeholder="Min"
min={0}
max={10}
step={0.1}
value={filters.ratingMin}
onChange={(e) => setFilters((f) => ({ ...f, ratingMin: e.target.value }))}
className="h-9"
/>
<span className="text-muted-foreground">–</span>
<Input
type="number"
placeholder="Max"
min={0}
max={10}
step={0.1}
value={filters.ratingMax}
onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))}
className="h-9"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Year Range</label>
<div className="flex items-center gap-2">
<Input
type="number"
placeholder="From"
min={1900}
max={2099}
value={filters.yearMin}
onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))}
className="h-9"
/>
<span className="text-muted-foreground">–</span>
<Input
type="number"
placeholder="To"
min={1900}
max={2099}
value={filters.yearMax}
onChange={(e) => setFilters((f) => ({ ...f, yearMax: e.target.value }))}
className="h-9"
/>
</div>
</div>
{hasActiveFilters && (
<Button variant="ghost" size="sm" className="w-full" onClick={clearFilters}>
Clear Filters
</Button>
)}
</PopoverContent>
</Popover>
{/* Tabs */}
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as FilterTab)}
>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="movies">Movies</TabsTrigger>
<TabsTrigger value="tv">TV Series</TabsTrigger>
<TabsTrigger value="favorites">Favorites</TabsTrigger>
<TabsTrigger value="hidden">Hidden</TabsTrigger>
</TabsList>
</Tabs>
</div>
<EntryLibraryGrid entries={filteredEntries} isLoading={isLoading} />
</div>
);
}
+125
View File
@@ -0,0 +1,125 @@
import { useState, useMemo } from 'react';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { Search } from 'lucide-react';
import { getMediaUrl } from '@/lib/api';
import type { Media } from '@/types';
export function MediaPage() {
const { isLoading } = useLibrary();
const [search, setSearch] = useState('');
const [mediaType, setMediaType] = useState<'all' | 'poster' | 'backdrop' | 'logo'>('all');
const entries = useLibraryEntries();
const allMedias = useMemo(() => {
const medias: (Media & { entryTitle: string })[] = [];
entries.forEach((entry) => {
entry.medias?.forEach((m) => {
medias.push({ ...m, entryTitle: entry.title });
});
});
return medias;
}, [entries]);
const filtered = useMemo(() => {
let result = allMedias;
if (mediaType !== 'all') {
result = result.filter((m) => m.type === mediaType);
}
if (search) {
const q = search.toLowerCase();
result = result.filter((m) => m.entryTitle.toLowerCase().includes(q));
}
return result;
}, [allMedias, mediaType, search]);
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Media</h1>
<div className="flex flex-wrap items-center gap-3">
<Tabs
value={mediaType}
onValueChange={(v) => setMediaType(v as typeof mediaType)}
>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="poster">Posters</TabsTrigger>
<TabsTrigger value="backdrop">Backdrops</TabsTrigger>
<TabsTrigger value="logo">Logos</TabsTrigger>
</TabsList>
</Tabs>
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by title..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
</div>
{isLoading ? (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{Array.from({ length: 18 }).map((_, i) => (
<Skeleton
key={i}
className={
mediaType === 'backdrop'
? 'aspect-video w-full rounded-lg'
: 'aspect-[2/3] w-full rounded-lg'
}
/>
))}
</div>
) : filtered.length === 0 ? (
<div className="flex h-40 items-center justify-center text-muted-foreground">
No media found.
</div>
) : (
<div
className={`grid gap-4 ${
mediaType === 'backdrop'
? 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3'
: 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'
}`}
>
{filtered.map((media) => (
<div
key={media.id}
className="group relative overflow-hidden rounded-lg bg-muted"
>
<img
src={getMediaUrl(
'entries',
`${media.type}s`,
'preview',
media.path
)}
alt={media.entryTitle}
className={`w-full object-cover ${
media.type === 'backdrop' ? 'aspect-video' : 'aspect-[2/3]'
}`}
loading="lazy"
/>
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 transition-opacity group-hover:opacity-100">
<p className="text-xs text-white truncate">
{media.entryTitle}
</p>
</div>
</div>
))}
</div>
)}
</div>
);
}
+95
View File
@@ -0,0 +1,95 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { usePopularPeople, useTmdbSearchPeople } from '@/hooks/useTmdb';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Search } from 'lucide-react';
import { getProfileUrl } from '@/lib/media-utils';
export function PeoplePage() {
const [search, setSearch] = useState('');
const isSearching = search.length > 0;
const popularQuery = usePopularPeople();
const searchQuery = useTmdbSearchPeople(search);
const activeQuery = isSearching ? searchQuery : popularQuery;
const people = activeQuery.data?.pages.flatMap((p) => p.results) ?? [];
const observerRef = useRef<IntersectionObserver | null>(null);
const lastRef = useCallback(
(node: HTMLDivElement | null) => {
if (activeQuery.isFetchingNextPage) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && activeQuery.hasNextPage) {
activeQuery.fetchNextPage();
}
});
if (node) observerRef.current.observe(node);
},
[activeQuery.isFetchingNextPage, activeQuery.hasNextPage, activeQuery.fetchNextPage]
);
useEffect(() => {
return () => observerRef.current?.disconnect();
}, []);
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">People</h1>
<div className="relative max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search people..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
{activeQuery.isLoading ? (
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{Array.from({ length: 24 }).map((_, i) => (
<div key={i} className="flex flex-col items-center gap-2">
<Skeleton className="h-24 w-24 rounded-full" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
) : (
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
{people.map((person, index) => (
<div
key={person.id}
ref={index === people.length - 1 ? lastRef : undefined}
>
<Link
to={`/people/${person.id}`}
className="group flex flex-col items-center gap-2 text-center"
>
<Avatar className="h-24 w-24 transition-transform group-hover:scale-105">
<AvatarImage
src={getProfileUrl(person.profile_path)}
alt={person.name}
/>
<AvatarFallback>
{person.name
.split(' ')
.map((n) => n[0])
.join('')}
</AvatarFallback>
</Avatar>
<p className="text-sm font-medium line-clamp-2">
{person.name}
</p>
</Link>
</div>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,94 @@
import { useParams } from 'react-router-dom';
import { usePerson } from '@/hooks/usePeople';
import { useQuery } from '@tanstack/react-query';
import { peopleApi } from '@/api/people';
import { Skeleton } from '@/components/ui/skeleton';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { EntryCard } from '@/components/entries/EntryCard';
import { getProfileUrl, formatDate } from '@/lib/media-utils';
export function PersonDetailsPage() {
const { id } = useParams<{ id: string }>();
const personId = parseInt(id!, 10);
const { data: person, isLoading } = usePerson(personId);
if (isLoading || !person) {
return (
<div className="space-y-6">
<div className="flex gap-6">
<Skeleton className="h-48 w-48 rounded-full" />
<div className="flex-1 space-y-3">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-20 w-full" />
</div>
</div>
</div>
);
}
return (
<div className="space-y-8">
{/* Profile header */}
<div className="flex gap-8">
<Avatar className="h-48 w-48 shrink-0">
<AvatarImage
src={getProfileUrl(person.profile_path)}
alt={person.name}
/>
<AvatarFallback className="text-3xl">
{person.name
.split(' ')
.map((n: string) => n[0])
.join('')}
</AvatarFallback>
</Avatar>
<div className="space-y-3">
<h1 className="text-3xl font-bold">{person.name}</h1>
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{person.known_for_department && (
<span>{person.known_for_department}</span>
)}
{person.birthday && (
<>
<span>•</span>
<span>Born: {formatDate(person.birthday)}</span>
</>
)}
{person.deathday && (
<>
<span>•</span>
<span>Died: {formatDate(person.deathday)}</span>
</>
)}
{person.place_of_birth && (
<>
<span>•</span>
<span>{person.place_of_birth}</span>
</>
)}
</div>
{person.biography && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl line-clamp-6">
{person.biography}
</p>
)}
</div>
</div>
<Separator />
{/* Filmography placeholder */}
<div className="space-y-4">
<h2 className="text-xl font-semibold">Filmography</h2>
<p className="text-sm text-muted-foreground">
Filmography details will be loaded from credits associated with this person.
</p>
</div>
</div>
);
}
+156
View File
@@ -0,0 +1,156 @@
import { useParams, Link } from 'react-router-dom';
import { useSeason, useSeasonEpisodes } from '@/hooks/useSeasons';
import { Skeleton } from '@/components/ui/skeleton';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Eye, CheckCircle2 } from 'lucide-react';
import { getTmdbPosterUrl, getYear, formatDate } from '@/lib/media-utils';
export function SeasonPage() {
const { entryId, seasonId } = useParams<{
entryId: string;
seasonId: string;
}>();
const { data: season, isLoading } = useSeason(parseInt(seasonId!, 10));
const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10));
if (isLoading || !season) {
return (
<div className="space-y-6">
<div className="flex gap-6">
<Skeleton className="h-56 w-36 shrink-0 rounded-lg" />
<div className="flex-1 space-y-3">
<Skeleton className="h-6 w-48" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-64" />
</div>
</div>
</div>
);
}
const watchedCount = episodes.filter(
(ep) =>
ep.date_first_seen ||
(ep.episodeSeens && ep.episodeSeens.length > 0)
).length;
const totalEpisodes = episodes.length;
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0;
return (
<div className="space-y-8">
{/* Header */}
<div className="flex gap-6">
<img
src={getTmdbPosterUrl(season.poster_path, 'w185')}
alt={season.name}
className="h-56 w-36 shrink-0 rounded-lg object-cover shadow-lg"
/>
<div className="flex flex-col justify-center space-y-3">
<h1 className="text-2xl font-bold">{season.name}</h1>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>Season {season.season_number}</span>
{season.air_date && (
<>
<span>•</span>
<span>{getYear(season.air_date)}</span>
</>
)}
<span>•</span>
<span>{totalEpisodes} episodes</span>
</div>
{/* Watch progress */}
<div className="flex items-center gap-3 max-w-xs">
<Progress value={progress} className="flex-1 h-2" />
<span className="text-sm font-medium">
{watchedCount}/{totalEpisodes}
</span>
</div>
{season.overview && (
<p className="text-sm text-muted-foreground max-w-lg">
{season.overview}
</p>
)}
</div>
</div>
{/* Episodes */}
<div className="space-y-3">
<h3 className="text-lg font-semibold">Episodes</h3>
<div className="space-y-2">
{episodes.map((episode) => {
const isWatched =
!!episode.date_first_seen ||
(episode.episodeSeens && episode.episodeSeens.length > 0);
return (
<Link
key={episode.id}
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="flex gap-4 rounded-lg border border-border p-3 transition-colors hover:bg-accent/50"
>
{/* Thumbnail */}
<div className="h-16 w-28 shrink-0 overflow-hidden rounded bg-muted">
{episode.still_path ? (
<img
src={getTmdbPosterUrl(episode.still_path, 'w300')}
alt={episode.name}
className="h-full w-full object-cover"
loading="lazy"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
No Image
</div>
)}
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
E{episode.episode_number}
</span>
<span className="text-sm font-medium truncate">
{episode.name}
</span>
{isWatched && (
<CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />
)}
</div>
{episode.air_date && (
<p className="text-xs text-muted-foreground">
{formatDate(episode.air_date)}
</p>
)}
{episode.overview && (
<p className="mt-1 text-xs text-muted-foreground line-clamp-2">
{episode.overview}
</p>
)}
</div>
{/* Watch button */}
<Button
size="icon"
variant={isWatched ? 'secondary' : 'outline'}
className="h-8 w-8 shrink-0 self-center"
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
// TODO: Mark episode as watched
}}
>
<Eye className="h-4 w-4" />
</Button>
</Link>
);
})}
</div>
</div>
</div>
);
}
+104
View File
@@ -0,0 +1,104 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { settingsApi } from '@/api/settings';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Save } from 'lucide-react';
import type { Settings } from '@/types';
const settingsSchema = z.object({
tmdbApiKey: z.string().min(1, 'TMDB API key is required'),
backPort: z.coerce.number().int().positive(),
});
export function SettingsPage() {
const queryClient = useQueryClient();
const { data: settings, isLoading } = useQuery({
queryKey: ['settings'],
queryFn: settingsApi.get,
});
const updateSettings = useMutation({
mutationFn: (data: Partial<Settings>) => settingsApi.update(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings'] });
},
});
const {
register,
handleSubmit,
formState: { errors, isDirty },
} = useForm({
resolver: zodResolver(settingsSchema),
values: settings
? { tmdbApiKey: settings.tmdbApiKey, backPort: settings.backPort }
: undefined,
});
const onSubmit = (data: { tmdbApiKey: string; backPort: number }) => {
updateSettings.mutate(data);
};
if (isLoading) {
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Settings</h1>
<Skeleton className="h-48 w-full" />
</div>
);
}
return (
<div className="space-y-6 max-w-2xl">
<h1 className="text-2xl font-bold">Settings</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle>General</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="tmdbApiKey">TMDB API Key</Label>
<Input
id="tmdbApiKey"
type="password"
{...register('tmdbApiKey')}
/>
{errors.tmdbApiKey && (
<p className="text-xs text-destructive">
{errors.tmdbApiKey.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="backPort">Backend Port</Label>
<Input
id="backPort"
type="number"
{...register('backPort')}
/>
{errors.backPort && (
<p className="text-xs text-destructive">
{errors.backPort.message}
</p>
)}
</div>
<Button type="submit" disabled={!isDirty || updateSettings.isPending}>
<Save className="mr-2 h-4 w-4" />
{updateSettings.isPending ? 'Saving...' : 'Save Settings'}
</Button>
</CardContent>
</Card>
</form>
</div>
);
}
+237
View File
@@ -0,0 +1,237 @@
import { useState, useMemo, useCallback } from 'react';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Search, SlidersHorizontal, ArrowUpDown } from 'lucide-react';
import type { Entry } from '@/types';
type SortField = 'createdAt' | 'date_last_seen' | 'title' | 'release_date' | 'rating';
type SortDir = 'asc' | 'desc';
interface Filters {
genre: string;
ratingMin: string;
ratingMax: string;
yearMin: string;
yearMax: string;
}
const defaultFilters: Filters = { genre: '', ratingMin: '', ratingMax: '', yearMin: '', yearMax: '' };
const sortLabels: Record<SortField, string> = {
createdAt: 'Date Added',
date_last_seen: 'Last Watched',
title: 'Title',
release_date: 'Release Date',
rating: 'Rating',
};
function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[] {
return [...entries].sort((a, b) => {
let cmp = 0;
switch (field) {
case 'title':
cmp = a.title.localeCompare(b.title);
break;
case 'release_date':
cmp = new Date(a.release_date || '1900').getTime() - new Date(b.release_date || '1900').getTime();
break;
case 'rating':
cmp = (a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0) -
(b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0);
break;
case 'date_last_seen':
cmp = new Date(a.date_last_seen || '1900').getTime() - new Date(b.date_last_seen || '1900').getTime();
break;
case 'createdAt':
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
break;
}
return dir === 'desc' ? -cmp : cmp;
});
}
export function WatchlistPage() {
const { isLoading } = useLibrary();
const [search, setSearch] = useState('');
const [sortField, setSortField] = useState<SortField>('createdAt');
const [sortDir, setSortDir] = useState<SortDir>('desc');
const [filters, setFilters] = useState<Filters>(defaultFilters);
const allEntries = useLibraryEntries();
const watchlist = useMemo(() => allEntries.filter((e) => e.watchlist), [allEntries]);
const allGenres = useMemo(() => {
const set = new Set<string>();
watchlist.forEach((e) => e.genres?.forEach((g) => set.add(g.name)));
return Array.from(set).sort();
}, [watchlist]);
const hasActiveFilters = filters.genre || filters.ratingMin || filters.ratingMax || filters.yearMin || filters.yearMax;
const filtered = useMemo(() => {
let result = watchlist;
if (search) {
const q = search.toLowerCase();
result = result.filter((e) => e.title.toLowerCase().includes(q));
}
if (filters.genre) {
result = result.filter((e) => e.genres?.some((g) => g.name === filters.genre));
}
if (filters.ratingMin) {
const min = parseFloat(filters.ratingMin);
result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) >= min);
}
if (filters.ratingMax) {
const max = parseFloat(filters.ratingMax);
result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) <= max);
}
if (filters.yearMin) {
const min = parseInt(filters.yearMin);
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() >= min);
}
if (filters.yearMax) {
const max = parseInt(filters.yearMax);
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() <= max);
}
return sortEntries(result, sortField, sortDir);
}, [watchlist, search, filters, sortField, sortDir]);
const clearFilters = useCallback(() => setFilters(defaultFilters), []);
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Watchlist</h1>
<div className="flex flex-wrap items-center gap-3">
{/* Search */}
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search watchlist..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
{/* Spacer */}
<div className="flex-1" />
{/* Sort */}
<div className="flex items-center gap-1">
<ArrowUpDown className="h-4 w-4 text-muted-foreground" />
<Select value={sortField} onValueChange={(v) => setSortField(v as SortField)}>
<SelectTrigger className="w-[160px] h-9">
<SelectValue>{sortLabels[sortField]}</SelectValue>
</SelectTrigger>
<SelectContent>
{Object.entries(sortLabels).map(([value, label]) => (
<SelectItem key={value} value={value}>{label}</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="ghost"
size="icon"
className="h-9 w-9"
onClick={() => setSortDir((d) => (d === 'desc' ? 'asc' : 'desc'))}
>
<span className="text-xs font-medium">{sortDir === 'desc' ? '↓' : '↑'}</span>
</Button>
</div>
{/* Filter */}
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="h-9 gap-1">
<SlidersHorizontal className="h-4 w-4" />
Filter
{hasActiveFilters && <Badge variant="secondary" className="ml-1 h-5 px-1 text-[10px]">Active</Badge>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 space-y-4" align="end">
<div className="space-y-2">
<label className="text-sm font-medium">Genre</label>
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : v }))}>
<SelectTrigger className="h-9">
<SelectValue placeholder="All genres" />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all">All genres</SelectItem>
{allGenres.map((g) => (
<SelectItem key={g} value={g}>{g}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Rating Range</label>
<div className="flex items-center gap-2">
<Input
type="number"
placeholder="Min"
min={0}
max={10}
step={0.1}
value={filters.ratingMin}
onChange={(e) => setFilters((f) => ({ ...f, ratingMin: e.target.value }))}
className="h-9"
/>
<span className="text-muted-foreground">–</span>
<Input
type="number"
placeholder="Max"
min={0}
max={10}
step={0.1}
value={filters.ratingMax}
onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))}
className="h-9"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Year Range</label>
<div className="flex items-center gap-2">
<Input
type="number"
placeholder="From"
min={1900}
max={2099}
value={filters.yearMin}
onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))}
className="h-9"
/>
<span className="text-muted-foreground">–</span>
<Input
type="number"
placeholder="To"
min={1900}
max={2099}
value={filters.yearMax}
onChange={(e) => setFilters((f) => ({ ...f, yearMax: e.target.value }))}
className="h-9"
/>
</div>
</div>
{hasActiveFilters && (
<Button variant="ghost" size="sm" className="w-full" onClick={clearFilters}>
Clear Filters
</Button>
)}
</PopoverContent>
</Popover>
</div>
<EntryLibraryGrid entries={filtered} isLoading={isLoading} />
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
import { createBrowserRouter } from 'react-router-dom';
import { lazy, Suspense } from 'react';
import { AppLayout } from '@/components/layout/AppLayout';
import { Skeleton } from '@/components/ui/skeleton';
// Lazy-loaded pages
const HomePage = lazy(() =>
import('@/pages/HomePage').then((m) => ({ default: m.HomePage }))
);
const DashboardPage = lazy(() =>
import('@/pages/DashboardPage').then((m) => ({ default: m.DashboardPage }))
);
const LibraryPage = lazy(() =>
import('@/pages/LibraryPage').then((m) => ({ default: m.LibraryPage }))
);
const WatchlistPage = lazy(() =>
import('@/pages/WatchlistPage').then((m) => ({ default: m.WatchlistPage }))
);
const CollectionsPage = lazy(() =>
import('@/pages/CollectionsPage').then((m) => ({
default: m.CollectionsPage,
}))
);
const CollectionDetailsPage = lazy(() =>
import('@/pages/CollectionDetailsPage').then((m) => ({
default: m.CollectionDetailsPage,
}))
);
const MediaPage = lazy(() =>
import('@/pages/MediaPage').then((m) => ({ default: m.MediaPage }))
);
const CalendarPage = lazy(() =>
import('@/pages/CalendarPage').then((m) => ({ default: m.CalendarPage }))
);
const EntryDetailsPage = lazy(() =>
import('@/pages/EntryDetailsPage').then((m) => ({
default: m.EntryDetailsPage,
}))
);
const SeasonPage = lazy(() =>
import('@/pages/SeasonPage').then((m) => ({ default: m.SeasonPage }))
);
const EpisodePage = lazy(() =>
import('@/pages/EpisodePage').then((m) => ({ default: m.EpisodePage }))
);
const PeoplePage = lazy(() =>
import('@/pages/PeoplePage').then((m) => ({ default: m.PeoplePage }))
);
const PersonDetailsPage = lazy(() =>
import('@/pages/PersonDetailsPage').then((m) => ({
default: m.PersonDetailsPage,
}))
);
const SettingsPage = lazy(() =>
import('@/pages/SettingsPage').then((m) => ({ default: m.SettingsPage }))
);
function PageFallback() {
return (
<div className="space-y-4 p-6">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-64 w-full" />
</div>
);
}
function SuspensePage({ children }: { children: React.ReactNode }) {
return <Suspense fallback={<PageFallback />}>{children}</Suspense>;
}
export const router = createBrowserRouter([
{
element: <AppLayout />,
children: [
{
path: '/',
element: (
<SuspensePage>
<HomePage />
</SuspensePage>
),
},
{
path: '/dashboard',
element: (
<SuspensePage>
<DashboardPage />
</SuspensePage>
),
},
{
path: '/library',
element: (
<SuspensePage>
<LibraryPage />
</SuspensePage>
),
},
{
path: '/watchlist',
element: (
<SuspensePage>
<WatchlistPage />
</SuspensePage>
),
},
{
path: '/collections',
element: (
<SuspensePage>
<CollectionsPage />
</SuspensePage>
),
},
{
path: '/collections/:id',
element: (
<SuspensePage>
<CollectionDetailsPage />
</SuspensePage>
),
},
{
path: '/media',
element: (
<SuspensePage>
<MediaPage />
</SuspensePage>
),
},
{
path: '/calendar',
element: (
<SuspensePage>
<CalendarPage />
</SuspensePage>
),
},
{
path: '/entry/:id',
element: (
<SuspensePage>
<EntryDetailsPage />
</SuspensePage>
),
},
{
path: '/entry/:entryId/season/:seasonId',
element: (
<SuspensePage>
<SeasonPage />
</SuspensePage>
),
},
{
path: '/entry/:entryId/season/:seasonId/episode/:episodeId',
element: (
<SuspensePage>
<EpisodePage />
</SuspensePage>
),
},
{
path: '/people',
element: (
<SuspensePage>
<PeoplePage />
</SuspensePage>
),
},
{
path: '/people/:id',
element: (
<SuspensePage>
<PersonDetailsPage />
</SuspensePage>
),
},
{
path: '/settings',
element: (
<SuspensePage>
<SettingsPage />
</SuspensePage>
),
},
],
},
]);
@@ -0,0 +1,59 @@
import { create } from 'zustand';
import type { Entry } from '@/types';
interface LibraryState {
entries: Map<number, Entry>;
isLoaded: boolean;
// Actions
setEntries: (entries: Entry[]) => void;
addEntry: (entry: Entry) => void;
updateEntry: (id: number, data: Partial<Entry>) => void;
removeEntry: (id: number) => void;
}
export const useLibraryStore = create<LibraryState>((set) => ({
entries: new Map(),
isLoaded: false,
setEntries: (entries) => {
const map = new Map<number, Entry>();
entries.forEach((entry) => {
map.set(entry.id, { ...entry, isInLibrary: true });
});
set({ entries: map, isLoaded: true });
},
addEntry: (entry) => {
set((state) => {
const newEntries = new Map(state.entries);
newEntries.set(entry.id, { ...entry, isInLibrary: true });
return { entries: newEntries };
});
},
updateEntry: (id, data) => {
set((state) => {
const existing = state.entries.get(id);
if (!existing) return state;
const newEntries = new Map(state.entries);
newEntries.set(id, { ...existing, ...data });
return { entries: newEntries };
});
},
removeEntry: (id) => {
set((state) => {
const newEntries = new Map(state.entries);
newEntries.delete(id);
return { entries: newEntries };
});
},
}));
// Derived selectors — call these outside of Zustand selectors
// Use with: const entries = useLibraryEntries();
export function useLibraryEntries() {
const entries = useLibraryStore((s) => s.entries);
return Array.from(entries.values());
}
+232
View File
@@ -0,0 +1,232 @@
// Entry types
export interface EntryIds {
tmdb_id: number | null;
imdb_id: string | null;
tvdb_id: number | null;
}
export interface EntryRatings {
user_rating: number | null;
tmdb_rating: number | null;
imdb_rating: number | null;
rotten_tomatoes_rating: number | null;
}
export interface Media {
id: number;
mediaable: 'entry' | 'people' | 'collection' | 'season' | 'episode';
mediaable_id: number;
type: 'poster' | 'backdrop' | 'logo' | 'still' | 'profile';
path: string;
is_local: boolean;
is_selected: boolean;
is_custom: boolean;
is_favorit: boolean;
}
export interface Entry {
id: number;
title: string;
original_title: string | null;
release_date: string | null;
runtime: number | null;
storyline: string | null;
country: string | null;
is_tvseries: boolean;
status: string | null;
poster_path: string | null;
banner_path: string | null;
watchlist: boolean;
favorit: boolean;
hidden: boolean;
note: string | null;
date_first_seen: string | null;
date_last_seen: string | null;
createdAt: string;
updatedAt: string;
// Relations
entryIds?: EntryIds;
entryRatings?: EntryRatings;
medias?: Media[];
genres?: Genre[];
credits?: Credit[];
seasons?: Season[];
entrySeens?: EntrySeen[];
episodeSeens?: EpisodeSeen[];
networks?: Network[];
// Computed for library
isInLibrary?: boolean;
isInWatchlist?: boolean;
}
export interface Season {
id: number;
entry_id: number;
name: string;
season_number: number;
episode_count: number;
air_date: string | null;
user_rating: number | null;
tmdb_rating: number | null;
imdb_rating: number | null;
poster_path: string | null;
banner_path: string | null;
overview: string | null;
createdAt: string;
updatedAt: string;
episodes?: Episode[];
}
export interface Episode {
id: number;
season_id: number;
name: string;
episode_number: number;
episode_type: string | null;
runtime: number | null;
air_date: string | null;
user_rating: number | null;
tmdb_rating: number | null;
still_path: string | null;
overview: string | null;
date_first_seen: string | null;
date_last_seen: string | null;
createdAt: string;
updatedAt: string;
episodeSeens?: EpisodeSeen[];
guest_stars?: Credit[];
}
export interface EntrySeen {
id: number;
entry_id: number;
date_seen: string;
seen_with: string | null;
createdAt: string;
updatedAt: string;
}
export interface EpisodeSeen {
id: number;
entry_id: number;
episode_id: number;
date_seen: string;
seen_with: string | null;
createdAt: string;
updatedAt: string;
}
export interface Collection {
id: number;
tmdb_id: number | null;
name: string;
description: string | null;
user_rating: number | null;
poster_path: string | null;
backdrop_path: string | null;
is_local: boolean;
is_user_collection: boolean;
createdAt: string;
updatedAt: string;
entries?: Entry[];
medias?: Media[];
}
export interface People {
id: number;
tmdb_id: number;
name: string;
birthday: string | null;
deathday: string | null;
gender: number;
biography: string | null;
place_of_birth: string | null;
known_for_department: string | null;
fully_fetched: boolean;
profile_path: string | null;
createdAt: string;
updatedAt: string;
}
export interface Credit {
id: number;
entry_id: number;
people_id: number;
character: string | null;
cast_type: 'cast' | 'crew';
department: string | null;
job: string | null;
order: number | null;
people?: People;
}
export interface Genre {
id: number;
name: string;
}
export interface Network {
id: number;
name: string;
origin_country: string | null;
homepage: string | null;
logo_path: string | null;
}
export interface Settings {
userDataPath: string;
tmdbApiUrl: string;
tmdbApiKey: string;
frontPort: string;
backPort: number;
portableMode: string;
libraryViewMode: string;
favoritViewMode: string;
watchlistViewMode: string;
CollectionsViewMode: string;
CollectionItemsViewMode: string;
favoritsViewMode: string;
}
export interface Statistics {
totalMovies: number;
totalTvSeries: number;
totalFavorites: number;
totalWatchlist: number;
totalWatchTime: number;
}
// TMDB types for discover/search
export interface TmdbEntry {
id: number;
title?: string;
name?: string;
original_title?: string;
original_name?: string;
release_date?: string;
first_air_date?: string;
overview: string;
poster_path: string | null;
backdrop_path: string | null;
vote_average: number;
vote_count: number;
genre_ids: number[];
media_type?: string;
popularity: number;
}
export interface TmdbPerson {
id: number;
name: string;
profile_path: string | null;
known_for_department: string | null;
popularity: number;
known_for?: TmdbEntry[];
}
export interface TmdbPaginatedResponse<T> {
page: number;
results: T[];
total_pages: number;
total_results: number;
}
+8
View File
@@ -11,4 +11,12 @@ export default defineConfig({
'@': path.resolve(__dirname, './src'),
},
},
server: {
proxy: {
'/api': {
target: 'http://showyback.coolguy.space',
changeOrigin: true,
},
},
},
})