Normalize to double quotes across all files with Prettier

This commit is contained in:
X4Lo committed 2026-06-21 22:28:08 +01:00
1 parent 73bff72cec
commit a5659cf4c8
190 files changed
+9523 -8859

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
{
"singleQuote": false,
"trailingComma": "all",
"tabWidth": 2,
"semi": true
}
+11 -6
View File
@@ -1,8 +1,8 @@
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { TooltipProvider } from '@/components/ui/tooltip';
import { Toaster } from '@/components/ui/sonner';
import { router } from './router';
import { RouterProvider } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Toaster } from "@/components/ui/sonner";
import { router } from "./router";
const queryClient = new QueryClient({
defaultOptions: {
@@ -19,7 +19,12 @@ export function App() {
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<RouterProvider router={router} />
<Toaster position="bottom-right" richColors closeButton duration={3000} />
<Toaster
position="bottom-right"
richColors
closeButton
duration={3000}
/>
</TooltipProvider>
</QueryClientProvider>
);
+13 -10
View File
@@ -1,11 +1,11 @@
import { api } from '@/lib/api';
import { normalizeCollection } from '@/lib/normalizers';
import type { Collection } from '@/types';
import { api } from "@/lib/api";
import { normalizeCollection } from "@/lib/normalizers";
import type { Collection } from "@/types";
export const collectionsApi = {
getAll: () =>
api
.get<Collection[]>('/collections')
.get<Collection[]>("/collections")
.then((r) => r.data.map(normalizeCollection)),
getById: (id: number) =>
@@ -14,23 +14,26 @@ export const collectionsApi = {
.then((r) => normalizeCollection(r.data)),
create: (data: Partial<Collection>) =>
api.post<Collection>('/collections', data).then((r) => r.data),
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)),
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' },
headers: { "Content-Type": "multipart/form-data" },
})
.then((r) => normalizeCollection(r.data)),
delete: (id: number) =>
api.delete(`/collections/${id}`).then((r) => r.data),
delete: (id: number) => api.delete(`/collections/${id}`).then((r) => r.data),
getCollectionParts: (id: number) =>
api.put<Collection>(`/collections/${id}/parts`).then((r) => normalizeCollection(r.data)),
api
.put<Collection>(`/collections/${id}/parts`)
.then((r) => normalizeCollection(r.data)),
addEntry: (collectionId: number, entryId: number) =>
api
+28 -15
View File
@@ -1,19 +1,23 @@
import { api } from '@/lib/api';
import { normalizeEntry, normalizeCredit } from '@/lib/normalizers';
import type { Entry, Credit, TmdbPreview } from '@/types';
import { api } from "@/lib/api";
import { normalizeEntry, normalizeCredit } from "@/lib/normalizers";
import type { Entry, Credit, TmdbPreview } from "@/types";
export const entriesApi = {
getAll: () =>
api.get<Entry[]>('/entries').then((r) => r.data.map(normalizeEntry)),
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)),
api
.post<Entry>("/entries", { tmdb_id, is_tvserie })
.then((r) => normalizeEntry(r.data)),
update: (id: number, data: Partial<Entry>) =>
api.put<Entry>(`/entries/${id}`, { entryData: data }).then((r) => normalizeEntry(r.data)),
api
.put<Entry>(`/entries/${id}`, { entryData: data })
.then((r) => normalizeEntry(r.data)),
updateRatings: (
id: number,
@@ -23,39 +27,48 @@ export const entriesApi = {
tmdb_rating?: number | null;
imdb_rating?: number | null;
rotten_tomatoes_rating?: number | null;
}
) => api.put(`/entries/${id}/ratings`, { entryRatings: ratings }).then((r) => r.data),
},
) =>
api
.put(`/entries/${id}/ratings`, { entryRatings: ratings })
.then((r) => r.data),
updateIds: (
id: number,
ids: { tmdb_id?: number; imdb_id?: string; tvdb_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)),
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 : []),
api
.get(`/entries/${id}/seasons`)
.then((r) => (Array.isArray(r.data) ? r.data : [])),
getCredits: (id: number) =>
api
.get<Credit[]>(`/entries/${id}/credits`)
.then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])),
syncSeries: () => api.get('/entries/sync-series').then((r) => r.data),
syncSeries: () => api.get("/entries/sync-series").then((r) => r.data),
previewTmdb: (tmdbId: number, type: 'movie' | 'tv') =>
api.get<TmdbPreview>(`/entries/tmdb/preview/${type}/${tmdbId}`).then((r) => r.data),
previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
api
.get<TmdbPreview>(`/entries/tmdb/preview/${type}/${tmdbId}`)
.then((r) => r.data),
uploadMedia: (id: number, formData: FormData) =>
api
.post(`/entries/${id}/media`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
headers: { "Content-Type": "multipart/form-data" },
})
.then((r) => r.data),
+9 -5
View File
@@ -1,8 +1,8 @@
import { api } from '@/lib/api';
import type { EntrySeen } from '@/types';
import { api } from "@/lib/api";
import type { EntrySeen } from "@/types";
export const entrySeenApi = {
getAll: () => api.get<EntrySeen[]>('/entry-seen').then((r) => r.data),
getAll: () => api.get<EntrySeen[]>("/entry-seen").then((r) => r.data),
getById: (id: number) =>
api.get<EntrySeen>(`/entry-seen/${id}`).then((r) => r.data),
@@ -16,8 +16,12 @@ export const entrySeenApi = {
throw err;
}),
create: (data: { entry_id: number; date_seen: string; seen_with?: string; accuracy?: string }) =>
api.post<EntrySeen>('/entry-seen', data).then((r) => r.data),
create: (data: {
entry_id: number;
date_seen: string;
seen_with?: string;
accuracy?: 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),
+5 -6
View File
@@ -1,8 +1,8 @@
import { api } from '@/lib/api';
import type { EpisodeSeen } from '@/types';
import { api } from "@/lib/api";
import type { EpisodeSeen } from "@/types";
export const episodeSeenApi = {
getAll: () => api.get<EpisodeSeen[]>('/episode-seen').then((r) => r.data),
getAll: () => api.get<EpisodeSeen[]>("/episode-seen").then((r) => r.data),
getById: (id: number) =>
api.get<EpisodeSeen>(`/episode-seen/${id}`).then((r) => r.data),
@@ -22,11 +22,10 @@ export const episodeSeenApi = {
date_seen: string;
seen_with?: string;
accuracy?: string;
}) => api.post<EpisodeSeen>('/episode-seen', data).then((r) => r.data),
}) => 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),
delete: (id: number) => api.delete(`/episode-seen/${id}`).then((r) => r.data),
};
+2 -2
View File
@@ -1,5 +1,5 @@
import { api } from '@/lib/api';
import type { Episode } from '@/types';
import { api } from "@/lib/api";
import type { Episode } from "@/types";
export const episodesApi = {
getByMonth: (startDate: string, endDate: string) =>
+18 -11
View File
@@ -1,5 +1,5 @@
import { api } from '@/lib/api';
import type { People, Credit } from '@/types';
import { api } from "@/lib/api";
import type { People, Credit } from "@/types";
export interface TmdbFilmographyItem {
id: number;
@@ -8,7 +8,7 @@ export interface TmdbFilmographyItem {
poster_path: string | null;
release_date?: string;
first_air_date?: string;
media_type: 'movie' | 'tv';
media_type: "movie" | "tv";
character?: string;
job?: string;
department?: string;
@@ -44,31 +44,38 @@ export interface PaginatedPeopleResponse {
}
export const peopleApi = {
getAll: () => api.get<People[]>('/people').then((r) => r.data),
getAll: () => api.get<People[]>("/people").then((r) => r.data),
getAllPaginated: (page: number, limit: number, search?: string) =>
api
.get<PaginatedPeopleResponse>('/people', { params: { page, limit, ...(search ? { search } : {}) } })
.get<PaginatedPeopleResponse>("/people", {
params: { page, limit, ...(search ? { search } : {}) },
})
.then((r) => r.data),
getById: (id: number) =>
api.get<People>(`/people/${id}`).then((r) => r.data),
getById: (id: number) => api.get<People>(`/people/${id}`).then((r) => r.data),
getCredits: (id: number) =>
api.get<Credit[]>(`/people/${id}/credits`).then((r) => r.data),
getTmdbFilmography: (id: number) =>
api.get<TmdbFilmographyResponse>(`/people/${id}/tmdb-filmography`).then((r) => r.data),
api
.get<TmdbFilmographyResponse>(`/people/${id}/tmdb-filmography`)
.then((r) => r.data),
previewTmdb: (tmdbId: number) =>
api.get<TmdbPersonPreview>(`/people/tmdb/preview/${tmdbId}`).then((r) => r.data),
api
.get<TmdbPersonPreview>(`/people/tmdb/preview/${tmdbId}`)
.then((r) => r.data),
fetchByTmdbId: (tmdb_id: number, pinned = false) =>
api.post<People>('/people/fetch', { tmdb_id, pinned }).then((r) => r.data),
api.post<People>("/people/fetch", { tmdb_id, pinned }).then((r) => r.data),
update: (id: number, data: Partial<People>) =>
api.put<People>(`/people/${id}`, data).then((r) => r.data),
search: (query: string) =>
api.get<People[]>('/people/search', { params: { query } }).then((r) => r.data),
api
.get<People[]>("/people/search", { params: { query } })
.then((r) => r.data),
};
+4 -4
View File
@@ -1,8 +1,8 @@
import { api } from '@/lib/api';
import type { Season, Episode } from '@/types';
import { api } from "@/lib/api";
import type { Season, Episode } from "@/types";
export const seasonsApi = {
getAll: () => api.get<Season[]>('/seasons').then((r) => r.data),
getAll: () => api.get<Season[]>("/seasons").then((r) => r.data),
getById: (id: number) =>
api.get<Season>(`/seasons/${id}`).then((r) => r.data),
@@ -11,7 +11,7 @@ export const seasonsApi = {
api.get<Episode[]>(`/seasons/${id}/episodes`).then((r) => r.data),
create: (data: Partial<Season>) =>
api.post<Season>('/seasons', data).then((r) => r.data),
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),
+4 -4
View File
@@ -1,9 +1,9 @@
import { api } from '@/lib/api';
import type { Settings } from '@/types';
import { api } from "@/lib/api";
import type { Settings } from "@/types";
export const settingsApi = {
get: () => api.get<Settings>('/settings').then((r) => r.data),
get: () => api.get<Settings>("/settings").then((r) => r.data),
update: (data: Partial<Settings>) =>
api.put<Settings>('/settings', data).then((r) => r.data),
api.put<Settings>("/settings", data).then((r) => r.data),
};
+11 -5
View File
@@ -1,4 +1,4 @@
import { api } from '@/lib/api';
import { api } from "@/lib/api";
export interface MonthlyCountItem {
month: number;
@@ -37,11 +37,17 @@ export interface AllTimeWatchTime {
export const statisticsApi = {
getAllTimeWatchTime: () =>
api.get<AllTimeWatchTime>('/statistics/watch-time').then((r) => r.data),
api.get<AllTimeWatchTime>("/statistics/watch-time").then((r) => r.data),
getYearlyWatchCount: (year: number) =>
api.get<YearlyWatchCount>(`/statistics/watch-count/year/${year}`).then((r) => r.data),
api
.get<YearlyWatchCount>(`/statistics/watch-count/year/${year}`)
.then((r) => r.data),
getYearlyWatchTime: (year: number) =>
api.get<YearlyWatchTime>(`/statistics/watch-time/year/${year}`).then((r) => r.data),
api
.get<YearlyWatchTime>(`/statistics/watch-time/year/${year}`)
.then((r) => r.data),
getWatchdayDistribution: () =>
api.get<WatchdayDistribution>('/statistics/watch-weekday').then((r) => r.data),
api
.get<WatchdayDistribution>("/statistics/watch-weekday")
.then((r) => r.data),
};
+12 -12
View File
@@ -1,73 +1,73 @@
import { api } from '@/lib/api';
import type { TmdbEntry, TmdbPaginatedResponse, TmdbPerson } from '@/types';
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', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/popular/movie", {
params: { page },
})
.then((r) => r.data),
getPopularTv: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/popular/tv', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/popular/tv", {
params: { page },
})
.then((r) => r.data),
getTrendingMovies: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/trending/movie', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/trending/movie", {
params: { page },
})
.then((r) => r.data),
getTrendingTv: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/trending/tv', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/trending/tv", {
params: { page },
})
.then((r) => r.data),
getTopRatedMovies: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/top-rated/movie', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/top-rated/movie", {
params: { page },
})
.then((r) => r.data),
getTopRatedTv: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/top-rated/tv', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/top-rated/tv", {
params: { page },
})
.then((r) => r.data),
getUpcomingMovies: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/upcoming/movie', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/upcoming/movie", {
params: { page },
})
.then((r) => r.data),
search: (query: string, page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/search', {
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/search", {
params: { query, page },
})
.then((r) => r.data),
getPopularPeople: (page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbPerson>>('/people/tmdb/popular', {
.get<TmdbPaginatedResponse<TmdbPerson>>("/people/tmdb/popular", {
params: { page },
})
.then((r) => r.data),
searchPeople: (query: string, page = 1) =>
api
.get<TmdbPaginatedResponse<TmdbPerson>>('/people/tmdb/search', {
.get<TmdbPaginatedResponse<TmdbPerson>>("/people/tmdb/search", {
params: { query, page },
})
.then((r) => r.data),
+136 -65
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
Search,
Film,
@@ -16,22 +16,22 @@ import {
ArrowDown,
CornerDownLeft,
ArrowRight,
} from 'lucide-react';
import { tmdbApi } from '@/api/tmdb';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
import { useCreateEntry } from '@/hooks/useEntries';
import { getTmdbImageUrl } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { TmdbEntry } from '@/types';
} from "lucide-react";
import { tmdbApi } from "@/api/tmdb";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
import { useCreateEntry } from "@/hooks/useEntries";
import { getTmdbImageUrl } from "@/lib/api";
import { cn } from "@/lib/utils";
import type { TmdbEntry } from "@/types";
interface CommandItem {
id: string;
type: 'command' | 'library' | 'tmdb';
type: "command" | "library" | "tmdb";
title: string;
subtitle?: string;
year?: string;
mediaType?: 'movie' | 'tv';
mediaType?: "movie" | "tv";
posterPath?: string | null;
icon?: React.ReactNode;
inLibrary?: boolean;
@@ -41,23 +41,58 @@ interface CommandItem {
}
const NAVIGATION_COMMANDS: CommandItem[] = [
{ id: 'cmd-library', type: 'command', title: 'Go to Library', icon: <Library className="h-4 w-4" /> },
{ id: 'cmd-watchlist', type: 'command', title: 'Go to Watchlist', icon: <BookOpen className="h-4 w-4" /> },
{ id: 'cmd-stats', type: 'command', title: 'Go to Statistics', icon: <BarChart3 className="h-4 w-4" /> },
{ id: 'cmd-calendar', type: 'command', title: 'Go to Calendar', icon: <Calendar className="h-4 w-4" /> },
{ id: 'cmd-people', type: 'command', title: 'Go to People', icon: <Users className="h-4 w-4" /> },
{ id: 'cmd-settings', type: 'command', title: 'Go to Settings', icon: <Settings className="h-4 w-4" /> },
{ id: 'cmd-favorites', type: 'command', title: 'Go to Favorites', icon: <Star className="h-4 w-4" /> },
{
id: "cmd-library",
type: "command",
title: "Go to Library",
icon: <Library className="h-4 w-4" />,
},
{
id: "cmd-watchlist",
type: "command",
title: "Go to Watchlist",
icon: <BookOpen className="h-4 w-4" />,
},
{
id: "cmd-stats",
type: "command",
title: "Go to Statistics",
icon: <BarChart3 className="h-4 w-4" />,
},
{
id: "cmd-calendar",
type: "command",
title: "Go to Calendar",
icon: <Calendar className="h-4 w-4" />,
},
{
id: "cmd-people",
type: "command",
title: "Go to People",
icon: <Users className="h-4 w-4" />,
},
{
id: "cmd-settings",
type: "command",
title: "Go to Settings",
icon: <Settings className="h-4 w-4" />,
},
{
id: "cmd-favorites",
type: "command",
title: "Go to Favorites",
icon: <Star className="h-4 w-4" />,
},
];
const COMMAND_ROUTES: Record<string, string> = {
'cmd-library': '/library',
'cmd-watchlist': '/watchlist',
'cmd-stats': '/dashboard',
'cmd-calendar': '/calendar',
'cmd-people': '/people',
'cmd-settings': '/settings',
'cmd-favorites': '/library?filter=favorites',
"cmd-library": "/library",
"cmd-watchlist": "/watchlist",
"cmd-stats": "/dashboard",
"cmd-calendar": "/calendar",
"cmd-people": "/people",
"cmd-settings": "/settings",
"cmd-favorites": "/library?filter=favorites",
};
export function CommandPalette() {
@@ -68,8 +103,8 @@ export function CommandPalette() {
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const [query, setQuery] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState('');
const [query, setQuery] = useState("");
const [debouncedQuery, setDebouncedQuery] = useState("");
const [selectedIndex, setSelectedIndex] = useState(0);
// Debounce search query
@@ -81,8 +116,8 @@ export function CommandPalette() {
// Focus input when opened
useEffect(() => {
if (isOpen) {
setQuery('');
setDebouncedQuery('');
setQuery("");
setDebouncedQuery("");
setSelectedIndex(0);
setTimeout(() => inputRef.current?.focus(), 50);
}
@@ -90,7 +125,7 @@ export function CommandPalette() {
// TMDB search
const { data: tmdbResults, isFetching: tmdbLoading } = useQuery({
queryKey: ['command-palette', 'tmdb', debouncedQuery],
queryKey: ["command-palette", "tmdb", debouncedQuery],
queryFn: () => tmdbApi.search(debouncedQuery, 1),
enabled: debouncedQuery.length > 1,
staleTime: 60 * 1000,
@@ -98,7 +133,16 @@ export function CommandPalette() {
// Build library TMDB ID index for fast lookups
const libraryTmdbIndex = useMemo(() => {
const index = new Map<number, { id: number; title: string; is_tvseries: boolean; poster_path: string | null; rating: number | null }>();
const index = new Map<
number,
{
id: number;
title: string;
is_tvseries: boolean;
poster_path: string | null;
rating: number | null;
}
>();
libraryEntries.forEach((entry) => {
if (entry.entryIds?.tmdb_id) {
index.set(entry.entryIds.tmdb_id, {
@@ -122,10 +166,10 @@ export function CommandPalette() {
if (entry.title.toLowerCase().includes(lower)) {
results.push({
id: `lib-${entry.id}`,
type: 'library',
type: "library",
title: entry.title,
year: entry.release_date?.slice(0, 4),
mediaType: entry.is_tvseries ? 'tv' : 'movie',
mediaType: entry.is_tvseries ? "tv" : "movie",
posterPath: entry.poster_path,
inLibrary: true,
libraryId: entry.id,
@@ -145,13 +189,13 @@ export function CommandPalette() {
.filter((r: TmdbEntry) => !libraryTmdbIndex.has(r.id))
.slice(0, 8)
.map((r: TmdbEntry) => {
const mediaType = r.media_type === 'tv' || r.name ? 'tv' : 'movie';
const title = r.title || r.name || 'Unknown';
const mediaType = r.media_type === "tv" || r.name ? "tv" : "movie";
const title = r.title || r.name || "Unknown";
const year = (r.release_date || r.first_air_date)?.slice(0, 4);
return {
id: `tmdb-${r.id}`,
type: 'tmdb' as const,
type: "tmdb" as const,
title,
year,
mediaType,
@@ -167,7 +211,9 @@ export function CommandPalette() {
const filteredCommands = useMemo((): CommandItem[] => {
if (!query.trim()) return NAVIGATION_COMMANDS;
const lower = query.toLowerCase();
return NAVIGATION_COMMANDS.filter((c) => c.title.toLowerCase().includes(lower));
return NAVIGATION_COMMANDS.filter((c) =>
c.title.toLowerCase().includes(lower),
);
}, [query]);
// Recently viewed items (shown when no query)
@@ -175,7 +221,7 @@ export function CommandPalette() {
if (query.trim()) return [];
return recentlyViewed.map((r) => ({
id: `recent-${r.id}`,
type: (r.libraryId ? 'library' : 'tmdb') as 'library' | 'tmdb',
type: (r.libraryId ? "library" : "tmdb") as "library" | "tmdb",
title: r.title,
mediaType: r.type,
posterPath: r.poster_path,
@@ -187,7 +233,12 @@ export function CommandPalette() {
// All items combined
const allItems = useMemo(() => {
return [...filteredCommands, ...localResults, ...tmdbItems, ...(query ? [] : recentItems)];
return [
...filteredCommands,
...localResults,
...tmdbItems,
...(query ? [] : recentItems),
];
}, [filteredCommands, localResults, tmdbItems, recentItems, query]);
// Keep selected index in bounds
@@ -199,13 +250,15 @@ export function CommandPalette() {
// Scroll selected item into view
useEffect(() => {
const el = listRef.current?.querySelector(`[data-index="${selectedIndex}"]`);
el?.scrollIntoView({ block: 'nearest' });
const el = listRef.current?.querySelector(
`[data-index="${selectedIndex}"]`,
);
el?.scrollIntoView({ block: "nearest" });
}, [selectedIndex]);
const handleSelect = useCallback(
(item: CommandItem, quickAdd = false) => {
if (item.type === 'command') {
if (item.type === "command") {
const route = COMMAND_ROUTES[item.id];
if (route) navigate(route);
close();
@@ -220,13 +273,13 @@ export function CommandPalette() {
if (quickAdd && item.tmdbId && item.mediaType) {
createEntry.mutate(
{ tmdb_id: item.tmdbId, is_tvserie: item.mediaType === 'tv' },
{ tmdb_id: item.tmdbId, is_tvserie: item.mediaType === "tv" },
{
onSuccess: (entry) => {
navigate(`/entry/${entry.id}`);
close();
},
}
},
);
return;
}
@@ -237,39 +290,42 @@ export function CommandPalette() {
close();
}
},
[navigate, close, createEntry]
[navigate, close, createEntry],
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
case "ArrowDown":
e.preventDefault();
setSelectedIndex((i) => Math.min(i + 1, allItems.length - 1));
break;
case 'ArrowUp':
case "ArrowUp":
e.preventDefault();
setSelectedIndex((i) => Math.max(i - 1, 0));
break;
case 'Enter': {
case "Enter": {
e.preventDefault();
const item = allItems[selectedIndex];
if (item) handleSelect(item, e.shiftKey);
break;
}
case 'Escape':
case "Escape":
e.preventDefault();
close();
break;
}
},
[allItems, selectedIndex, handleSelect, close]
[allItems, selectedIndex, handleSelect, close],
);
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]" onClick={close}>
<div
className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]"
onClick={close}
>
{/* Backdrop */}
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
@@ -304,7 +360,7 @@ export function CommandPalette() {
{filteredCommands.length > 0 && (
<div>
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
{query ? 'Commands' : 'Quick Actions'}
{query ? "Commands" : "Quick Actions"}
</div>
{filteredCommands.map((item, i) => {
const idx = i;
@@ -346,7 +402,9 @@ export function CommandPalette() {
{localResults.length > 0 && (
<div>
<div className="flex items-center justify-between px-2 py-1.5">
<span className="text-xs font-medium text-muted-foreground">Library</span>
<span className="text-xs font-medium text-muted-foreground">
Library
</span>
<button
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => {
@@ -376,7 +434,9 @@ export function CommandPalette() {
{tmdbItems.length > 0 && (
<div>
<div className="flex items-center justify-between px-2 py-1.5">
<span className="text-xs font-medium text-muted-foreground">TMDB Results</span>
<span className="text-xs font-medium text-muted-foreground">
TMDB Results
</span>
<button
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => {
@@ -416,7 +476,9 @@ export function CommandPalette() {
<CornerDownLeft className="h-3 w-3" /> Open
</span>
<span className="flex items-center gap-1">
<kbd className="rounded border border-border px-1 font-mono text-[10px]">⇧</kbd>
<kbd className="rounded border border-border px-1 font-mono text-[10px]">
⇧
</kbd>
<CornerDownLeft className="h-3 w-3" /> Quick Add
</span>
<span className="flex items-center gap-1">
@@ -424,7 +486,10 @@ export function CommandPalette() {
<ArrowDown className="h-3 w-3" /> Navigate
</span>
<span className="ml-auto">
<kbd className="rounded border border-border px-1 font-mono text-[10px]">Esc</kbd> Close
<kbd className="rounded border border-border px-1 font-mono text-[10px]">
Esc
</kbd>{" "}
Close
</span>
</div>
</div>
@@ -447,25 +512,29 @@ function ResultRow({
<div
data-index={dataIndex}
className={cn(
'flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 transition-colors',
isSelected ? 'bg-accent text-accent-foreground' : 'hover:bg-muted'
"flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 transition-colors",
isSelected ? "bg-accent text-accent-foreground" : "hover:bg-muted",
)}
onClick={onClick}
>
{/* Poster or icon */}
{item.type === 'command' ? (
{item.type === "command" ? (
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted">
{item.icon}
</div>
) : item.posterPath ? (
<img
src={getTmdbImageUrl(item.posterPath, 'w92')}
src={getTmdbImageUrl(item.posterPath, "w92")}
alt=""
className="h-12 w-8 shrink-0 rounded object-cover"
/>
) : (
<div className="flex h-12 w-8 shrink-0 items-center justify-center rounded bg-muted">
{item.mediaType === 'tv' ? <Tv className="h-4 w-4 text-muted-foreground" /> : <Film className="h-4 w-4 text-muted-foreground" />}
{item.mediaType === "tv" ? (
<Tv className="h-4 w-4 text-muted-foreground" />
) : (
<Film className="h-4 w-4 text-muted-foreground" />
)}
</div>
)}
@@ -478,9 +547,11 @@ function ResultRow({
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{item.year && <span>{item.year}</span>}
{item.mediaType && (
<span className="capitalize">{item.mediaType === 'tv' ? 'TV Series' : 'Movie'}</span>
<span className="capitalize">
{item.mediaType === "tv" ? "TV Series" : "Movie"}
</span>
)}
{item.rating != null && item.type !== 'command' && (
{item.rating != null && item.type !== "command" && (
<span className="flex items-center gap-0.5">
<Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
{item.rating}
@@ -1,8 +1,8 @@
import { useCallback, useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { getCollectionPosterUrl } from '@/lib/media-utils';
import { Skeleton } from '@/components/ui/skeleton';
import type { Collection } from '@/types';
import { useCallback, useRef, useEffect } from "react";
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;
@@ -61,7 +61,7 @@ export function CollectionsGrid({
});
if (node) observerRef.current.observe(node);
},
[isLoading, hasMore, onLoadMore]
[isLoading, hasMore, onLoadMore],
);
useEffect(() => {
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useMemo } from "react";
import {
BarChart,
Bar,
@@ -8,30 +8,37 @@ import {
Tooltip,
Cell,
ResponsiveContainer,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useWatchdayDistribution } from '@/hooks/useStatistics';
import type { WatchdayItem } from '@/api/statistics';
} from "recharts";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useWatchdayDistribution } from "@/hooks/useStatistics";
import type { WatchdayItem } from "@/api/statistics";
// DAYOFWEEK: MySQL returns 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat
// We display Mon–Sun
const DAY_ORDER = [2, 3, 4, 5, 6, 7, 1];
const DAY_LABELS: Record<number, string> = {
1: 'Sun',
2: 'Mon',
3: 'Tue',
4: 'Wed',
5: 'Thu',
6: 'Fri',
7: 'Sat',
1: "Sun",
2: "Mon",
3: "Tue",
4: "Wed",
5: "Thu",
6: "Fri",
7: "Sat",
};
function buildChartData(episodes: WatchdayItem[], movies: WatchdayItem[]) {
return DAY_ORDER.map((dayNum) => {
const ep = episodes.find((x) => Number(x.day) === dayNum);
const mv = movies.find((x) => Number(x.day) === dayNum);
const total = (ep ? parseInt(ep.count, 10) : 0) + (mv ? parseInt(mv.count, 10) : 0);
const total =
(ep ? parseInt(ep.count, 10) : 0) + (mv ? parseInt(mv.count, 10) : 0);
return { day: DAY_LABELS[dayNum], total, dayNum };
});
}
@@ -47,16 +54,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
return (
<div
style={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
padding: '8px 12px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
padding: "8px 12px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
>
<p style={{ fontWeight: 600 }}>{day}</p>
<p style={{ color: 'var(--color-muted-foreground)' }}>{total} {total === 1 ? 'watch' : 'watches'}</p>
<p style={{ color: "var(--color-muted-foreground)" }}>
{total} {total === 1 ? "watch" : "watches"}
</p>
</div>
);
}
@@ -71,7 +80,10 @@ export function CouchDayChart() {
const peakDay = useMemo(() => {
if (!chartData.length) return null;
return chartData.reduce((max, d) => (d.total > max.total ? d : max), chartData[0]);
return chartData.reduce(
(max, d) => (d.total > max.total ? d : max),
chartData[0],
);
}, [chartData]);
const maxTotal = Math.max(...chartData.map((d) => d.total), 1);
@@ -96,29 +108,39 @@ export function CouchDayChart() {
<Skeleton className="h-52 w-full" />
) : (
<ResponsiveContainer width="100%" height={210}>
<BarChart data={chartData} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
<BarChart
data={chartData}
margin={{ top: 4, right: 8, left: -20, bottom: 0 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--color-border)"
vertical={false}
/>
<XAxis
dataKey="day"
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<YAxis
allowDecimals={false}
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: 'var(--color-accent)' }} />
<Tooltip
content={<CustomTooltip />}
cursor={{ fill: "var(--color-accent)" }}
/>
<Bar dataKey="total" radius={[4, 4, 0, 0]}>
{chartData.map((entry) => (
<Cell
key={entry.day}
fill={
entry.total === maxTotal && entry.total > 0
? 'var(--color-chart-4)'
: 'var(--color-chart-1)'
? "var(--color-chart-4)"
: "var(--color-chart-1)"
}
opacity={entry.total === 0 ? 0.3 : 1}
/>
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react';
import { useMemo, useState } from "react";
import {
AreaChart,
Area,
@@ -7,15 +7,37 @@ import {
CartesianGrid,
Tooltip,
ResponsiveContainer,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { useLibraryEntries } from '@/stores/useLibraryStore';
} from "recharts";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { useLibraryEntries } from "@/stores/useLibraryStore";
const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const MONTH_LABELS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
interface CustomTooltipProps {
active?: boolean;
payload?: { value: number; payload: { month: string; count: number; cumulative: number } }[];
payload?: {
value: number;
payload: { month: string; count: number; cumulative: number };
}[];
}
function CustomTooltip({ active, payload }: CustomTooltipProps) {
@@ -24,17 +46,19 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
return (
<div
style={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
padding: '8px 12px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
padding: "8px 12px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
>
<p style={{ fontWeight: 600 }}>{d.month}</p>
<p style={{ color: 'var(--color-muted-foreground)' }}>+{d.count} added</p>
<p style={{ color: 'var(--color-muted-foreground)' }}>{d.cumulative} total</p>
<p style={{ color: "var(--color-muted-foreground)" }}>+{d.count} added</p>
<p style={{ color: "var(--color-muted-foreground)" }}>
{d.cumulative} total
</p>
</div>
);
}
@@ -43,8 +67,7 @@ export function LibraryGrowthChart() {
const allEntries = useLibraryEntries();
const currentYear = new Date().getFullYear();
const getEntryDate = (e: { createdAt?: string }) =>
e.createdAt || null;
const getEntryDate = (e: { createdAt?: string }) => e.createdAt || null;
const years = useMemo(() => {
const set = new Set<number>();
@@ -56,16 +79,17 @@ export function LibraryGrowthChart() {
return Array.from(set).sort((a, b) => b - a);
}, [allEntries, currentYear]);
const [year, setYear] = useState<number | 'all'>('all');
const [year, setYear] = useState<number | "all">("all");
// Ensure selected year is always valid
const effectiveYear = year === 'all' ? 'all' : (years.includes(year) ? year : years[0]);
const effectiveYear =
year === "all" ? "all" : years.includes(year) ? year : years[0];
const chartData = useMemo(() => {
// Include all entries (library + watchlist)
const entries = allEntries;
if (effectiveYear === 'all') {
if (effectiveYear === "all") {
// Build monthly data across all years
const dateEntries = entries
.map((e) => {
@@ -75,7 +99,11 @@ export function LibraryGrowthChart() {
.filter(Boolean) as Date[];
if (dateEntries.length === 0) {
return MONTH_LABELS.map((label) => ({ month: label, count: 0, cumulative: 0 }));
return MONTH_LABELS.map((label) => ({
month: label,
count: 0,
cumulative: 0,
}));
}
const minYear = Math.min(...dateEntries.map((d) => d.getFullYear()));
@@ -88,7 +116,7 @@ export function LibraryGrowthChart() {
for (let y = minYear; y <= maxYear; y++) {
for (let m = 0; m < 12; m++) {
const count = dateEntries.filter(
(d) => d.getFullYear() === y && d.getMonth() === m
(d) => d.getFullYear() === y && d.getMonth() === m,
).length;
cumulative += count;
data.push({
@@ -137,29 +165,50 @@ export function LibraryGrowthChart() {
value={effectiveYear}
onChange={(e) => {
const val = e.target.value;
setYear(val === 'all' ? 'all' : Number(val));
setYear(val === "all" ? "all" : Number(val));
}}
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
>
<option value="all">All</option>
{years.map((y) => (
<option key={y} value={y}>{y}</option>
<option key={y} value={y}>
{y}
</option>
))}
</select>
</div>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={260}>
<AreaChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
<AreaChart
data={chartData}
margin={{ top: 4, right: 8, left: -16, bottom: 0 }}
>
<defs>
<linearGradient id="colorGrowth" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--color-chart-4)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--color-chart-4)" stopOpacity={0} />
<stop
offset="5%"
stopColor="var(--color-chart-4)"
stopOpacity={0.3}
/>
<stop
offset="95%"
stopColor="var(--color-chart-4)"
stopOpacity={0}
/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
<XAxis dataKey="month" tick={{ fontSize: 12 }} stroke="var(--color-muted-foreground)" />
<YAxis tick={{ fontSize: 12 }} stroke="var(--color-muted-foreground)" allowDecimals={false} />
<XAxis
dataKey="month"
tick={{ fontSize: 12 }}
stroke="var(--color-muted-foreground)"
/>
<YAxis
tick={{ fontSize: 12 }}
stroke="var(--color-muted-foreground)"
allowDecimals={false}
/>
<Tooltip content={<CustomTooltip />} />
<Area
type="monotone"
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react';
import { useMemo, useState } from "react";
import {
PieChart,
Pie,
@@ -6,13 +6,19 @@ import {
ResponsiveContainer,
Tooltip,
Legend,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { useLibraryEntries } from '@/stores/useLibraryStore';
} from "recharts";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { useLibraryEntries } from "@/stores/useLibraryStore";
type Scope = 'library' | 'watchlist';
type Scope = "library" | "watchlist";
const COLORS = ['var(--color-chart-1)', 'var(--color-chart-2)'];
const COLORS = ["var(--color-chart-1)", "var(--color-chart-2)"];
interface CustomTooltipProps {
active?: boolean;
@@ -25,33 +31,34 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
return (
<div
style={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
padding: '8px 12px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
padding: "8px 12px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
>
<p style={{ fontWeight: 600 }}>{name}</p>
<p style={{ color: 'var(--color-muted-foreground)' }}>{value} titles</p>
<p style={{ color: "var(--color-muted-foreground)" }}>{value} titles</p>
</div>
);
}
export function MediaTypeChart() {
const allEntries = useLibraryEntries();
const [scope, setScope] = useState<Scope>('library');
const [scope, setScope] = useState<Scope>("library");
const chartData = useMemo(() => {
const filtered = scope === 'library'
? allEntries.filter((e) => !e.watchlist)
: allEntries.filter((e) => e.watchlist);
const filtered =
scope === "library"
? allEntries.filter((e) => !e.watchlist)
: allEntries.filter((e) => e.watchlist);
const movies = filtered.filter((e) => !e.is_tvseries).length;
const tv = filtered.filter((e) => e.is_tvseries).length;
return [
{ name: 'Movies', value: movies },
{ name: 'TV Series', value: tv },
{ name: "Movies", value: movies },
{ name: "TV Series", value: tv },
];
}, [allEntries, scope]);
@@ -68,14 +75,14 @@ export function MediaTypeChart() {
</CardDescription>
</div>
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
{(['library', 'watchlist'] as Scope[]).map((s) => (
{(["library", "watchlist"] as Scope[]).map((s) => (
<button
key={s}
onClick={() => setScope(s)}
className={`px-3 py-1.5 capitalize transition-colors ${
scope === s
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:bg-accent'
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-accent"
}`}
>
{s}
@@ -103,7 +110,11 @@ export function MediaTypeChart() {
<Tooltip content={<CustomTooltip />} />
<Legend
formatter={(value) => (
<span style={{ color: 'var(--color-foreground)', fontSize: '13px' }}>{value}</span>
<span
style={{ color: "var(--color-foreground)", fontSize: "13px" }}
>
{value}
</span>
)}
/>
</PieChart>
@@ -1,5 +1,5 @@
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
BarChart,
Bar,
@@ -9,12 +9,18 @@ import {
Tooltip,
Cell,
ResponsiveContainer,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import type { Entry } from '@/types';
} from "recharts";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { useLibraryEntries } from "@/stores/useLibraryStore";
import type { Entry } from "@/types";
type Filter = 'all' | 'movies' | 'series';
type Filter = "all" | "movies" | "series";
function buildRatingsData(entries: Entry[]) {
const counts: Record<number, number> = {};
@@ -37,16 +43,16 @@ function buildRatingsData(entries: Entry[]) {
// Color ramp: low scores red-ish → mid yellow-ish → high scores green/blue
const SCORE_COLORS: Record<number, string> = {
1: 'var(--color-chart-5)',
2: 'var(--color-chart-5)',
3: 'var(--color-chart-5)',
4: 'var(--color-chart-3)',
5: 'var(--color-chart-3)',
6: 'var(--color-chart-3)',
7: 'var(--color-chart-2)',
8: 'var(--color-chart-2)',
9: 'var(--color-chart-1)',
10: 'var(--color-chart-1)',
1: "var(--color-chart-5)",
2: "var(--color-chart-5)",
3: "var(--color-chart-5)",
4: "var(--color-chart-3)",
5: "var(--color-chart-3)",
6: "var(--color-chart-3)",
7: "var(--color-chart-2)",
8: "var(--color-chart-2)",
9: "var(--color-chart-1)",
10: "var(--color-chart-1)",
};
interface CustomTooltipProps {
@@ -60,16 +66,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
return (
<div
style={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
padding: '8px 12px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
padding: "8px 12px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
>
<p style={{ fontWeight: 600 }}>{score}</p>
<p style={{ color: 'var(--color-muted-foreground)' }}>{count} {count === 1 ? 'title' : 'titles'}</p>
<p style={{ color: "var(--color-muted-foreground)" }}>
{count} {count === 1 ? "title" : "titles"}
</p>
</div>
);
}
@@ -77,16 +85,19 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
export function RatingsChart() {
const allEntries = useLibraryEntries();
const navigate = useNavigate();
const [filter, setFilter] = useState<Filter>('all');
const [filter, setFilter] = useState<Filter>("all");
const filteredEntries = useMemo(() => {
const library = allEntries.filter((e) => !e.watchlist);
if (filter === 'movies') return library.filter((e) => !e.is_tvseries);
if (filter === 'series') return library.filter((e) => e.is_tvseries);
if (filter === "movies") return library.filter((e) => !e.is_tvseries);
if (filter === "series") return library.filter((e) => e.is_tvseries);
return library;
}, [allEntries, filter]);
const chartData = useMemo(() => buildRatingsData(filteredEntries), [filteredEntries]);
const chartData = useMemo(
() => buildRatingsData(filteredEntries),
[filteredEntries],
);
const ratedCount = filteredEntries.filter(
(e) => e.entryRatings?.user_rating != null,
@@ -99,18 +110,23 @@ export function RatingsChart() {
<div>
<CardTitle>My Ratings</CardTitle>
<CardDescription className="mt-1">
{ratedCount} rated {filter === 'all' ? 'titles' : filter === 'movies' ? 'movies' : 'series'}
{ratedCount} rated{" "}
{filter === "all"
? "titles"
: filter === "movies"
? "movies"
: "series"}
</CardDescription>
</div>
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
{(['all', 'movies', 'series'] as Filter[]).map((f) => (
{(["all", "movies", "series"] as Filter[]).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 capitalize transition-colors ${
filter === f
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:bg-accent'
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-accent"
}`}
>
{f}
@@ -121,21 +137,31 @@ export function RatingsChart() {
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={220}>
<BarChart data={chartData} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
<BarChart
data={chartData}
margin={{ top: 4, right: 8, left: -20, bottom: 0 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--color-border)"
vertical={false}
/>
<XAxis
dataKey="score"
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<YAxis
allowDecimals={false}
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: 'var(--color-accent)' }} />
<Tooltip
content={<CustomTooltip />}
cursor={{ fill: "var(--color-accent)" }}
/>
<Bar
dataKey="count"
radius={[4, 4, 0, 0]}
@@ -145,12 +171,12 @@ export function RatingsChart() {
navigate(`/library?ratingMin=${raw}&ratingMax=${raw}`);
}
}}
style={{ cursor: 'pointer' }}
style={{ cursor: "pointer" }}
>
{chartData.map((entry) => (
<Cell
key={entry.raw}
fill={SCORE_COLORS[entry.raw] ?? 'var(--color-chart-1)'}
fill={SCORE_COLORS[entry.raw] ?? "var(--color-chart-1)"}
/>
))}
</Bar>
@@ -1,24 +1,26 @@
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Treemap, ResponsiveContainer, Tooltip } from "recharts";
import {
Treemap,
ResponsiveContainer,
Tooltip,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import type { Entry } from '@/types';
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { useLibraryEntries } from "@/stores/useLibraryStore";
import type { Entry } from "@/types";
type Filter = 'all' | 'movies' | 'series';
type Filter = "all" | "movies" | "series";
const TOP_N = 10;
const COLORS = [
'var(--color-chart-1)',
'var(--color-chart-2)',
'var(--color-chart-3)',
'var(--color-chart-4)',
'var(--color-chart-5)',
"var(--color-chart-1)",
"var(--color-chart-2)",
"var(--color-chart-3)",
"var(--color-chart-4)",
"var(--color-chart-5)",
];
function buildGenreData(entries: Entry[]) {
@@ -26,7 +28,7 @@ function buildGenreData(entries: Entry[]) {
for (const entry of entries) {
if (!entry.genres) continue;
for (const genre of entry.genres) {
const name = typeof genre === 'string' ? genre : genre.name;
const name = typeof genre === "string" ? genre : genre.name;
if (!name) continue;
counts[name] = (counts[name] ?? 0) + 1;
}
@@ -34,7 +36,11 @@ function buildGenreData(entries: Entry[]) {
return Object.entries(counts)
.sort((a, b) => b[1] - a[1])
.slice(0, TOP_N)
.map(([genre, count], i) => ({ name: genre, size: count, fill: COLORS[i % COLORS.length] }));
.map(([genre, count], i) => ({
name: genre,
size: count,
fill: COLORS[i % COLORS.length],
}));
}
interface CustomTooltipProps {
@@ -48,16 +54,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
return (
<div
style={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
padding: '8px 12px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
padding: "8px 12px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
>
<p style={{ fontWeight: 600 }}>{name}</p>
<p style={{ color: 'var(--color-muted-foreground)' }}>{size} {size === 1 ? 'title' : 'titles'}</p>
<p style={{ color: "var(--color-muted-foreground)" }}>
{size} {size === 1 ? "title" : "titles"}
</p>
</div>
);
}
@@ -83,7 +91,7 @@ function TreemapContent(props: {
fill={fill}
stroke="var(--color-card)"
strokeWidth={2}
style={{ cursor: 'pointer' }}
style={{ cursor: "pointer" }}
/>
{width > 50 && height > 28 && (
<text
@@ -94,7 +102,7 @@ function TreemapContent(props: {
fill="white"
fontSize={Math.min(12, width / 6)}
fontWeight={500}
style={{ pointerEvents: 'none' }}
style={{ pointerEvents: "none" }}
>
{name}
</text>
@@ -106,17 +114,20 @@ function TreemapContent(props: {
export function TopGenresChart() {
const allEntries = useLibraryEntries();
const navigate = useNavigate();
const [filter, setFilter] = useState<Filter>('all');
const [filter, setFilter] = useState<Filter>("all");
const filteredEntries = useMemo(() => {
// Only count actually watched entries (not watchlist, must be seen)
const watched = allEntries.filter((e) => !e.watchlist && e.date_last_seen);
if (filter === 'movies') return watched.filter((e) => !e.is_tvseries);
if (filter === 'series') return watched.filter((e) => e.is_tvseries);
if (filter === "movies") return watched.filter((e) => !e.is_tvseries);
if (filter === "series") return watched.filter((e) => e.is_tvseries);
return watched;
}, [allEntries, filter]);
const chartData = useMemo(() => buildGenreData(filteredEntries), [filteredEntries]);
const chartData = useMemo(
() => buildGenreData(filteredEntries),
[filteredEntries],
);
const handleClick = (node: { name?: string }) => {
if (node?.name) {
@@ -135,14 +146,14 @@ export function TopGenresChart() {
</CardDescription>
</div>
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
{(['all', 'movies', 'series'] as Filter[]).map((f) => (
{(["all", "movies", "series"] as Filter[]).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 capitalize transition-colors ${
filter === f
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:bg-accent'
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-accent"
}`}
>
{f}
@@ -157,7 +168,16 @@ export function TopGenresChart() {
data={chartData}
dataKey="size"
aspectRatio={4 / 3}
content={<TreemapContent x={0} y={0} width={0} height={0} name="" fill="" />}
content={
<TreemapContent
x={0}
y={0}
width={0}
height={0}
name=""
fill=""
/>
}
onClick={handleClick}
>
<Tooltip content={<CustomTooltip />} />
@@ -1,4 +1,4 @@
import { useState, useMemo } from 'react';
import { useState, useMemo } from "react";
import {
AreaChart,
Area,
@@ -8,14 +8,33 @@ import {
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useYearlyWatchCount } from '@/hooks/useStatistics';
} from "recharts";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useYearlyWatchCount } from "@/hooks/useStatistics";
const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const MONTH_LABELS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
type Filter = 'all' | 'movies' | 'episodes';
type Filter = "all" | "movies" | "episodes";
function buildChartData(
series: { month: number; count: string }[],
@@ -36,7 +55,7 @@ function buildChartData(
export function WatchActivityChart() {
const currentYear = new Date().getFullYear();
const [year, setYear] = useState(currentYear);
const [filter, setFilter] = useState<Filter>('all');
const [filter, setFilter] = useState<Filter>("all");
const { data, isLoading } = useYearlyWatchCount(year);
@@ -47,8 +66,8 @@ export function WatchActivityChart() {
const years = Array.from({ length: 8 }, (_, i) => currentYear - i);
const showMovies = filter === 'all' || filter === 'movies';
const showEpisodes = filter === 'all' || filter === 'episodes';
const showMovies = filter === "all" || filter === "movies";
const showEpisodes = filter === "all" || filter === "episodes";
return (
<Card>
@@ -63,14 +82,14 @@ export function WatchActivityChart() {
<div className="flex items-center gap-2 flex-wrap">
{/* Filter tabs */}
<div className="flex rounded-md border border-border overflow-hidden text-xs">
{(['all', 'movies', 'episodes'] as Filter[]).map((f) => (
{(["all", "movies", "episodes"] as Filter[]).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 capitalize transition-colors ${
filter === f
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:bg-accent'
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-accent"
}`}
>
{f}
@@ -84,7 +103,9 @@ export function WatchActivityChart() {
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
>
{years.map((y) => (
<option key={y} value={y}>{y}</option>
<option key={y} value={y}>
{y}
</option>
))}
</select>
</div>
@@ -95,43 +116,72 @@ export function WatchActivityChart() {
<Skeleton className="h-64 w-full" />
) : (
<ResponsiveContainer width="100%" height={260}>
<AreaChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
<AreaChart
data={chartData}
margin={{ top: 4, right: 8, left: -16, bottom: 0 }}
>
<defs>
<linearGradient id="colorMovies" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--color-chart-1)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--color-chart-1)" stopOpacity={0} />
<stop
offset="5%"
stopColor="var(--color-chart-1)"
stopOpacity={0.3}
/>
<stop
offset="95%"
stopColor="var(--color-chart-1)"
stopOpacity={0}
/>
</linearGradient>
<linearGradient id="colorEpisodes" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--color-chart-2)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--color-chart-2)" stopOpacity={0} />
<stop
offset="5%"
stopColor="var(--color-chart-2)"
stopOpacity={0.3}
/>
<stop
offset="95%"
stopColor="var(--color-chart-2)"
stopOpacity={0}
/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--color-border)"
/>
<XAxis
dataKey="month"
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<YAxis
allowDecimals={false}
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<Tooltip
contentStyle={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
cursor={{ stroke: 'var(--color-border)', strokeWidth: 1 }}
cursor={{ stroke: "var(--color-border)", strokeWidth: 1 }}
/>
<Legend
formatter={(value) => (
<span style={{ fontSize: 12, color: 'var(--color-muted-foreground)' }}>{value}</span>
<span
style={{
fontSize: 12,
color: "var(--color-muted-foreground)",
}}
>
{value}
</span>
)}
/>
{showMovies && (
@@ -142,7 +192,11 @@ export function WatchActivityChart() {
strokeWidth={2}
fill="url(#colorMovies)"
dot={false}
activeDot={{ r: 4, strokeWidth: 0, fill: 'var(--color-chart-1)' }}
activeDot={{
r: 4,
strokeWidth: 0,
fill: "var(--color-chart-1)",
}}
/>
)}
{showEpisodes && (
@@ -153,7 +207,11 @@ export function WatchActivityChart() {
strokeWidth={2}
fill="url(#colorEpisodes)"
dot={false}
activeDot={{ r: 4, strokeWidth: 0, fill: 'var(--color-chart-2)' }}
activeDot={{
r: 4,
strokeWidth: 0,
fill: "var(--color-chart-2)",
}}
/>
)}
</AreaChart>
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useMemo } from "react";
import {
BarChart,
Bar,
@@ -8,12 +8,31 @@ import {
Tooltip,
Legend,
ResponsiveContainer,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useYearlyWatchTime } from '@/hooks/useStatistics';
} from "recharts";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useYearlyWatchTime } from "@/hooks/useStatistics";
const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const MONTH_LABELS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
function minutesToHours(minutes: number) {
return Math.round((minutes / 60) * 10) / 10;
@@ -29,7 +48,7 @@ function buildChartData(
const m = movies.find((x) => Number(x.month) === monthNum);
return {
month: label,
'TV Series': s ? minutesToHours(parseInt(s.watchTime, 10)) : 0,
"TV Series": s ? minutesToHours(parseInt(s.watchTime, 10)) : 0,
Movies: m ? minutesToHours(parseInt(m.watchTime, 10)) : 0,
};
});
@@ -47,12 +66,12 @@ function CustomTooltip({ active, payload, label }: CustomTooltipProps) {
return (
<div
style={{
backgroundColor: 'var(--color-card)',
border: '1px solid var(--color-border)',
borderRadius: '8px',
padding: '10px 14px',
fontSize: '13px',
color: 'var(--color-card-foreground)',
backgroundColor: "var(--color-card)",
border: "1px solid var(--color-border)",
borderRadius: "8px",
padding: "10px 14px",
fontSize: "13px",
color: "var(--color-card-foreground)",
}}
>
<p style={{ fontWeight: 600, marginBottom: 6 }}>{label}</p>
@@ -62,7 +81,14 @@ function CustomTooltip({ active, payload, label }: CustomTooltipProps) {
</p>
))}
{payload.length > 1 && (
<p style={{ color: 'var(--color-muted-foreground)', marginTop: 4, borderTop: '1px solid var(--color-border)', paddingTop: 4 }}>
<p
style={{
color: "var(--color-muted-foreground)",
marginTop: 4,
borderTop: "1px solid var(--color-border)",
paddingTop: 4,
}}
>
Total: {total}h
</p>
)}
@@ -70,7 +96,13 @@ function CustomTooltip({ active, payload, label }: CustomTooltipProps) {
);
}
export function WatchTimeChart({ year, onYearChange }: { year: number; onYearChange: (y: number) => void }) {
export function WatchTimeChart({
year,
onYearChange,
}: {
year: number;
onYearChange: (y: number) => void;
}) {
const currentYear = new Date().getFullYear();
const { data, isLoading } = useYearlyWatchTime(year);
@@ -83,11 +115,20 @@ export function WatchTimeChart({ year, onYearChange }: { year: number; onYearCha
const monthTotal = useMemo(() => {
if (!chartData.length || year !== currentYear) return 0;
const m = chartData[currentMonth];
return m ? Math.round(((m['Movies'] || 0) + (m['TV Series'] || 0)) * 10) / 10 : 0;
return m
? Math.round(((m["Movies"] || 0) + (m["TV Series"] || 0)) * 10) / 10
: 0;
}, [chartData, currentMonth, year, currentYear]);
const yearTotal = useMemo(() => {
return Math.round(chartData.reduce((s, m) => s + (m['Movies'] || 0) + (m['TV Series'] || 0), 0) * 10) / 10;
return (
Math.round(
chartData.reduce(
(s, m) => s + (m["Movies"] || 0) + (m["TV Series"] || 0),
0,
) * 10,
) / 10
);
}, [chartData]);
const years = Array.from({ length: 5 }, (_, i) => currentYear - i);
@@ -119,7 +160,9 @@ export function WatchTimeChart({ year, onYearChange }: { year: number; onYearCha
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
>
{years.map((y) => (
<option key={y} value={y}>{y}</option>
<option key={y} value={y}>
{y}
</option>
))}
</select>
</div>
@@ -130,24 +173,41 @@ export function WatchTimeChart({ year, onYearChange }: { year: number; onYearCha
<Skeleton className="h-56 w-full" />
) : (
<ResponsiveContainer width="100%" height={220}>
<BarChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
<BarChart
data={chartData}
margin={{ top: 4, right: 8, left: -16, bottom: 0 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--color-border)"
vertical={false}
/>
<XAxis
dataKey="month"
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<YAxis
unit="h"
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
axisLine={false}
tickLine={false}
/>
<Tooltip content={<CustomTooltip />} cursor={{ fill: 'var(--color-accent)' }} />
<Tooltip
content={<CustomTooltip />}
cursor={{ fill: "var(--color-accent)" }}
/>
<Legend
formatter={(value) => (
<span style={{ fontSize: 12, color: 'var(--color-muted-foreground)' }}>{value}</span>
<span
style={{
fontSize: 12,
color: "var(--color-muted-foreground)",
}}
>
{value}
</span>
)}
/>
<Bar
@@ -1,21 +1,21 @@
import { useState } from 'react';
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 { Button } from '@/components/ui/button';
import { Plus, Loader2 } from 'lucide-react';
import { useCollections } from '@/hooks/useCollections';
import { useQueryClient } from '@tanstack/react-query';
import { collectionsApi } from '@/api/collections';
import { collectionKeys } from '@/hooks/useCollections';
import { toast } from 'sonner';
import type { Collection } from '@/types';
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Plus, Loader2 } from "lucide-react";
import { useCollections } from "@/hooks/useCollections";
import { useQueryClient } from "@tanstack/react-query";
import { collectionsApi } from "@/api/collections";
import { collectionKeys } from "@/hooks/useCollections";
import { toast } from "sonner";
import type { Collection } from "@/types";
interface AddEntryToCollectionDialogProps {
open: boolean;
@@ -28,20 +28,20 @@ export function AddEntryToCollectionDialog({
onOpenChange,
entryId,
}: AddEntryToCollectionDialogProps) {
const [search, setSearch] = useState('');
const [search, setSearch] = useState("");
const [pending, setPending] = useState<Set<number>>(new Set());
const [creating, setCreating] = useState(false);
const { data: allCollections = [] } = useCollections();
const queryClient = useQueryClient();
const filtered = allCollections.filter((c) =>
c.name.toLowerCase().includes(search.toLowerCase())
c.name.toLowerCase().includes(search.toLowerCase()),
);
const showCreateOption =
search.trim().length > 0 &&
!allCollections.some(
(c) => c.name.toLowerCase() === search.trim().toLowerCase()
(c) => c.name.toLowerCase() === search.trim().toLowerCase(),
);
const isInCollection = (collectionId: number) =>
@@ -61,11 +61,17 @@ export function AddEntryToCollectionDialog({
const entries = col.entries ?? [];
const already = entries.some((e) => e.id === entryId);
if (already) return col;
return { ...col, entries: [...entries, { id: entryId } as Collection['entries'][0]] };
return {
...col,
entries: [...entries, { id: entryId } as Collection["entries"][0]],
};
} else {
return { ...col, entries: (col.entries ?? []).filter((e) => e.id !== entryId) };
return {
...col,
entries: (col.entries ?? []).filter((e) => e.id !== entryId),
};
}
})
}),
);
try {
@@ -90,13 +96,16 @@ export function AddEntryToCollectionDialog({
if (!name) return;
setCreating(true);
try {
const newCollection = await collectionsApi.create({ name, is_user_collection: true } as Partial<Collection>);
const newCollection = await collectionsApi.create({
name,
is_user_collection: true,
} as Partial<Collection>);
await collectionsApi.addEntry(newCollection.id, entryId);
await queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success(`Created "${name}" and added entry`);
setSearch('');
setSearch("");
} catch {
toast.error('Failed to create collection');
toast.error("Failed to create collection");
} finally {
setCreating(false);
}
@@ -1,19 +1,19 @@
import { useState, useRef } from 'react';
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 { StarRating } from '@/components/ui/star-rating';
import { useUpdateCollection } from '@/hooks/useCollections';
import type { Collection } from '@/types';
} 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 { StarRating } from "@/components/ui/star-rating";
import { useUpdateCollection } from "@/hooks/useCollections";
import type { Collection } from "@/types";
interface CollectionEditDialogProps {
open: boolean;
@@ -27,10 +27,8 @@ export function CollectionEditDialog({
collection,
}: CollectionEditDialogProps) {
const [name, setName] = useState(collection.name);
const [description, setDescription] = useState(collection.description || '');
const [userRating, setUserRating] = useState(
collection.user_rating ?? 0
);
const [description, setDescription] = useState(collection.description || "");
const [userRating, setUserRating] = useState(collection.user_rating ?? 0);
const [posterFile, setPosterFile] = useState<File | null>(null);
const [backdropFile, setBackdropFile] = useState<File | null>(null);
const [posterPreview, setPosterPreview] = useState<string | null>(null);
@@ -61,20 +59,20 @@ export function CollectionEditDialog({
e.preventDefault();
const formData = new FormData();
formData.append('name', name);
formData.append('description', description);
formData.append('userRating', String(userRating || 0));
formData.append("name", name);
formData.append("description", description);
formData.append("userRating", String(userRating || 0));
if (posterFile) {
formData.append('poster', posterFile);
formData.append("poster", posterFile);
}
if (backdropFile) {
formData.append('backdrop', backdropFile);
formData.append("backdrop", backdropFile);
}
updateCollection.mutate(
{ id: collection.id, data: formData },
{ onSuccess: () => onOpenChange(false) }
{ onSuccess: () => onOpenChange(false) },
);
};
@@ -108,9 +106,13 @@ export function CollectionEditDialog({
<div className="space-y-2">
<Label>User Rating</Label>
<div className="flex items-center gap-3">
<StarRating value={userRating} onChange={setUserRating} size="md" />
<StarRating
value={userRating}
onChange={setUserRating}
size="md"
/>
<span className="text-sm text-muted-foreground tabular-nums">
{userRating > 0 ? `${userRating}/10` : '—'}
{userRating > 0 ? `${userRating}/10` : "—"}
</span>
</div>
</div>
@@ -191,7 +193,7 @@ export function CollectionEditDialog({
Cancel
</Button>
<Button type="submit" disabled={updateCollection.isPending}>
{updateCollection.isPending ? 'Saving...' : 'Save'}
{updateCollection.isPending ? "Saving..." : "Save"}
</Button>
</DialogFooter>
</form>
@@ -5,9 +5,9 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
interface ConfirmDialogProps {
open: boolean;
@@ -17,7 +17,7 @@ interface ConfirmDialogProps {
confirmLabel?: string;
cancelLabel?: string;
onConfirm: () => void;
variant?: 'default' | 'destructive';
variant?: "default" | "destructive";
isLoading?: boolean;
}
@@ -26,10 +26,10 @@ export function ConfirmDialog({
onOpenChange,
title,
description,
confirmLabel = 'Confirm',
cancelLabel = 'Cancel',
confirmLabel = "Confirm",
cancelLabel = "Cancel",
onConfirm,
variant = 'default',
variant = "default",
isLoading = false,
}: ConfirmDialogProps) {
return (
@@ -40,11 +40,15 @@ export function ConfirmDialog({
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isLoading}>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
{cancelLabel}
</Button>
<Button
variant={variant === 'destructive' ? 'destructive' : 'default'}
variant={variant === "destructive" ? "destructive" : "default"}
onClick={onConfirm}
disabled={isLoading}
>
@@ -1,19 +1,19 @@
import { useState } from 'react';
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';
} 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;
@@ -28,15 +28,15 @@ export function EntryMediaDialog({
entryId,
medias,
}: EntryMediaDialogProps) {
const [activeTab, setActiveTab] = useState<string>('poster');
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/*';
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;
@@ -93,16 +93,16 @@ export function EntryMediaDialog({
key={media.id}
className={`group relative overflow-hidden rounded-lg border-2 ${
media.is_selected
? 'border-primary'
: 'border-transparent'
? "border-primary"
: "border-transparent"
}`}
>
<img
src={getMediaUrl(
'entries',
"entries",
`${activeTab}s`,
'preview',
media.path
"preview",
media.path,
)}
alt={activeTab}
className="w-full object-cover"
@@ -1,36 +1,36 @@
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 { Loader2 } from 'lucide-react';
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 { Loader2 } 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';
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useCreateEntrySeen, useUpdateEntrySeen } from '@/hooks/useEntrySeen';
import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen';
import type { Entry, Season, EntrySeen, SeenAccuracy } from '@/types';
} from "@/components/ui/select";
import { useCreateEntrySeen, useUpdateEntrySeen } from "@/hooks/useEntrySeen";
import { useCreateEpisodeSeen } from "@/hooks/useEpisodeSeen";
import type { Entry, Season, EntrySeen, SeenAccuracy } from "@/types";
const seenSchema = z.object({
season_id: z.string().optional(),
episode_id: z.string().optional(),
date_seen: z.string().min(1, 'Date is required'),
date_seen: z.string().min(1, "Date is required"),
seen_with: z.string().optional(),
accuracy: z.enum(['EXACT', 'ESTIMATED', 'UNKNOWN']).default('EXACT'),
accuracy: z.enum(["EXACT", "ESTIMATED", "UNKNOWN"]).default("EXACT"),
});
interface EntrySeenDialogProps {
@@ -38,7 +38,7 @@ interface EntrySeenDialogProps {
onOpenChange: (open: boolean) => void;
entry: Entry;
seasons?: Season[];
mode: 'add' | 'edit';
mode: "add" | "edit";
editRecord?: EntrySeen;
}
@@ -50,7 +50,7 @@ export function EntrySeenDialog({
mode,
editRecord,
}: EntrySeenDialogProps) {
const [selectedSeasonId, setSelectedSeasonId] = useState<string>('');
const [selectedSeasonId, setSelectedSeasonId] = useState<string>("");
const isTV = entry.is_tvseries;
const seasonList = Array.isArray(seasons) ? seasons : [];
@@ -64,26 +64,26 @@ export function EntrySeenDialog({
} = useForm({
resolver: zodResolver(seenSchema),
defaultValues: {
date_seen: editRecord?.date_seen || format(new Date(), 'yyyy-MM-dd'),
seen_with: editRecord?.seen_with || '',
season_id: '',
episode_id: '',
accuracy: (editRecord?.accuracy || 'EXACT') as SeenAccuracy,
date_seen: editRecord?.date_seen || format(new Date(), "yyyy-MM-dd"),
seen_with: editRecord?.seen_with || "",
season_id: "",
episode_id: "",
accuracy: (editRecord?.accuracy || "EXACT") as SeenAccuracy,
},
});
const accuracyValue = watch('accuracy') as SeenAccuracy;
const accuracyValue = watch("accuracy") as SeenAccuracy;
const createEntrySeen = useCreateEntrySeen();
const updateEntrySeen = useUpdateEntrySeen();
const createEpisodeSeen = useCreateEpisodeSeen();
const selectedSeason = seasonList.find(
(s) => s.id.toString() === selectedSeasonId
(s) => s.id.toString() === selectedSeasonId,
);
const onSubmit = (data: Record<string, string | undefined>) => {
const acc = (data.accuracy as SeenAccuracy) || 'EXACT';
const acc = (data.accuracy as SeenAccuracy) || "EXACT";
if (isTV && data.episode_id) {
createEpisodeSeen.mutate(
{
@@ -93,9 +93,9 @@ export function EntrySeenDialog({
seen_with: data.seen_with || undefined,
accuracy: acc,
},
{ onSuccess: () => onOpenChange(false) }
{ onSuccess: () => onOpenChange(false) },
);
} else if (mode === 'edit' && editRecord) {
} else if (mode === "edit" && editRecord) {
updateEntrySeen.mutate(
{
id: editRecord.id,
@@ -106,7 +106,7 @@ export function EntrySeenDialog({
accuracy: acc,
},
},
{ onSuccess: () => onOpenChange(false) }
{ onSuccess: () => onOpenChange(false) },
);
} else {
createEntrySeen.mutate(
@@ -116,7 +116,7 @@ export function EntrySeenDialog({
seen_with: data.seen_with || undefined,
accuracy: acc,
},
{ onSuccess: () => onOpenChange(false) }
{ onSuccess: () => onOpenChange(false) },
);
}
};
@@ -126,7 +126,7 @@ export function EntrySeenDialog({
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{mode === 'edit' ? 'Edit Watch Record' : 'Mark as Watched'}
{mode === "edit" ? "Edit Watch Record" : "Mark as Watched"}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
@@ -139,8 +139,8 @@ export function EntrySeenDialog({
value={selectedSeasonId}
onValueChange={(v) => {
setSelectedSeasonId(v);
setValue('season_id', v);
setValue('episode_id', '');
setValue("season_id", v);
setValue("episode_id", "");
}}
>
<SelectTrigger>
@@ -164,7 +164,7 @@ export function EntrySeenDialog({
{selectedSeason?.episodes && (
<div className="space-y-2">
<Label>Episode</Label>
<Select onValueChange={(v) => setValue('episode_id', v)}>
<Select onValueChange={(v) => setValue("episode_id", v)}>
<SelectTrigger>
<SelectValue placeholder="Select episode" />
</SelectTrigger>
@@ -192,16 +192,18 @@ export function EntrySeenDialog({
<div className="flex items-center gap-2">
<Input
type="date"
value={watch('date_seen')}
value={watch("date_seen")}
onChange={(e) => {
setValue('date_seen', e.target.value);
setDate(e.target.value ? new Date(e.target.value) : undefined);
setValue("date_seen", e.target.value);
setDate(
e.target.value ? new Date(e.target.value) : undefined,
);
}}
className="flex-1"
/>
<Select
value={accuracyValue}
onValueChange={(v) => setValue('accuracy', v as SeenAccuracy)}
onValueChange={(v) => setValue("accuracy", v as SeenAccuracy)}
>
<SelectTrigger className="w-[120px] shrink-0">
<SelectValue />
@@ -223,7 +225,11 @@ export function EntrySeenDialog({
{/* 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" />
<Input
id="seen_with"
{...register("seen_with")}
placeholder="e.g. John, Jane"
/>
</div>
<DialogFooter>
@@ -231,18 +237,28 @@ export function EntrySeenDialog({
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={createEntrySeen.isPending || updateEntrySeen.isPending || createEpisodeSeen.isPending}
disabled={
createEntrySeen.isPending ||
updateEntrySeen.isPending ||
createEpisodeSeen.isPending
}
>
Cancel
</Button>
<Button
type="submit"
disabled={createEntrySeen.isPending || updateEntrySeen.isPending || createEpisodeSeen.isPending}
disabled={
createEntrySeen.isPending ||
updateEntrySeen.isPending ||
createEpisodeSeen.isPending
}
>
{(createEntrySeen.isPending || updateEntrySeen.isPending || createEpisodeSeen.isPending) && (
{(createEntrySeen.isPending ||
updateEntrySeen.isPending ||
createEpisodeSeen.isPending) && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
{mode === 'edit' ? 'Save Changes' : 'Mark as Watched'}
{mode === "edit" ? "Save Changes" : "Mark as Watched"}
</Button>
</DialogFooter>
</form>
@@ -3,13 +3,13 @@ import {
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { useUpdateEntry, useUpdateEntryRatings } from '@/hooks/useEntries';
import { StarRating } from '@/components/ui/star-rating';
import type { Entry } from '@/types';
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import { useUpdateEntry, useUpdateEntryRatings } from "@/hooks/useEntries";
import { StarRating } from "@/components/ui/star-rating";
import type { Entry } from "@/types";
interface EntrySettingsDialogProps {
open: boolean;
@@ -30,11 +30,11 @@ export function EntrySettingsDialog({
};
const boolSettings = [
{ field: 'favorit' as const, label: 'Favorite' },
{ field: 'hidden' as const, label: 'Hidden' },
{ field: 'watchlist' as const, label: 'Watchlist' },
{ field: 'show_in_calendar' as const, label: 'Show in Calendar' },
{ field: 'auto_sync' as const, label: 'Auto Sync' },
{ field: "favorit" as const, label: "Favorite" },
{ field: "hidden" as const, label: "Hidden" },
{ field: "watchlist" as const, label: "Watchlist" },
{ field: "show_in_calendar" as const, label: "Show in Calendar" },
{ field: "auto_sync" as const, label: "Auto Sync" },
];
const userRating = entry.entryRatings?.user_rating ?? 0;
@@ -51,11 +51,16 @@ export function EntrySettingsDialog({
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Entry Settings</DialogTitle>
<p className="text-sm text-muted-foreground line-clamp-1">{entry.title}</p>
<p className="text-sm text-muted-foreground line-clamp-1">
{entry.title}
</p>
</DialogHeader>
<div className="space-y-1 py-2">
{boolSettings.map(({ field, label }) => (
<div key={field} className="flex items-center justify-between rounded-lg px-1 py-2.5">
<div
key={field}
className="flex items-center justify-between rounded-lg px-1 py-2.5"
>
<Label htmlFor={field} className="cursor-pointer">
{label}
</Label>
@@ -70,9 +75,13 @@ export function EntrySettingsDialog({
<div className="space-y-2 rounded-lg px-1 py-2.5">
<Label>Your Rating</Label>
<div className="flex items-center gap-3">
<StarRating value={userRating} onChange={handleRatingChange} size="sm" />
<StarRating
value={userRating}
onChange={handleRatingChange}
size="sm"
/>
<span className="text-sm text-muted-foreground tabular-nums">
{userRating > 0 ? `${userRating}/10` : '—'}
{userRating > 0 ? `${userRating}/10` : "—"}
</span>
</div>
</div>
@@ -1,23 +1,26 @@
import { useState } from 'react';
import { useState } 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';
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useUpdateEpisodeSeen, useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen';
import type { EpisodeSeen, SeenAccuracy } from '@/types';
} from "@/components/ui/select";
import {
useUpdateEpisodeSeen,
useCreateEpisodeSeen,
} from "@/hooks/useEpisodeSeen";
import type { EpisodeSeen, SeenAccuracy } from "@/types";
interface EpisodeSeenEditDialogProps {
open: boolean;
@@ -28,9 +31,13 @@ interface EpisodeSeenEditDialogProps {
episodeId?: number;
entryId: number;
seasonId?: number;
mode?: 'create' | 'edit';
mode?: "create" | "edit";
/** If provided, called instead of the normal create/update mutation */
overrideSubmit?: (date: string, seenWith: string, accuracy: SeenAccuracy) => void;
overrideSubmit?: (
date: string,
seenWith: string,
accuracy: SeenAccuracy,
) => void;
}
export function EpisodeSeenEditDialog({
@@ -40,13 +47,15 @@ export function EpisodeSeenEditDialog({
episodeId,
entryId,
seasonId,
mode = record ? 'edit' : 'create',
mode = record ? "edit" : "create",
overrideSubmit,
}: EpisodeSeenEditDialogProps) {
const today = new Date().toISOString().split('T')[0];
const [date, setDate] = useState(record?.date_seen?.split('T')[0] ?? today);
const [seenWith, setSeenWith] = useState(record?.seen_with ?? '');
const [accuracy, setAccuracy] = useState<SeenAccuracy>(record?.accuracy ?? 'EXACT');
const today = new Date().toISOString().split("T")[0];
const [date, setDate] = useState(record?.date_seen?.split("T")[0] ?? today);
const [seenWith, setSeenWith] = useState(record?.seen_with ?? "");
const [accuracy, setAccuracy] = useState<SeenAccuracy>(
record?.accuracy ?? "EXACT",
);
const updateEpisodeSeen = useUpdateEpisodeSeen();
const createEpisodeSeen = useCreateEpisodeSeen();
@@ -56,7 +65,7 @@ export function EpisodeSeenEditDialog({
overrideSubmit(date, seenWith, accuracy);
return;
}
if (mode === 'edit' && record) {
if (mode === "edit" && record) {
updateEpisodeSeen.mutate({
id: record.id,
data: {
@@ -86,7 +95,9 @@ export function EpisodeSeenEditDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>{mode === 'edit' ? 'Edit Watch Record' : 'Mark as Watched'}</DialogTitle>
<DialogTitle>
{mode === "edit" ? "Edit Watch Record" : "Mark as Watched"}
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-1.5">
@@ -99,7 +110,10 @@ export function EpisodeSeenEditDialog({
onChange={(e) => setDate(e.target.value)}
className="flex-1"
/>
<Select value={accuracy} onValueChange={(v) => setAccuracy(v as SeenAccuracy)}>
<Select
value={accuracy}
onValueChange={(v) => setAccuracy(v as SeenAccuracy)}
>
<SelectTrigger className="w-[120px] shrink-0">
<SelectValue />
</SelectTrigger>
@@ -122,9 +136,11 @@ export function EpisodeSeenEditDialog({
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={!date}>
{mode === 'edit' ? 'Save' : 'Add'}
{mode === "edit" ? "Save" : "Add"}
</Button>
</DialogFooter>
</DialogContent>
@@ -1,4 +1,4 @@
import { useState, useMemo } from 'react';
import { useState, useMemo } from "react";
import {
Dialog,
DialogContent,
@@ -6,21 +6,21 @@ import {
DialogHeader,
DialogTitle,
DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, CalendarRange, CalendarDays } from 'lucide-react';
import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen';
import type { Episode, SeenAccuracy } from '@/types';
} from "@/components/ui/select";
import { Loader2, CalendarRange, CalendarDays } from "lucide-react";
import { useCreateEpisodeSeen } from "@/hooks/useEpisodeSeen";
import type { Episode, SeenAccuracy } from "@/types";
interface MarkSeasonWatchedDialogProps {
open: boolean;
@@ -30,7 +30,7 @@ interface MarkSeasonWatchedDialogProps {
episodes: Episode[];
}
type Mode = 'single' | 'scatter';
type Mode = "single" | "scatter";
function addDays(date: Date, days: number): Date {
const result = new Date(date);
@@ -39,7 +39,7 @@ function addDays(date: Date, days: number): Date {
}
function toDateStr(date: Date): string {
return date.toISOString().split('T')[0];
return date.toISOString().split("T")[0];
}
/**
@@ -79,18 +79,18 @@ export function MarkSeasonWatchedDialog({
seasonId,
episodes,
}: MarkSeasonWatchedDialogProps) {
const today = new Date().toISOString().split('T')[0];
const today = new Date().toISOString().split("T")[0];
const createEpisodeSeen = useCreateEpisodeSeen();
// Shared fields
const [seenWith, setSeenWith] = useState('');
const [accuracy, setAccuracy] = useState<SeenAccuracy>('EXACT');
const [seenWith, setSeenWith] = useState("");
const [accuracy, setAccuracy] = useState<SeenAccuracy>("EXACT");
// Single-date mode
const [singleDate, setSingleDate] = useState(today);
// Scatter mode
const [mode, setMode] = useState<Mode>('single');
const [mode, setMode] = useState<Mode>("single");
const [startDate, setStartDate] = useState(today);
const [endDate, setEndDate] = useState(today);
@@ -107,7 +107,7 @@ export function MarkSeasonWatchedDialog({
);
const scatterPreview = useMemo(() => {
if (mode !== 'scatter' || !startDate || !endDate) return null;
if (mode !== "scatter" || !startDate || !endDate) return null;
const start = new Date(startDate);
const end = new Date(endDate);
if (end < start) return null;
@@ -131,7 +131,7 @@ export function MarkSeasonWatchedDialog({
setIsSubmitting(true);
try {
if (mode === 'single') {
if (mode === "single") {
for (const ep of unwatched) {
await createEpisodeSeen.mutateAsync({
entry_id: entryId,
@@ -171,7 +171,8 @@ export function MarkSeasonWatchedDialog({
<DialogHeader>
<DialogTitle>Mark Season as Watched</DialogTitle>
<DialogDescription>
{unwatched.length} unwatched episode{unwatched.length !== 1 ? 's' : ''} will be marked as seen.
{unwatched.length} unwatched episode
{unwatched.length !== 1 ? "s" : ""} will be marked as seen.
</DialogDescription>
</DialogHeader>
@@ -179,25 +180,25 @@ export function MarkSeasonWatchedDialog({
{/* Mode toggle */}
<div className="flex items-center justify-between rounded-lg border border-border p-3">
<div className="flex items-center gap-2">
{mode === 'single' ? (
{mode === "single" ? (
<CalendarDays className="h-4 w-4 text-muted-foreground" />
) : (
<CalendarRange className="h-4 w-4 text-muted-foreground" />
)}
<span className="text-sm font-medium">
{mode === 'single' ? 'Single Date' : 'Scatter Mode'}
{mode === "single" ? "Single Date" : "Scatter Mode"}
</span>
</div>
<Switch
checked={mode === 'scatter'}
checked={mode === "scatter"}
onCheckedChange={(checked) =>
setMode(checked ? 'scatter' : 'single')
setMode(checked ? "scatter" : "single")
}
/>
</div>
{/* Date inputs */}
{mode === 'single' ? (
{mode === "single" ? (
<div className="space-y-1.5">
<Label htmlFor="single-date">Date Watched</Label>
<Input
@@ -234,19 +235,24 @@ export function MarkSeasonWatchedDialog({
{scatterPreview && (
<div className="rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground space-y-0.5">
<p>
{unwatched.length} episodes across {scatterPreview.totalDays} day{scatterPreview.totalDays !== 1 ? 's' : ''}
{unwatched.length} episodes across{" "}
{scatterPreview.totalDays} day
{scatterPreview.totalDays !== 1 ? "s" : ""}
</p>
<p>
~{scatterPreview.maxPerDay} episode{scatterPreview.maxPerDay !== 1 ? 's' : ''}/day max
~{scatterPreview.maxPerDay} episode
{scatterPreview.maxPerDay !== 1 ? "s" : ""}/day max
</p>
</div>
)}
{startDate && endDate && new Date(endDate) < new Date(startDate) && (
<p className="text-xs text-destructive">
End date must be after start date.
</p>
)}
{startDate &&
endDate &&
new Date(endDate) < new Date(startDate) && (
<p className="text-xs text-destructive">
End date must be after start date.
</p>
)}
</div>
)}
@@ -293,19 +299,17 @@ export function MarkSeasonWatchedDialog({
disabled={
isSubmitting ||
unwatched.length === 0 ||
(mode === 'single' && !singleDate) ||
(mode === 'scatter' &&
(mode === "single" && !singleDate) ||
(mode === "scatter" &&
(!startDate ||
!endDate ||
new Date(endDate) < new Date(startDate)))
}
>
{isSubmitting && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isSubmitting
? 'Marking...'
: `Mark ${unwatched.length} Episode${unwatched.length !== 1 ? 's' : ''}`}
? "Marking..."
: `Mark ${unwatched.length} Episode${unwatched.length !== 1 ? "s" : ""}`}
</Button>
</DialogFooter>
</DialogContent>
@@ -1,13 +1,13 @@
import { format } from 'date-fns';
import { format } from "date-fns";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Trash2 } from 'lucide-react';
import type { EntrySeen } from '@/types';
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Trash2 } from "lucide-react";
import type { EntrySeen } from "@/types";
interface MovieWatchHistoryDialogProps {
open: boolean;
@@ -51,11 +51,11 @@ export function MovieWatchHistoryDialog({
>
<td className="px-4 py-2">
{record.date_seen
? format(new Date(record.date_seen), 'MMM d, yyyy')
: '-'}
? format(new Date(record.date_seen), "MMM d, yyyy")
: "-"}
</td>
<td className="px-4 py-2 text-muted-foreground">
{record.seen_with || '-'}
{record.seen_with || "-"}
</td>
<td className="px-4 py-2">
<div className="flex justify-end">
@@ -1,14 +1,14 @@
import { useState, useEffect } from 'react';
import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { StarRating } from '@/components/ui/star-rating';
import { useUpdateEntryRatings } from '@/hooks/useEntries';
import type { Entry } from '@/types';
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { StarRating } from "@/components/ui/star-rating";
import { useUpdateEntryRatings } from "@/hooks/useEntries";
import type { Entry } from "@/types";
interface RatingDialogProps {
open: boolean;
@@ -48,14 +48,16 @@ export function RatingDialog({ open, onOpenChange, entry }: RatingDialogProps) {
<DialogContent className="w-auto sm:max-w-none">
<DialogHeader>
<DialogTitle>Rate</DialogTitle>
<p className="text-sm text-muted-foreground line-clamp-1">{entry.title}</p>
<p className="text-sm text-muted-foreground line-clamp-1">
{entry.title}
</p>
</DialogHeader>
<div className="flex flex-col items-center gap-4 py-2">
<StarRating value={selected} onChange={handleRate} size="lg" />
<p className="text-xl font-semibold tabular-nums">
{selected > 0 ? `${selected} / 10` : '—'}
{selected > 0 ? `${selected} / 10` : "—"}
</p>
{(selected > 0 || currentRating > 0) && (
@@ -1,7 +1,7 @@
import { format } from 'date-fns';
import type { EntrySeen, EpisodeSeen } from '@/types';
import { Button } from '@/components/ui/button';
import { Pencil, Trash2 } from 'lucide-react';
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)[];
@@ -40,11 +40,11 @@ export function EpisodeWatchHistory({
>
<td className="px-4 py-2">
{record.date_seen
? format(new Date(record.date_seen), 'MMM d, yyyy')
: '-'}
? format(new Date(record.date_seen), "MMM d, yyyy")
: "-"}
</td>
<td className="px-4 py-2 text-muted-foreground">
{record.seen_with || '-'}
{record.seen_with || "-"}
</td>
<td className="px-4 py-2">
<div className="flex justify-end gap-1">
@@ -1,21 +1,18 @@
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 { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog';
import { getYear, getTmdbPosterUrl } from '@/lib/media-utils';
import type { Season } from '@/types';
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 { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { getYear, getTmdbPosterUrl } from "@/lib/media-utils";
import type { Season } from "@/types";
interface SeasonsContainerProps {
seasons: Season[];
entryId: number;
}
export function SeasonsContainer({
seasons,
entryId,
}: SeasonsContainerProps) {
export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
const [expanded, setExpanded] = useState(false);
// Sort: specials (season 0) at bottom, rest latest to oldest
@@ -48,8 +45,8 @@ export function SeasonsContainer({
</>
) : (
<>
<ChevronDown className="mr-1 h-4 w-4" /> Show All (
{sorted.length})
<ChevronDown className="mr-1 h-4 w-4" /> Show All ({sorted.length}
)
</>
)}
</Button>
@@ -58,17 +55,12 @@ export function SeasonsContainer({
);
}
function SeasonItem({
season,
entryId,
}: {
season: Season;
entryId: number;
}) {
function SeasonItem({ season, entryId }: { season: Season; entryId: number }) {
const [dialogOpen, setDialogOpen] = useState(false);
const watchedCount =
season.episodes?.filter(
(ep) => ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0)
(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;
@@ -76,7 +68,11 @@ function SeasonItem({
const nextUnwatched = season.episodes
?.slice()
.sort((a, b) => a.episode_number - b.episode_number)
.find((ep) => !ep.date_first_seen && (!ep.episodeSeens || ep.episodeSeens.length === 0));
.find(
(ep) =>
!ep.date_first_seen &&
(!ep.episodeSeens || ep.episodeSeens.length === 0),
);
return (
<>
@@ -87,7 +83,7 @@ function SeasonItem({
{/* Poster thumbnail */}
<div className="h-16 w-11 shrink-0 overflow-hidden rounded bg-muted">
<img
src={getTmdbPosterUrl(season.poster_path, 'w92')}
src={getTmdbPosterUrl(season.poster_path, "w92")}
alt={season.name}
className="h-full w-full object-cover"
loading="lazy"
@@ -1,10 +1,10 @@
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';
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;
@@ -22,8 +22,8 @@ export function TrendingGrid({
isLoading,
category,
}: TrendingGridProps) {
const [activeTab, setActiveTab] = useState<'movie' | 'tv'>('movie');
const entries = activeTab === 'movie' ? movieEntries : tvEntries;
const [activeTab, setActiveTab] = useState<"movie" | "tv">("movie");
const entries = activeTab === "movie" ? movieEntries : tvEntries;
const displayEntries = entries.slice(0, 14);
return (
@@ -33,7 +33,7 @@ export function TrendingGrid({
<div className="flex items-center gap-3">
<Tabs
value={activeTab}
onValueChange={(v) => setActiveTab(v as 'movie' | 'tv')}
onValueChange={(v) => setActiveTab(v as "movie" | "tv")}
>
<TabsList className="h-8">
<TabsTrigger value="movie" className="text-xs px-3">
@@ -1,10 +1,10 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { Link } from 'react-router-dom';
import { ChevronLeft, ChevronRight, Star } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useCreateEntry } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import type { TmdbEntry } from '@/types';
import { useState, useEffect, useCallback, useRef } from "react";
import { Link } from "react-router-dom";
import { ChevronLeft, ChevronRight, Star } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useCreateEntry } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import type { TmdbEntry } from "@/types";
interface TrendingSliderProps {
entries: TmdbEntry[];
@@ -48,14 +48,14 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) {
const safeIndex = currentIndex < display.length ? currentIndex : 0;
const item = display[safeIndex];
const title = item.title || item.name || 'Untitled';
const title = item.title || item.name || "Untitled";
const backdropUrl = item.backdrop_path
? `https://image.tmdb.org/t/p/w1280${item.backdrop_path}`
: null;
const isTv = item.media_type === 'tv' || !!item.name;
const isTv = item.media_type === "tv" || !!item.name;
const matchedEntry = Array.from(libraryEntries.values()).find(
(e) => e.entryIds?.tmdb_id === item.id
(e) => e.entryIds?.tmdb_id === item.id,
);
const isInLibrary = !!matchedEntry;
@@ -77,14 +77,20 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) {
<button
type="button"
className="absolute left-3 top-1/2 -translate-y-1/2 z-20 h-10 w-10 rounded-full bg-black/40 text-white hover:bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer"
onClick={(e) => { e.stopPropagation(); prev(); }}
onClick={(e) => {
e.stopPropagation();
prev();
}}
>
<ChevronLeft className="h-5 w-5" />
</button>
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 z-20 h-10 w-10 rounded-full bg-black/40 text-white hover:bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer"
onClick={(e) => { e.stopPropagation(); next(); }}
onClick={(e) => {
e.stopPropagation();
next();
}}
>
<ChevronRight className="h-5 w-5" />
</button>
@@ -94,7 +100,7 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) {
<div className="max-w-2xl space-y-3">
<div className="flex items-center gap-2 text-white/70 text-sm">
<span className="uppercase font-medium tracking-wider text-xs bg-white/20 backdrop-blur-sm px-2 py-0.5 rounded">
{isTv ? 'TV Series' : 'Movie'}
{isTv ? "TV Series" : "Movie"}
</span>
{item.vote_average > 0 && (
<span className="flex items-center gap-1">
@@ -122,7 +128,9 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) {
<Button
size="sm"
className="rounded-full px-5"
onClick={() => createEntry.mutate({ tmdb_id: item.id, is_tvserie: isTv })}
onClick={() =>
createEntry.mutate({ tmdb_id: item.id, is_tvserie: isTv })
}
disabled={createEntry.isPending}
>
Add to Library
@@ -140,8 +148,8 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) {
onClick={() => setCurrentIndex(i)}
className={`h-1.5 rounded-full transition-all ${
i === currentIndex
? 'w-6 bg-white'
: 'w-1.5 bg-white/40 hover:bg-white/60'
? "w-6 bg-white"
: "w-1.5 bg-white/40 hover:bg-white/60"
}`}
/>
))}
@@ -1,10 +1,17 @@
import { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useCreateEntry } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { Button } from '@/components/ui/button';
import { Star, Plus, Play, Search, ChevronLeft, ChevronRight } from 'lucide-react';
import type { TmdbEntry } from '@/types';
import { useState, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useCreateEntry } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { Button } from "@/components/ui/button";
import {
Star,
Plus,
Play,
Search,
ChevronLeft,
ChevronRight,
} from "lucide-react";
import type { TmdbEntry } from "@/types";
interface HeroSliderProps {
entries: TmdbEntry[];
@@ -13,7 +20,7 @@ interface HeroSliderProps {
export function HeroSlider({ entries }: HeroSliderProps) {
const navigate = useNavigate();
const [activeIndex, setActiveIndex] = useState(0);
const [searchInput, setSearchInput] = useState('');
const [searchInput, setSearchInput] = useState("");
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const createEntry = useCreateEntry();
const libraryEntries = useLibraryStore((s) => s.entries);
@@ -51,7 +58,7 @@ export function HeroSlider({ entries }: HeroSliderProps) {
return (
<div
className="relative w-full overflow-hidden"
style={{ aspectRatio: '16/9', maxHeight: '70vh' }}
style={{ aspectRatio: "16/9", maxHeight: "70vh" }}
>
{/* Slide track */}
<div
@@ -62,11 +69,11 @@ export function HeroSlider({ entries }: HeroSliderProps) {
}}
>
{slides.map((entry) => {
const title = entry.title || entry.name || 'Untitled';
const title = entry.title || entry.name || "Untitled";
const backdrop = entry.backdrop_path
? `https://image.tmdb.org/t/p/original${entry.backdrop_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const isTv = entry.media_type === "tv" || !!entry.name;
const matchedEntry = Array.from(libraryEntries.values()).find(
(e) => e.entryIds?.tmdb_id === entry.id,
);
@@ -91,7 +98,7 @@ export function HeroSlider({ entries }: HeroSliderProps) {
<div className="absolute bottom-0 left-0 right-0 z-10 space-y-2 px-4 pb-5 md:px-6 md:pb-8">
<div className="flex items-center gap-2">
<span className="rounded-full bg-white/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-white/60 backdrop-blur-sm">
{isTv ? 'Series' : 'Movie'}
{isTv ? "Series" : "Movie"}
</span>
{entry.vote_average > 0 && (
<span className="flex items-center gap-1 text-xs text-yellow-400">
@@ -111,7 +118,11 @@ export function HeroSlider({ entries }: HeroSliderProps) {
<div className="flex gap-2 pt-1">
{matchedEntry ? (
<Link to={`/entry/${matchedEntry.id}`}>
<Button size="sm" variant="secondary" className="rounded-full gap-1.5 text-xs">
<Button
size="sm"
variant="secondary"
className="rounded-full gap-1.5 text-xs"
>
<Play className="h-3 w-3 fill-current" />
Details
</Button>
@@ -121,7 +132,12 @@ export function HeroSlider({ entries }: HeroSliderProps) {
size="sm"
variant="secondary"
className="rounded-full gap-1.5 text-xs"
onClick={() => createEntry.mutate({ tmdb_id: entry.id, is_tvserie: isTv })}
onClick={() =>
createEntry.mutate({
tmdb_id: entry.id,
is_tvserie: isTv,
})
}
disabled={createEntry.isPending}
>
<Plus className="h-3 w-3" />
@@ -144,7 +160,7 @@ export function HeroSlider({ entries }: HeroSliderProps) {
placeholder="Search movies, TV shows..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
className="w-full rounded-full border border-white/20 bg-black/40 py-2.5 pl-9 pr-4 text-sm text-white backdrop-blur-md placeholder-white/50 transition-colors focus:border-white/50 focus:outline-none"
/>
</div>
@@ -153,7 +169,10 @@ export function HeroSlider({ entries }: HeroSliderProps) {
{/* Left arrow */}
<button
className="absolute left-3 top-1/2 z-20 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/30 text-white backdrop-blur-sm transition-colors hover:bg-black/60"
onClick={() => { go(activeIndex - 1); startAutoplay(); }}
onClick={() => {
go(activeIndex - 1);
startAutoplay();
}}
aria-label="Previous"
>
<ChevronLeft className="h-5 w-5" />
@@ -162,7 +181,10 @@ export function HeroSlider({ entries }: HeroSliderProps) {
{/* Right arrow */}
<button
className="absolute right-3 top-1/2 z-20 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/30 text-white backdrop-blur-sm transition-colors hover:bg-black/60"
onClick={() => { go(activeIndex + 1); startAutoplay(); }}
onClick={() => {
go(activeIndex + 1);
startAutoplay();
}}
aria-label="Next"
>
<ChevronRight className="h-5 w-5" />
@@ -173,12 +195,15 @@ export function HeroSlider({ entries }: HeroSliderProps) {
{slides.map((_, i) => (
<button
key={i}
onClick={() => { go(i); startAutoplay(); }}
onClick={() => {
go(i);
startAutoplay();
}}
aria-label={`Go to slide ${i + 1}`}
className={`rounded-full transition-all duration-300 ${
i === activeIndex
? 'h-1.5 w-6 bg-white'
: 'h-1.5 w-1.5 bg-white/30 hover:bg-white/60'
? "h-1.5 w-6 bg-white"
: "h-1.5 w-1.5 bg-white/30 hover:bg-white/60"
}`}
/>
))}
@@ -1,5 +1,5 @@
import { BackdropScrollCard } from './BackdropCard';
import type { TmdbEntry } from '@/types';
import { BackdropScrollCard } from "./BackdropCard";
import type { TmdbEntry } from "@/types";
interface PopularBeltProps {
movieEntries: TmdbEntry[];
@@ -16,17 +16,23 @@ export function PopularBelt({ movieEntries, tvEntries }: PopularBeltProps) {
<div
className="flex gap-4"
style={{
animation: 'marquee-left 40s linear infinite',
width: 'max-content',
animation: "marquee-left 40s linear infinite",
width: "max-content",
}}
onMouseEnter={(e) => ((e.currentTarget as HTMLDivElement).style.animationPlayState = 'paused')}
onMouseLeave={(e) => ((e.currentTarget as HTMLDivElement).style.animationPlayState = 'running')}
onMouseEnter={(e) =>
((e.currentTarget as HTMLDivElement).style.animationPlayState =
"paused")
}
onMouseLeave={(e) =>
((e.currentTarget as HTMLDivElement).style.animationPlayState =
"running")
}
>
{/* Original + duplicate for seamless loop */}
{[...Array(2)].flatMap((_, pass) =>
items.map((item) => (
<BackdropScrollCard key={`${pass}-${item.id}`} entry={item} />
))
)),
)}
</div>
</div>
@@ -1,4 +1,4 @@
import { Link } from 'react-router-dom';
import { Link } from "react-router-dom";
interface SectionHeaderProps {
icon: React.ReactNode;
+7 -7
View File
@@ -1,7 +1,7 @@
export { HeroSlider } from './HeroSlider';
export { BackdropCard, BackdropScrollCard } from './BackdropCard';
export { NumberedListItem } from './NumberedListItem';
export { MiniPosterCard } from './MiniPosterCard';
export { UpcomingCard } from './UpcomingCard';
export { SectionHeader } from './SectionHeader';
export { PopularBelt } from './PopularBelt';
export { HeroSlider } from "./HeroSlider";
export { BackdropCard, BackdropScrollCard } from "./BackdropCard";
export { NumberedListItem } from "./NumberedListItem";
export { MiniPosterCard } from "./MiniPosterCard";
export { UpcomingCard } from "./UpcomingCard";
export { SectionHeader } from "./SectionHeader";
export { PopularBelt } from "./PopularBelt";
@@ -1,19 +1,20 @@
import { Outlet, useLocation } from 'react-router-dom';
import { useState, useRef, useEffect } from 'react';
import { Menu } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Outlet, useLocation } from "react-router-dom";
import { useState, useRef, useEffect } from "react";
import { Menu } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import { Sidebar, MobileSidebarContent } from './Sidebar';
import { TitleBar } from './TitleBar';
import { CommandPalette } from '@/components/CommandPalette';
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
} from "@/components/ui/sheet";
import { Sidebar, MobileSidebarContent } from "./Sidebar";
import { TitleBar } from "./TitleBar";
import { CommandPalette } from "@/components/CommandPalette";
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
const isElectron = import.meta.env.VITE_ELECTRON === 'true' || !!window.electron?.isElectron;
const isElectron =
import.meta.env.VITE_ELECTRON === "true" || !!window.electron?.isElectron;
export function AppLayout() {
const [mobileOpen, setMobileOpen] = useState(false);
@@ -28,13 +29,13 @@ export function AppLayout() {
// Global keyboard shortcut: Ctrl+P or "/" when not in input
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
if ((e.ctrlKey || e.metaKey) && e.key === "p") {
e.preventDefault();
openPalette();
return;
}
if (
e.key === '/' &&
e.key === "/" &&
!e.ctrlKey &&
!e.metaKey &&
!e.altKey &&
@@ -46,8 +47,8 @@ export function AppLayout() {
openPalette();
}
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [openPalette]);
return (
@@ -63,7 +64,11 @@ export function AppLayout() {
{/* Mobile header */}
<div className="fixed inset-x-0 top-0 z-40 flex h-14 items-center gap-3 border-b border-border bg-background px-4 md:hidden">
<Button variant="ghost" size="icon" onClick={() => setMobileOpen(true)}>
<Button
variant="ghost"
size="icon"
onClick={() => setMobileOpen(true)}
>
<Menu className="h-5 w-5" />
</Button>
<span className="text-lg font-bold">Showy</span>
@@ -71,7 +76,11 @@ export function AppLayout() {
{/* Mobile sidebar sheet */}
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
<SheetContent side="left" className="w-64 p-0" showCloseButton={false}>
<SheetContent
side="left"
className="w-64 p-0"
showCloseButton={false}
>
<SheetHeader className="sr-only">
<SheetTitle>Navigation</SheetTitle>
</SheetHeader>
@@ -1,4 +1,4 @@
import { NavLink } from 'react-router-dom';
import { NavLink } from "react-router-dom";
import {
LayoutDashboard,
Home,
@@ -12,25 +12,25 @@ import {
Moon,
Sun,
Film,
} from 'lucide-react';
import { useThemeStore } from '@/stores/useThemeStore';
import { Separator } from '@/components/ui/separator';
} from "lucide-react";
import { useThemeStore } from "@/stores/useThemeStore";
import { Separator } from "@/components/ui/separator";
const mainNav = [
{ to: '/dashboard', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/', icon: Home, label: 'Home' },
{ 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' },
{ 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' },
{ to: "/calendar", icon: CalendarDays, label: "Calendar" },
{ to: "/people", icon: Users, label: "People" },
];
function NavItem({
@@ -45,17 +45,19 @@ function NavItem({
return (
<NavLink
to={to}
end={to === '/'}
end={to === "/"}
className={({ isActive }) =>
`relative flex flex-col items-center gap-1 rounded-md px-2 py-2.5 transition-colors ${
isActive
? 'bg-sidebar-accent text-sidebar-primary'
: 'text-sidebar-foreground/50 hover:bg-sidebar-accent/40 hover:text-sidebar-foreground'
? "bg-sidebar-accent text-sidebar-primary"
: "text-sidebar-foreground/50 hover:bg-sidebar-accent/40 hover:text-sidebar-foreground"
}`
}
>
<Icon className="h-5 w-5 shrink-0" />
<span className="text-[10px] font-medium leading-none tracking-wide">{label}</span>
<span className="text-[10px] font-medium leading-none tracking-wide">
{label}
</span>
</NavLink>
);
}
@@ -97,13 +99,13 @@ export function Sidebar() {
className="w-full flex flex-col items-center gap-1 rounded-md px-2 py-2.5 text-sidebar-foreground/50 hover:bg-sidebar-accent/40 hover:text-sidebar-foreground transition-colors"
onClick={toggleTheme}
>
{theme === 'dark' ? (
{theme === "dark" ? (
<Sun className="h-5 w-5" />
) : (
<Moon className="h-5 w-5" />
)}
<span className="text-[10px] font-medium leading-none tracking-wide">
{theme === 'dark' ? 'Light' : 'Dark'}
{theme === "dark" ? "Light" : "Dark"}
</span>
</button>
<NavItem to="/settings" icon={Settings} label="Settings" />
@@ -126,13 +128,13 @@ function MobileNavItem({
return (
<NavLink
to={to}
end={to === '/'}
end={to === "/"}
onClick={onClick}
className={({ isActive }) =>
`flex items-center gap-3 rounded-lg px-3 py-2.5 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'
? "bg-sidebar-accent text-sidebar-primary font-medium"
: "text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
}`
}
>
@@ -142,7 +144,11 @@ function MobileNavItem({
);
}
export function MobileSidebarContent({ onNavigate }: { onNavigate: () => void }) {
export function MobileSidebarContent({
onNavigate,
}: {
onNavigate: () => void;
}) {
const { theme, toggleTheme } = useThemeStore();
return (
@@ -189,14 +195,19 @@ export function MobileSidebarContent({ onNavigate }: { onNavigate: () => void })
className="w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground transition-colors"
onClick={toggleTheme}
>
{theme === 'dark' ? (
{theme === "dark" ? (
<Sun className="h-4 w-4" />
) : (
<Moon className="h-4 w-4" />
)}
<span>{theme === 'dark' ? 'Light Mode' : 'Dark Mode'}</span>
<span>{theme === "dark" ? "Light Mode" : "Dark Mode"}</span>
</button>
<MobileNavItem to="/settings" icon={Settings} label="Settings" onClick={onNavigate} />
<MobileNavItem
to="/settings"
icon={Settings}
label="Settings"
onClick={onNavigate}
/>
</div>
</div>
);
@@ -1,4 +1,4 @@
import { Minus, Square, X } from 'lucide-react';
import { Minus, Square, X } from "lucide-react";
export function TitleBar() {
const minimize = () => window.electron?.windowControls.minimize();
@@ -6,14 +6,20 @@ export function TitleBar() {
const close = () => window.electron?.windowControls.close();
return (
<div className="flex h-14 select-none items-center justify-between border-b border-border bg-background"
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
<div
className="flex h-14 select-none items-center justify-between border-b border-border bg-background"
style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
>
<div className="flex items-center gap-2 pl-3">
<span className="text-xs font-semibold tracking-wide text-foreground/80">SHOWY</span>
<span className="text-xs font-semibold tracking-wide text-foreground/80">
SHOWY
</span>
</div>
<div className="flex h-full" style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}>
<div
className="flex h-full"
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
>
<button
onClick={minimize}
className="flex h-full w-11 items-center justify-center transition-colors hover:bg-muted"
@@ -1,5 +1,5 @@
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
export function DashboardSkeleton() {
return (
@@ -236,7 +236,10 @@ export function SeasonSkeleton() {
<Skeleton className="h-6 w-28" />
<div className="space-y-2">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex gap-4 rounded-lg border border-border p-3">
<div
key={i}
className="flex gap-4 rounded-lg border border-border p-3"
>
<Skeleton className="h-16 w-28 shrink-0 rounded" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-40" />
@@ -1,12 +1,15 @@
import { Button } from '@/components/ui/button';
import { CheckCircle2, X } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { CheckCircle2, X } from "lucide-react";
interface AutoMarkWatchedPromptProps {
onAccept: () => void;
onDecline: () => void;
}
export function AutoMarkWatchedPrompt({ onAccept, onDecline }: AutoMarkWatchedPromptProps) {
export function AutoMarkWatchedPrompt({
onAccept,
onDecline,
}: AutoMarkWatchedPromptProps) {
return (
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-30 animate-in slide-in-from-bottom-4 fade-in duration-300">
<div className="flex items-center gap-3 bg-popover/95 backdrop-blur-lg border border-border rounded-xl px-4 py-3 shadow-xl max-w-sm">
@@ -1,8 +1,8 @@
import { useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import type { Season } from '@/types';
import { useMemo } from "react";
import { Button } from "@/components/ui/button";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { ChevronLeft, ChevronRight } from "lucide-react";
import type { Season } from "@/types";
interface EpisodeNavigatorProps {
seasons: Season[];
@@ -19,13 +19,16 @@ export function EpisodeNavigator({
}: EpisodeNavigatorProps) {
const activeSeason = useMemo(
() => seasons.find((s) => s.season_number === currentSeason),
[seasons, currentSeason]
[seasons, currentSeason],
);
const episodes = activeSeason?.episodes || [];
const hasPrev = currentEpisode && currentEpisode > 1;
const hasNext = currentEpisode && activeSeason && currentEpisode < (activeSeason.episode_count || episodes.length);
const hasNext =
currentEpisode &&
activeSeason &&
currentEpisode < (activeSeason.episode_count || episodes.length);
// Check if there's a next season
const hasNextSeason = useMemo(() => {
@@ -45,7 +48,11 @@ export function EpisodeNavigator({
.map((season) => (
<Button
key={season.id}
variant={season.season_number === currentSeason ? 'default' : 'outline'}
variant={
season.season_number === currentSeason
? "default"
: "outline"
}
size="sm"
className="shrink-0 h-7 text-xs px-3"
onClick={() => onEpisodeChange?.(season.season_number, 1)}
@@ -65,7 +72,9 @@ export function EpisodeNavigator({
size="icon"
className="h-8 w-8 shrink-0"
disabled={!hasPrev}
onClick={() => hasPrev && onEpisodeChange?.(currentSeason!, currentEpisode! - 1)}
onClick={() =>
hasPrev && onEpisodeChange?.(currentSeason!, currentEpisode! - 1)
}
>
<ChevronLeft className="h-4 w-4" />
</Button>
@@ -77,14 +86,18 @@ export function EpisodeNavigator({
.map((ep) => (
<Button
key={ep.id}
variant={ep.episode_number === currentEpisode ? 'default' : 'ghost'}
variant={
ep.episode_number === currentEpisode ? "default" : "ghost"
}
size="sm"
className={`shrink-0 h-7 w-7 p-0 text-xs ${
ep.episode_number === currentEpisode
? ''
: 'text-muted-foreground hover:text-foreground'
? ""
: "text-muted-foreground hover:text-foreground"
}`}
onClick={() => onEpisodeChange?.(currentSeason!, ep.episode_number)}
onClick={() =>
onEpisodeChange?.(currentSeason!, ep.episode_number)
}
>
{ep.episode_number}
</Button>
@@ -1,14 +1,14 @@
import { useEffect, useRef, useState } from 'react';
import { getTmdbImageUrl } from '@/lib/api';
import { useEffect, useRef, useState } from "react";
import { getTmdbImageUrl } from "@/lib/api";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { CheckCircle2, PlayCircle, Tv } from 'lucide-react';
import type { Season } from '@/types';
} from "@/components/ui/select";
import { CheckCircle2, PlayCircle, Tv } from "lucide-react";
import type { Season } from "@/types";
interface EpisodesSidebarProps {
seasons: Season[];
@@ -36,13 +36,20 @@ export function EpisodesSidebar({
// Auto-scroll to the currently playing episode
useEffect(() => {
if (activeEpisodeRef.current) {
activeEpisodeRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
activeEpisodeRef.current.scrollIntoView({
behavior: "smooth",
block: "center",
});
}
}, [currentSeason, currentEpisode, selectedSeason]);
const browsingSeason = seasons.find((s) => s.season_number === selectedSeason);
const browsingSeason = seasons.find(
(s) => s.season_number === selectedSeason,
);
const episodes = browsingSeason?.episodes
? [...browsingSeason.episodes].sort((a, b) => a.episode_number - b.episode_number)
? [...browsingSeason.episodes].sort(
(a, b) => a.episode_number - b.episode_number,
)
: [];
const playableSeasons = seasons
@@ -58,9 +65,7 @@ export function EpisodesSidebar({
onValueChange={(v) => setSelectedSeason(Number(v))}
>
<SelectTrigger className="h-9 bg-white/5 border-white/10 text-white hover:bg-white/10 focus:ring-0 focus:ring-offset-0">
<SelectValue>
Season {selectedSeason}
</SelectValue>
<SelectValue>Season {selectedSeason}</SelectValue>
</SelectTrigger>
<SelectContent className="bg-zinc-900 border-white/10">
{playableSeasons.map((season) => (
@@ -86,28 +91,32 @@ export function EpisodesSidebar({
{episodes.map((ep) => {
const isPlaying =
selectedSeason === currentSeason && ep.episode_number === currentEpisode;
selectedSeason === currentSeason &&
ep.episode_number === currentEpisode;
const isWatched =
!!ep.date_first_seen ||
(ep.episodeSeens != null && ep.episodeSeens.length > 0);
const isUnreleased =
!!ep.air_date && new Date(ep.air_date) > new Date();
const stillUrl = ep.still_path
? getTmdbImageUrl(ep.still_path, 'w300')
? getTmdbImageUrl(ep.still_path, "w300")
: null;
return (
<button
key={ep.id}
ref={isPlaying ? activeEpisodeRef : undefined}
onClick={() => !isUnreleased && onEpisodeSelect(selectedSeason, ep.episode_number)}
onClick={() =>
!isUnreleased &&
onEpisodeSelect(selectedSeason, ep.episode_number)
}
disabled={isUnreleased}
className={`w-full flex gap-3 p-2 rounded-lg text-left transition-colors group ${
isUnreleased
? 'opacity-50 cursor-not-allowed'
? "opacity-50 cursor-not-allowed"
: isPlaying
? 'bg-primary/15 ring-1 ring-primary/40'
: 'hover:bg-white/5'
? "bg-primary/15 ring-1 ring-primary/40"
: "hover:bg-white/5"
}`}
>
{/* Thumbnail */}
@@ -117,7 +126,7 @@ export function EpisodesSidebar({
src={stillUrl}
alt={ep.name}
className={`w-full h-full object-cover ${
isUnreleased ? 'grayscale' : ''
isUnreleased ? "grayscale" : ""
}`}
loading="lazy"
/>
@@ -144,10 +153,16 @@ export function EpisodesSidebar({
<div className="flex-1 min-w-0 py-0.5">
<p
className={`text-sm font-medium leading-tight truncate ${
isPlaying ? 'text-primary' : isUnreleased ? 'text-white/30' : 'text-white/80 group-hover:text-white'
isPlaying
? "text-primary"
: isUnreleased
? "text-white/30"
: "text-white/80 group-hover:text-white"
}`}
>
<span className={`font-bold mr-1 ${isPlaying ? 'text-primary' : 'text-white/50'}`}>
<span
className={`font-bold mr-1 ${isPlaying ? "text-primary" : "text-white/50"}`}
>
E{ep.episode_number}
</span>
{ep.name || `Episode ${ep.episode_number}`}
@@ -1,15 +1,16 @@
import { useStreamingStore } from '@/stores/useStreamingStore';
import { Button } from '@/components/ui/button';
import { useStreamingStore } from "@/stores/useStreamingStore";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Monitor, Check, Loader2 } from 'lucide-react';
} from "@/components/ui/dropdown-menu";
import { Monitor, Check, Loader2 } from "lucide-react";
export function ServerSelector() {
const { servers, activeServer, isLoading, switchServer } = useStreamingStore();
const { servers, activeServer, isLoading, switchServer } =
useStreamingStore();
return (
<DropdownMenu>
@@ -24,7 +25,9 @@ export function ServerSelector() {
) : (
<Monitor className="h-3.5 w-3.5" />
)}
<span className="hidden sm:inline">{activeServer?.name || 'Select Server'}</span>
<span className="hidden sm:inline">
{activeServer?.name || "Select Server"}
</span>
<span className="sm:hidden">Server</span>
</Button>
</DropdownMenuTrigger>
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useStreamingStore } from '@/stores/useStreamingStore';
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useStreamingStore } from "@/stores/useStreamingStore";
import {
isValidEventOrigin,
updateProgressFromEvent,
@@ -8,19 +8,14 @@ import {
logWatchCompleted,
isValidEmbedUrl,
getEntryWatchProgress,
} from '@/lib/streaming';
import type { PlayerEvent } from '@/lib/streaming';
import { ServerSelector } from './ServerSelector';
import { EpisodesSidebar } from './EpisodesSidebar';
import { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt';
import { Button } from '@/components/ui/button';
import {
X,
List,
AlertTriangle,
RefreshCw,
} from 'lucide-react';
import type { Entry, Season } from '@/types';
} from "@/lib/streaming";
import type { PlayerEvent } from "@/lib/streaming";
import { ServerSelector } from "./ServerSelector";
import { EpisodesSidebar } from "./EpisodesSidebar";
import { AutoMarkWatchedPrompt } from "./AutoMarkWatchedPrompt";
import { Button } from "@/components/ui/button";
import { X, List, AlertTriangle, RefreshCw } from "lucide-react";
import type { Entry, Season } from "@/types";
interface StreamingDialogProps {
entry: Entry;
@@ -67,11 +62,21 @@ export function StreamingDialog({
const autoMarkPromptShownRef = useRef(autoMarkPromptShown);
const onMarkAsWatchedRef = useRef(onMarkAsWatched);
useEffect(() => { currentSeasonRef.current = currentSeason; }, [currentSeason]);
useEffect(() => { currentEpisodeRef.current = currentEpisode; }, [currentEpisode]);
useEffect(() => { autoMarkRef.current = autoMarkWatched; }, [autoMarkWatched]);
useEffect(() => { autoMarkPromptShownRef.current = autoMarkPromptShown; }, [autoMarkPromptShown]);
useEffect(() => { onMarkAsWatchedRef.current = onMarkAsWatched; }, [onMarkAsWatched]);
useEffect(() => {
currentSeasonRef.current = currentSeason;
}, [currentSeason]);
useEffect(() => {
currentEpisodeRef.current = currentEpisode;
}, [currentEpisode]);
useEffect(() => {
autoMarkRef.current = autoMarkWatched;
}, [autoMarkWatched]);
useEffect(() => {
autoMarkPromptShownRef.current = autoMarkPromptShown;
}, [autoMarkPromptShown]);
useEffect(() => {
onMarkAsWatchedRef.current = onMarkAsWatched;
}, [onMarkAsWatched]);
// Sync initial values when dialog opens
useEffect(() => {
@@ -87,13 +92,13 @@ export function StreamingDialog({
useEffect(() => {
if (!isOpen) return;
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
if (e.key === "Escape") {
closePlayer();
onClose();
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [isOpen, onClose, closePlayer]);
// postMessage listener — handles episode sync + progress + auto-mark
@@ -107,13 +112,17 @@ export function StreamingDialog({
const episode = currentEpisodeRef.current;
// VidLink MEDIA_DATA: sync current episode from embed navigation
if (event.data?.type === 'MEDIA_DATA') {
if (event.data?.type === "MEDIA_DATA") {
const allData = event.data.data;
const tmdbId = entry.entryIds?.tmdb_id;
if (tmdbId && allData?.[String(tmdbId)]) {
const d = allData[String(tmdbId)];
const s = d.last_season_watched ? parseInt(d.last_season_watched) : null;
const e = d.last_episode_watched ? parseInt(d.last_episode_watched) : null;
const s = d.last_season_watched
? parseInt(d.last_season_watched)
: null;
const e = d.last_episode_watched
? parseInt(d.last_episode_watched)
: null;
if (s && e && (s !== season || e !== episode)) {
setCurrentSeason(s);
setCurrentEpisode(e);
@@ -125,13 +134,15 @@ export function StreamingDialog({
// PLAYER_EVENT (VidLink + VidKing JSON)
let playerData: Record<string, unknown> | null = null;
if (event.data?.type === 'PLAYER_EVENT') {
if (event.data?.type === "PLAYER_EVENT") {
playerData = event.data.data;
} else if (typeof event.data === 'string') {
} else if (typeof event.data === "string") {
try {
const parsed = JSON.parse(event.data);
if (parsed?.type === 'PLAYER_EVENT') playerData = parsed.data;
} catch { /* not JSON */ }
if (parsed?.type === "PLAYER_EVENT") playerData = parsed.data;
} catch {
/* not JSON */
}
}
if (!playerData) return;
@@ -147,10 +158,10 @@ export function StreamingDialog({
}
const playerEvent: PlayerEvent = {
event: playerData.event as PlayerEvent['event'],
event: playerData.event as PlayerEvent["event"],
currentTime: Number(playerData.currentTime) || 0,
duration: Number(playerData.duration) || 0,
mediaType: entry.is_tvseries ? 'tv' : 'movie',
mediaType: entry.is_tvseries ? "tv" : "movie",
tmdbId: entry.entryIds?.tmdb_id || 0,
season: playerData.season ? Number(playerData.season) : season,
episode: playerData.episode ? Number(playerData.episode) : episode,
@@ -158,16 +169,20 @@ export function StreamingDialog({
};
if (entry.entryIds?.tmdb_id) {
updateProgressFromEvent(playerEvent, entry.title, entry.poster_path || undefined);
updateProgressFromEvent(
playerEvent,
entry.title,
entry.poster_path || undefined,
);
}
const isFinished =
playerEvent.event === 'ended' ||
(playerEvent.event === 'timeupdate' &&
playerEvent.event === "ended" ||
(playerEvent.event === "timeupdate" &&
isConsideredWatched(
playerEvent.currentTime,
playerEvent.duration,
autoMarkRef.current.threshold
autoMarkRef.current.threshold,
));
if (isFinished) {
@@ -187,7 +202,10 @@ export function StreamingDialog({
});
if (autoMarkRef.current.enabled) {
onMarkAsWatchedRef.current?.(playerEvent.season, playerEvent.episode);
onMarkAsWatchedRef.current?.(
playerEvent.season,
playerEvent.episode,
);
markedAsWatched.current.add(key);
} else if (!autoMarkPromptShownRef.current) {
setShowAutoMarkPrompt(true);
@@ -196,8 +214,8 @@ export function StreamingDialog({
}
};
window.addEventListener('message', handler);
return () => window.removeEventListener('message', handler);
window.addEventListener("message", handler);
return () => window.removeEventListener("message", handler);
}, [isOpen, entry]);
const handleEpisodeSelect = useCallback(
@@ -209,7 +227,7 @@ export function StreamingDialog({
const watchProgress = getEntryWatchProgress(entry.entryIds.tmdb_id);
const epProgress = watchProgress?.showProgress?.[`s${season}e${episode}`];
play({
type: 'tv',
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season,
@@ -217,7 +235,7 @@ export function StreamingDialog({
startAt: epProgress?.watched,
});
},
[entry, play]
[entry, play],
);
// Current episode name for the top bar
@@ -248,7 +266,8 @@ export function StreamingDialog({
</span>
{entry.is_tvseries && (
<span className="text-white/50 text-xs leading-tight truncate">
S{String(currentSeason).padStart(2, '0')}E{String(currentEpisode).padStart(2, '0')}
S{String(currentSeason).padStart(2, "0")}E
{String(currentEpisode).padStart(2, "0")}
{currentEpisodeName && ` — ${currentEpisodeName}`}
</span>
)}
@@ -263,8 +282,8 @@ export function StreamingDialog({
size="sm"
className={`h-8 gap-1.5 text-xs transition-colors ${
showSidebar
? 'text-white bg-white/10 hover:bg-white/15'
: 'text-white/60 hover:text-white hover:bg-white/10'
? "text-white bg-white/10 hover:bg-white/15"
: "text-white/60 hover:text-white hover:bg-white/10"
}`}
onClick={() => setShowSidebar((v) => !v)}
>
@@ -276,7 +295,10 @@ export function StreamingDialog({
variant="ghost"
size="icon"
className="h-8 w-8 text-white/60 hover:text-white hover:bg-white/10"
onClick={() => { closePlayer(); onClose(); }}
onClick={() => {
closePlayer();
onClose();
}}
>
<X className="h-4 w-4" />
</Button>
@@ -305,7 +327,9 @@ export function StreamingDialog({
<AlertTriangle className="h-7 w-7 text-destructive" />
</div>
<div className="space-y-1">
<h3 className="text-white font-semibold">Stream Unavailable</h3>
<h3 className="text-white font-semibold">
Stream Unavailable
</h3>
<p className="text-white/50 text-sm">{error.message}</p>
</div>
<div className="flex gap-2">
@@ -321,7 +345,10 @@ export function StreamingDialog({
<Button
variant="outline"
size="sm"
onClick={() => { closePlayer(); onClose(); }}
onClick={() => {
closePlayer();
onClose();
}}
className="bg-white/5 border-white/20 text-white hover:bg-white/10"
>
Close
@@ -371,6 +398,6 @@ export function StreamingDialog({
)}
</div>
</div>,
document.body
document.body,
);
}
@@ -1,7 +1,7 @@
export { StreamingPlayer } from './StreamingPlayer';
export { StreamingDialog } from './StreamingDialog';
export { StreamingSection } from './StreamingSection';
export { ServerSelector } from './ServerSelector';
export { EpisodesSidebar } from './EpisodesSidebar';
export { EpisodeNavigator } from './EpisodeNavigator';
export { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt';
export { StreamingPlayer } from "./StreamingPlayer";
export { StreamingDialog } from "./StreamingDialog";
export { StreamingSection } from "./StreamingSection";
export { ServerSelector } from "./ServerSelector";
export { EpisodesSidebar } from "./EpisodesSidebar";
export { EpisodeNavigator } from "./EpisodeNavigator";
export { AutoMarkWatchedPrompt } from "./AutoMarkWatchedPrompt";
+18 -18
View File
@@ -1,16 +1,16 @@
"use client"
"use client";
import * as React from "react"
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
import * as React from "react";
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Avatar({
className,
size = "default",
...props
}: AvatarPrimitive.Root.Props & {
size?: "default" | "sm" | "lg"
size?: "default" | "sm" | "lg";
}) {
return (
<AvatarPrimitive.Root
@@ -18,11 +18,11 @@ function Avatar({
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className
className,
)}
{...props}
/>
)
);
}
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
@@ -31,11 +31,11 @@ function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
data-slot="avatar-image"
className={cn(
"aspect-square size-full rounded-full object-cover",
className
className,
)}
{...props}
/>
)
);
}
function AvatarFallback({
@@ -47,11 +47,11 @@ function AvatarFallback({
data-slot="avatar-fallback"
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
className
className,
)}
{...props}
/>
)
);
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
@@ -63,11 +63,11 @@ function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
className,
)}
{...props}
/>
)
);
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
@@ -76,11 +76,11 @@ function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
data-slot="avatar-group"
className={cn(
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
className
className,
)}
{...props}
/>
)
);
}
function AvatarGroupCount({
@@ -92,11 +92,11 @@ function AvatarGroupCount({
data-slot="avatar-group-count"
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -106,4 +106,4 @@ export {
AvatarGroup,
AvatarGroupCount,
AvatarBadge,
}
};
+9 -9
View File
@@ -1,8 +1,8 @@
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
@@ -24,8 +24,8 @@ const badgeVariants = cva(
defaultVariants: {
variant: "default",
},
}
)
},
);
function Badge({
className,
@@ -39,14 +39,14 @@ function Badge({
{
className: cn(badgeVariants({ variant }), className),
},
props
props,
),
render,
state: {
slot: "badge",
variant,
},
})
});
}
export { Badge, badgeVariants }
export { Badge, badgeVariants };
+7 -7
View File
@@ -1,7 +1,7 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button"
import { cva, type VariantProps } from "class-variance-authority"
import { Button as ButtonPrimitive } from "@base-ui/react/button";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
@@ -37,8 +37,8 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
)
},
);
function Button({
className,
@@ -52,7 +52,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
);
}
export { Button, buttonVariants }
export { Button, buttonVariants };
+48 -41
View File
@@ -1,16 +1,20 @@
"use client"
"use client";
import * as React from "react"
import * as React from "react";
import {
DayPicker,
getDefaultClassNames,
type DayButton,
type Locale,
} from "react-day-picker"
} from "react-day-picker";
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button";
import {
ChevronLeftIcon,
ChevronRightIcon,
ChevronDownIcon,
} from "lucide-react";
function Calendar({
className,
@@ -23,9 +27,9 @@ function Calendar({
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
}) {
const defaultClassNames = getDefaultClassNames()
const defaultClassNames = getDefaultClassNames();
return (
<DayPicker
@@ -34,7 +38,7 @@ function Calendar({
"group/calendar bg-background p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
className,
)}
captionLayout={captionLayout}
locale={locale}
@@ -47,88 +51,88 @@ function Calendar({
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
defaultClassNames.months,
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav
defaultClassNames.nav,
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_previous
defaultClassNames.button_previous,
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_next
defaultClassNames.button_next,
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption
defaultClassNames.month_caption,
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
defaultClassNames.dropdowns,
),
dropdown_root: cn(
"relative rounded-(--cell-radius)",
defaultClassNames.dropdown_root
defaultClassNames.dropdown_root,
),
dropdown: cn(
"absolute inset-0 bg-popover opacity-0",
defaultClassNames.dropdown
defaultClassNames.dropdown,
),
caption_label: cn(
"font-medium select-none",
captionLayout === "label"
? "text-sm"
: "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
defaultClassNames.caption_label
defaultClassNames.caption_label,
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none",
defaultClassNames.weekday
defaultClassNames.weekday,
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header
defaultClassNames.week_number_header,
),
week_number: cn(
"text-[0.8rem] text-muted-foreground select-none",
defaultClassNames.week_number
defaultClassNames.week_number,
),
day: cn(
"group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
: "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
defaultClassNames.day
defaultClassNames.day,
),
range_start: cn(
"relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",
defaultClassNames.range_start
defaultClassNames.range_start,
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn(
"relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",
defaultClassNames.range_end
defaultClassNames.range_end,
),
today: cn(
"rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",
defaultClassNames.today
defaultClassNames.today,
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
defaultClassNames.outside,
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
defaultClassNames.disabled,
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
@@ -142,24 +146,27 @@ function Calendar({
className={cn(className)}
{...props}
/>
)
);
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
);
}
if (orientation === "right") {
return (
<ChevronRightIcon className={cn("size-4", className)} {...props} />
)
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
);
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
);
},
DayButton: ({ ...props }) => (
<CalendarDayButton locale={locale} {...props} />
@@ -171,13 +178,13 @@ function Calendar({
{children}
</div>
</td>
)
);
},
...components,
}}
{...props}
/>
)
);
}
function CalendarDayButton({
@@ -187,12 +194,12 @@ function CalendarDayButton({
locale,
...props
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
const defaultClassNames = getDefaultClassNames()
const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null)
const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]);
return (
<Button
@@ -211,11 +218,11 @@ function CalendarDayButton({
className={cn(
"relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
className,
)}
{...props}
/>
)
);
}
export { Calendar, CalendarDayButton }
export { Calendar, CalendarDayButton };
+15 -15
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Card({
className,
@@ -13,11 +13,11 @@ function Card({
data-size={size}
className={cn(
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
className,
)}
{...props}
/>
)
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -26,11 +26,11 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
className
className,
)}
{...props}
/>
)
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
@@ -39,11 +39,11 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-title"
className={cn(
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
className,
)}
{...props}
/>
)
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
@@ -53,7 +53,7 @@ function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
@@ -62,11 +62,11 @@ function CardAction({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
className,
)}
{...props}
/>
)
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
@@ -76,7 +76,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
{...props}
/>
)
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -85,11 +85,11 @@ function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -100,4 +100,4 @@ export {
CardAction,
CardDescription,
CardContent,
}
};
@@ -1,7 +1,7 @@
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";
import { cn } from "@/lib/utils"
import { CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { CheckIcon } from "lucide-react";
function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
return (
@@ -9,7 +9,7 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
data-slot="checkbox"
className={cn(
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",
className
className,
)}
{...props}
>
@@ -17,11 +17,10 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none [&>svg]:size-3.5"
>
<CheckIcon
/>
<CheckIcon />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
);
}
export { Checkbox }
export { Checkbox };
+25 -26
View File
@@ -1,26 +1,26 @@
"use client"
"use client";
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import * as React from "react";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
@@ -32,11 +32,11 @@ function DialogOverlay({
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
className,
)}
{...props}
/>
)
);
}
function DialogContent({
@@ -45,7 +45,7 @@ function DialogContent({
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<DialogPortal>
@@ -54,7 +54,7 @@ function DialogContent({
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
className,
)}
{...props}
>
@@ -70,14 +70,13 @@ function DialogContent({
/>
}
>
<XIcon
/>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -87,7 +86,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
);
}
function DialogFooter({
@@ -96,14 +95,14 @@ function DialogFooter({
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
className,
)}
{...props}
>
@@ -114,7 +113,7 @@ function DialogFooter({
</DialogPrimitive.Close>
)}
</div>
)
);
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
@@ -123,11 +122,11 @@ function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
className,
)}
{...props}
/>
)
);
}
function DialogDescription({
@@ -139,11 +138,11 @@ function DialogDescription({
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -157,4 +156,4 @@ export {
DialogPortal,
DialogTitle,
DialogTrigger,
}
};
@@ -1,21 +1,21 @@
"use client"
"use client";
import * as React from "react"
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
import * as React from "react";
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
import { cn } from "@/lib/utils"
import { ChevronRightIcon, CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { ChevronRightIcon, CheckIcon } from "lucide-react";
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}
function DropdownMenuContent({
@@ -41,16 +41,19 @@ function DropdownMenuContent({
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
className={cn(
"z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
)
);
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}
function DropdownMenuLabel({
@@ -58,7 +61,7 @@ function DropdownMenuLabel({
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.GroupLabel
@@ -66,11 +69,11 @@ function DropdownMenuLabel({
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuItem({
@@ -79,8 +82,8 @@ function DropdownMenuItem({
variant = "default",
...props
}: MenuPrimitive.Item.Props & {
inset?: boolean
variant?: "default" | "destructive"
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<MenuPrimitive.Item
@@ -89,15 +92,15 @@ function DropdownMenuItem({
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
@@ -106,7 +109,7 @@ function DropdownMenuSubTrigger({
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.SubmenuTrigger
@@ -114,14 +117,14 @@ function DropdownMenuSubTrigger({
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
)
);
}
function DropdownMenuSubContent({
@@ -135,14 +138,17 @@ function DropdownMenuSubContent({
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
className={cn(
"w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
{...props}
/>
)
);
}
function DropdownMenuCheckboxItem({
@@ -152,7 +158,7 @@ function DropdownMenuCheckboxItem({
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.CheckboxItem
@@ -160,7 +166,7 @@ function DropdownMenuCheckboxItem({
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
checked={checked}
{...props}
@@ -170,13 +176,12 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
<CheckIcon
/>
<CheckIcon />
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
)
);
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
@@ -185,7 +190,7 @@ function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
);
}
function DropdownMenuRadioItem({
@@ -194,7 +199,7 @@ function DropdownMenuRadioItem({
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.RadioItem
@@ -202,7 +207,7 @@ function DropdownMenuRadioItem({
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -211,13 +216,12 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
<CheckIcon
/>
<CheckIcon />
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
)
);
}
function DropdownMenuSeparator({
@@ -230,7 +234,7 @@ function DropdownMenuSeparator({
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
);
}
function DropdownMenuShortcut({
@@ -242,11 +246,11 @@ function DropdownMenuShortcut({
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -265,4 +269,4 @@ export {
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
};
+6 -6
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import { Input as InputPrimitive } from "@base-ui/react/input"
import * as React from "react";
import { Input as InputPrimitive } from "@base-ui/react/input";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
@@ -10,11 +10,11 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
className,
)}
{...props}
/>
)
);
}
export { Input }
export { Input };
+5 -5
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Label({ className, ...props }: React.ComponentProps<"label">) {
return (
@@ -8,11 +8,11 @@ function Label({ className, ...props }: React.ComponentProps<"label">) {
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
className,
)}
{...props}
/>
)
);
}
export { Label }
export { Label };
+12 -12
View File
@@ -1,16 +1,16 @@
"use client"
"use client";
import * as React from "react"
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
import * as React from "react";
import { Popover as PopoverPrimitive } from "@base-ui/react/popover";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Popover({ ...props }: PopoverPrimitive.Root.Props) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
@@ -38,13 +38,13 @@ function PopoverContent({
data-slot="popover-content"
className={cn(
"z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
className,
)}
{...props}
/>
</PopoverPrimitive.Positioner>
</PopoverPrimitive.Portal>
)
);
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -54,7 +54,7 @@ function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
className={cn("flex flex-col gap-0.5 text-sm", className)}
{...props}
/>
)
);
}
function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
@@ -64,7 +64,7 @@ function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
className={cn("font-heading font-medium", className)}
{...props}
/>
)
);
}
function PopoverDescription({
@@ -77,7 +77,7 @@ function PopoverDescription({
className={cn("text-muted-foreground", className)}
{...props}
/>
)
);
}
export {
@@ -87,4 +87,4 @@ export {
PopoverHeader,
PopoverTitle,
PopoverTrigger,
}
};
+10 -10
View File
@@ -1,6 +1,6 @@
import { Progress as ProgressPrimitive } from "@base-ui/react/progress"
import { Progress as ProgressPrimitive } from "@base-ui/react/progress";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Progress({
className,
@@ -20,7 +20,7 @@ function Progress({
<ProgressIndicator />
</ProgressTrack>
</ProgressPrimitive.Root>
)
);
}
function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) {
@@ -28,12 +28,12 @@ function ProgressTrack({ className, ...props }: ProgressPrimitive.Track.Props) {
<ProgressPrimitive.Track
className={cn(
"relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted",
className
className,
)}
data-slot="progress-track"
{...props}
/>
)
);
}
function ProgressIndicator({
@@ -46,7 +46,7 @@ function ProgressIndicator({
className={cn("h-full bg-primary transition-all", className)}
{...props}
/>
)
);
}
function ProgressLabel({ className, ...props }: ProgressPrimitive.Label.Props) {
@@ -56,7 +56,7 @@ function ProgressLabel({ className, ...props }: ProgressPrimitive.Label.Props) {
data-slot="progress-label"
{...props}
/>
)
);
}
function ProgressValue({ className, ...props }: ProgressPrimitive.Value.Props) {
@@ -64,12 +64,12 @@ function ProgressValue({ className, ...props }: ProgressPrimitive.Value.Props) {
<ProgressPrimitive.Value
className={cn(
"ml-auto text-sm text-muted-foreground tabular-nums",
className
className,
)}
data-slot="progress-value"
{...props}
/>
)
);
}
export {
@@ -78,4 +78,4 @@ export {
ProgressIndicator,
ProgressLabel,
ProgressValue,
}
};
@@ -1,9 +1,9 @@
"use client"
"use client";
import * as React from "react"
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
import * as React from "react";
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function ScrollArea({
className,
@@ -25,7 +25,7 @@ function ScrollArea({
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
);
}
function ScrollBar({
@@ -40,7 +40,7 @@ function ScrollBar({
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
className
className,
)}
{...props}
>
@@ -49,7 +49,7 @@ function ScrollBar({
className="relative flex-1 rounded-full bg-border"
/>
</ScrollAreaPrimitive.Scrollbar>
)
);
}
export { ScrollArea, ScrollBar }
export { ScrollArea, ScrollBar };
+27 -26
View File
@@ -1,12 +1,12 @@
"use client"
"use client";
import * as React from "react"
import { Select as SelectPrimitive } from "@base-ui/react/select"
import * as React from "react";
import { Select as SelectPrimitive } from "@base-ui/react/select";
import { cn } from "@/lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react";
const Select = SelectPrimitive.Root
const Select = SelectPrimitive.Root;
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
@@ -15,7 +15,7 @@ function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
className={cn("scroll-my-1 p-1", className)}
{...props}
/>
)
);
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
@@ -25,7 +25,7 @@ function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
className={cn("flex flex-1 text-left", className)}
{...props}
/>
)
);
}
function SelectTrigger({
@@ -34,7 +34,7 @@ function SelectTrigger({
children,
...props
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default"
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
@@ -42,7 +42,7 @@ function SelectTrigger({
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -53,7 +53,7 @@ function SelectTrigger({
}
/>
</SelectPrimitive.Trigger>
)
);
}
function SelectContent({
@@ -83,7 +83,10 @@ function SelectContent({
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
className={cn(
"relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
>
<SelectScrollUpButton />
@@ -92,7 +95,7 @@ function SelectContent({
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
)
);
}
function SelectLabel({
@@ -105,7 +108,7 @@ function SelectLabel({
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
{...props}
/>
)
);
}
function SelectItem({
@@ -118,7 +121,7 @@ function SelectItem({
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
className,
)}
{...props}
>
@@ -133,7 +136,7 @@ function SelectItem({
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
);
}
function SelectSeparator({
@@ -146,7 +149,7 @@ function SelectSeparator({
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
);
}
function SelectScrollUpButton({
@@ -158,14 +161,13 @@ function SelectScrollUpButton({
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
<ChevronUpIcon
/>
<ChevronUpIcon />
</SelectPrimitive.ScrollUpArrow>
)
);
}
function SelectScrollDownButton({
@@ -177,14 +179,13 @@ function SelectScrollDownButton({
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
<ChevronDownIcon
/>
<ChevronDownIcon />
</SelectPrimitive.ScrollDownArrow>
)
);
}
export {
@@ -198,4 +199,4 @@ export {
SelectSeparator,
SelectTrigger,
SelectValue,
}
};
@@ -1,6 +1,6 @@
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Separator({
className,
@@ -13,11 +13,11 @@ function Separator({
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className
className,
)}
{...props}
/>
)
);
}
export { Separator }
export { Separator };
+22 -23
View File
@@ -1,24 +1,24 @@
import * as React from "react"
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
import * as React from "react";
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog";
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
function Sheet({ ...props }: SheetPrimitive.Root.Props) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
@@ -27,11 +27,11 @@ function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
data-slot="sheet-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",
className
className,
)}
{...props}
/>
)
);
}
function SheetContent({
@@ -41,8 +41,8 @@ function SheetContent({
showCloseButton = true,
...props
}: SheetPrimitive.Popup.Props & {
side?: "top" | "right" | "bottom" | "left"
showCloseButton?: boolean
side?: "top" | "right" | "bottom" | "left";
showCloseButton?: boolean;
}) {
return (
<SheetPortal>
@@ -52,7 +52,7 @@ function SheetContent({
data-side={side}
className={cn(
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",
className
className,
)}
{...props}
>
@@ -68,14 +68,13 @@ function SheetContent({
/>
}
>
<XIcon
/>
<XIcon />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Popup>
</SheetPortal>
)
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -85,7 +84,7 @@ function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
className={cn("flex flex-col gap-0.5 p-4", className)}
{...props}
/>
)
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -95,7 +94,7 @@ function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
);
}
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
@@ -104,11 +103,11 @@ function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
data-slot="sheet-title"
className={cn(
"font-heading text-base font-medium text-foreground",
className
className,
)}
{...props}
/>
)
);
}
function SheetDescription({
@@ -121,7 +120,7 @@ function SheetDescription({
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
);
}
export {
@@ -133,4 +132,4 @@ export {
SheetFooter,
SheetTitle,
SheetDescription,
}
};
@@ -1,4 +1,4 @@
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
@@ -7,7 +7,7 @@ function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
);
}
export { Skeleton }
export { Skeleton };
+9 -7
View File
@@ -1,8 +1,8 @@
import { Toaster as Sonner, type ToasterProps } from "sonner"
import { useThemeStore } from "@/stores/useThemeStore"
import { Toaster as Sonner, type ToasterProps } from "sonner";
import { useThemeStore } from "@/stores/useThemeStore";
function Toaster({ ...props }: ToasterProps) {
const theme = useThemeStore((s) => s.theme)
const theme = useThemeStore((s) => s.theme);
return (
<Sonner
@@ -17,13 +17,15 @@ function Toaster({ ...props }: ToasterProps) {
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
success: "group-[.toaster]:!bg-green-500/10 group-[.toaster]:!border-green-500/20 group-[.toaster]:!text-green-600 dark:group-[.toaster]:!text-green-400",
error: "group-[.toaster]:!bg-destructive/10 group-[.toaster]:!border-destructive/20 group-[.toaster]:!text-destructive",
success:
"group-[.toaster]:!bg-green-500/10 group-[.toaster]:!border-green-500/20 group-[.toaster]:!text-green-600 dark:group-[.toaster]:!text-green-400",
error:
"group-[.toaster]:!bg-destructive/10 group-[.toaster]:!border-destructive/20 group-[.toaster]:!text-destructive",
},
}}
{...props}
/>
)
);
}
export { Toaster }
export { Toaster };
@@ -1,25 +1,25 @@
import { useState } from 'react';
import { Star } from 'lucide-react';
import { useState } from "react";
import { Star } from "lucide-react";
interface StarRatingProps {
value: number;
onChange?: (rating: number) => void;
max?: number;
size?: 'sm' | 'md' | 'lg';
size?: "sm" | "md" | "lg";
readOnly?: boolean;
}
const sizeMap = {
sm: 'h-4 w-4',
md: 'h-6 w-6',
lg: 'h-8 w-8',
sm: "h-4 w-4",
md: "h-6 w-6",
lg: "h-8 w-8",
};
export function StarRating({
value,
onChange,
max = 10,
size = 'lg',
size = "lg",
readOnly = false,
}: StarRatingProps) {
const [hovered, setHovered] = useState<number | null>(null);
@@ -39,7 +39,9 @@ export function StarRating({
className="absolute inset-y-0 left-0 w-1/2 z-10 focus:outline-none"
onMouseEnter={() => setHovered(halfValue)}
onMouseLeave={() => setHovered(null)}
onClick={() => onChange?.(halfValue === value ? 0 : halfValue)}
onClick={() =>
onChange?.(halfValue === value ? 0 : halfValue)
}
/>
<button
type="button"
@@ -52,16 +54,24 @@ export function StarRating({
)}
<div className="pointer-events-none">
{displayRating >= star ? (
<Star className={`${iconClass} fill-yellow-400 text-yellow-400 transition-colors`} />
<Star
className={`${iconClass} fill-yellow-400 text-yellow-400 transition-colors`}
/>
) : displayRating >= halfValue ? (
<div className={`relative ${iconClass}`}>
<Star className={`absolute ${iconClass} text-muted-foreground/30 transition-colors`} />
<Star
className={`absolute ${iconClass} text-muted-foreground/30 transition-colors`}
/>
<div className="absolute inset-0 overflow-hidden w-1/2">
<Star className={`${iconClass} fill-yellow-400 text-yellow-400 transition-colors`} />
<Star
className={`${iconClass} fill-yellow-400 text-yellow-400 transition-colors`}
/>
</div>
</div>
) : (
<Star className={`${iconClass} text-muted-foreground/30 transition-colors`} />
<Star
className={`${iconClass} text-muted-foreground/30 transition-colors`}
/>
)}
</div>
</div>
+6 -6
View File
@@ -1,13 +1,13 @@
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { Switch as SwitchPrimitive } from "@base-ui/react/switch";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Switch({
className,
size = "default",
...props
}: SwitchPrimitive.Root.Props & {
size?: "sm" | "default"
size?: "sm" | "default";
}) {
return (
<SwitchPrimitive.Root
@@ -15,7 +15,7 @@ function Switch({
data-size={size}
className={cn(
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
className
className,
)}
{...props}
>
@@ -24,7 +24,7 @@ function Switch({
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
/>
</SwitchPrimitive.Root>
)
);
}
export { Switch }
export { Switch };
+13 -13
View File
@@ -1,9 +1,9 @@
"use client"
"use client";
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
import { cva, type VariantProps } from "class-variance-authority"
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Tabs({
className,
@@ -16,11 +16,11 @@ function Tabs({
data-orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-horizontal:flex-col",
className
className,
)}
{...props}
/>
)
);
}
const tabsListVariants = cva(
@@ -35,8 +35,8 @@ const tabsListVariants = cva(
defaultVariants: {
variant: "default",
},
}
)
},
);
function TabsList({
className,
@@ -50,7 +50,7 @@ function TabsList({
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
)
);
}
function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
@@ -62,11 +62,11 @@ function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
"data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
className
className,
)}
{...props}
/>
)
);
}
function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
@@ -76,7 +76,7 @@ function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
className={cn("flex-1 text-sm outline-none", className)}
{...props}
/>
)
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
@@ -1,6 +1,6 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
@@ -8,11 +8,11 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
className,
)}
{...props}
/>
)
);
}
export { Textarea }
export { Textarea };
+26 -17
View File
@@ -1,10 +1,10 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { collectionsApi } from '@/api/collections';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { collectionsApi } from "@/api/collections";
export const collectionKeys = {
all: ['collections'] as const,
detail: (id: number) => ['collections', id] as const,
all: ["collections"] as const,
detail: (id: number) => ["collections", id] as const,
};
export function useCollections() {
@@ -29,12 +29,14 @@ export function useUpdateCollection() {
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.detail(variables.id),
});
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success('Collection updated');
toast.success("Collection updated");
},
onError: () => {
toast.error('Failed to update collection');
toast.error("Failed to update collection");
},
});
}
@@ -46,10 +48,10 @@ export function useDeleteCollection() {
mutationFn: (id: number) => collectionsApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success('Collection deleted');
toast.success("Collection deleted");
},
onError: () => {
toast.error('Failed to delete collection');
toast.error("Failed to delete collection");
},
});
}
@@ -62,10 +64,10 @@ export function useGetCollectionParts() {
onSuccess: (_data, id) => {
queryClient.invalidateQueries({ queryKey: collectionKeys.detail(id) });
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success('Collection parts fetched');
toast.success("Collection parts fetched");
},
onError: () => {
toast.error('Failed to fetch collection parts');
toast.error("Failed to fetch collection parts");
},
});
}
@@ -74,15 +76,22 @@ export function useRemoveEntryFromCollection() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ collectionId, entryId }: { collectionId: number; entryId: number }) =>
collectionsApi.removeEntry(collectionId, entryId),
mutationFn: ({
collectionId,
entryId,
}: {
collectionId: number;
entryId: number;
}) => collectionsApi.removeEntry(collectionId, entryId),
onSuccess: (_data, { collectionId }) => {
queryClient.invalidateQueries({ queryKey: collectionKeys.detail(collectionId) });
queryClient.invalidateQueries({
queryKey: collectionKeys.detail(collectionId),
});
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success('Entry removed from collection');
toast.success("Entry removed from collection");
},
onError: () => {
toast.error('Failed to remove entry from collection');
toast.error("Failed to remove entry from collection");
},
});
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect } from "react";
export function useDebounce<T>(value: T, delay = 300): T {
const [debouncedValue, setDebouncedValue] = useState(value);
+18 -13
View File
@@ -1,11 +1,11 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { entrySeenApi } from '@/api/entry-seen';
import { entryKeys } from './useEntries';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
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,
all: ["entry-seen"] as const,
byEntry: (entryId: number) => ["entry-seen", "by-entry", entryId] as const,
};
export function useEntrySeenByEntry(entryId: number) {
@@ -34,10 +34,10 @@ export function useCreateEntrySeen() {
queryKey: entryKeys.detail(variables.entry_id),
});
queryClient.invalidateQueries({ queryKey: entryKeys.all });
toast.success('Marked as watched');
toast.success("Marked as watched");
},
onError: () => {
toast.error('Failed to mark as watched');
toast.error("Failed to mark as watched");
},
});
}
@@ -51,16 +51,21 @@ export function useUpdateEntrySeen() {
data,
}: {
id: number;
data: { entry_id: number; date_seen?: string; seen_with?: string; accuracy?: 'EXACT' | 'ESTIMATED' | 'UNKNOWN' };
data: {
entry_id: number;
date_seen?: string;
seen_with?: string;
accuracy?: "EXACT" | "ESTIMATED" | "UNKNOWN";
};
}) => entrySeenApi.update(id, data),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
queryKey: entrySeenKeys.byEntry(variables.data.entry_id),
});
toast.success('Watch record updated');
toast.success("Watch record updated");
},
onError: () => {
toast.error('Failed to update watch record');
toast.error("Failed to update watch record");
},
});
}
@@ -76,10 +81,10 @@ export function useDeleteEntrySeen() {
queryKey: entrySeenKeys.byEntry(variables.entryId),
});
queryClient.invalidateQueries({ queryKey: entryKeys.all });
toast.success('Watch record removed');
toast.success("Watch record removed");
},
onError: () => {
toast.error('Failed to remove watch record');
toast.error("Failed to remove watch record");
},
});
}
+20 -14
View File
@@ -1,13 +1,13 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { episodeSeenApi } from '@/api/episode-seen';
import { entryKeys } from './useEntries';
import { seasonKeys } from './useSeasons';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { episodeSeenApi } from "@/api/episode-seen";
import { entryKeys } from "./useEntries";
import { seasonKeys } from "./useSeasons";
export const episodeSeenKeys = {
all: ['episode-seen'] as const,
all: ["episode-seen"] as const,
byEpisode: (episodeId: number) =>
['episode-seen', 'by-episode', episodeId] as const,
["episode-seen", "by-episode", episodeId] as const,
};
export function useEpisodeSeenByEpisode(episodeId: number) {
@@ -45,10 +45,10 @@ export function useCreateEpisodeSeen() {
queryKey: seasonKeys.episodes(variables.season_id),
});
}
toast.success('Episode marked as watched');
toast.success("Episode marked as watched");
},
onError: () => {
toast.error('Failed to mark episode as watched');
toast.error("Failed to mark episode as watched");
},
});
}
@@ -62,7 +62,13 @@ export function useUpdateEpisodeSeen() {
data,
}: {
id: number;
data: { episode_id: number; entry_id: number; date_seen?: string; seen_with?: string | null; accuracy?: 'EXACT' | 'ESTIMATED' | 'UNKNOWN' };
data: {
episode_id: number;
entry_id: number;
date_seen?: string;
seen_with?: string | null;
accuracy?: "EXACT" | "ESTIMATED" | "UNKNOWN";
};
}) => episodeSeenApi.update(id, data),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({
@@ -71,10 +77,10 @@ export function useUpdateEpisodeSeen() {
queryClient.invalidateQueries({
queryKey: entryKeys.detail(variables.data.entry_id),
});
toast.success('Episode watch record updated');
toast.success("Episode watch record updated");
},
onError: () => {
toast.error('Failed to update episode watch record');
toast.error("Failed to update episode watch record");
},
});
}
@@ -108,10 +114,10 @@ export function useDeleteEpisodeSeen() {
queryKey: seasonKeys.episodes(variables.seasonId),
});
}
toast.success('Episode watch record removed');
toast.success("Episode watch record removed");
},
onError: () => {
toast.error('Failed to remove episode watch record');
toast.error("Failed to remove episode watch record");
},
});
}
+3 -3
View File
@@ -1,9 +1,9 @@
import { useQuery } from '@tanstack/react-query';
import { episodesApi } from '@/api/episodes';
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,
["episodes", "month", start, end] as const,
};
export function useEpisodesByMonth(startDate: string, endDate: string) {
+34 -17
View File
@@ -1,13 +1,18 @@
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { peopleApi } from '@/api/people';
import {
useQuery,
useMutation,
useQueryClient,
useInfiniteQuery,
} from "@tanstack/react-query";
import { toast } from "sonner";
import { peopleApi } from "@/api/people";
export const peopleKeys = {
all: ['people'] as const,
detail: (id: number) => ['people', id] as const,
credits: (id: number) => ['people', id, 'credits'] as const,
tmdbFilmography: (id: number) => ['people', id, 'tmdb-filmography'] as const,
tmdbPreview: (tmdbId: number) => ['people', 'tmdb-preview', tmdbId] as const,
all: ["people"] as const,
detail: (id: number) => ["people", id] as const,
credits: (id: number) => ["people", id, "credits"] as const,
tmdbFilmography: (id: number) => ["people", id, "tmdb-filmography"] as const,
tmdbPreview: (tmdbId: number) => ["people", "tmdb-preview", tmdbId] as const,
};
export function usePerson(id: number) {
@@ -54,22 +59,30 @@ export function useUpdatePerson() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, data }: { id: number; data: Partial<import('@/types').People> }) =>
peopleApi.update(id, data),
mutationFn: ({
id,
data,
}: {
id: number;
data: Partial<import("@/types").People>;
}) => peopleApi.update(id, data),
onSuccess: (updatedPerson) => {
queryClient.invalidateQueries({ queryKey: peopleKeys.detail(updatedPerson.id) });
toast.success('Person updated');
queryClient.invalidateQueries({
queryKey: peopleKeys.detail(updatedPerson.id),
});
toast.success("Person updated");
},
onError: () => {
toast.error('Failed to update person');
toast.error("Failed to update person");
},
});
}
export function useSearchLocalPeople(query: string) {
return useQuery({
queryKey: ['people', 'search', query],
queryFn: () => query === '*' ? peopleApi.getAll() : peopleApi.search(query),
queryKey: ["people", "search", query],
queryFn: () =>
query === "*" ? peopleApi.getAll() : peopleApi.search(query),
enabled: query.length > 0,
});
}
@@ -78,9 +91,13 @@ const LOCAL_PEOPLE_PAGE_SIZE = 48;
export function useLocalPeopleInfinite(search: string, enabled: boolean) {
return useInfiniteQuery({
queryKey: ['people', 'paginated', search],
queryKey: ["people", "paginated", search],
queryFn: ({ pageParam = 1 }) =>
peopleApi.getAllPaginated(pageParam, LOCAL_PEOPLE_PAGE_SIZE, search || undefined),
peopleApi.getAllPaginated(
pageParam,
LOCAL_PEOPLE_PAGE_SIZE,
search || undefined,
),
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.totalPages ? lastPage.page + 1 : undefined,
initialPageParam: 1,
+5 -5
View File
@@ -1,10 +1,10 @@
import { useQuery } from '@tanstack/react-query';
import { seasonsApi } from '@/api/seasons';
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,
all: ["seasons"] as const,
detail: (id: number) => ["seasons", id] as const,
episodes: (id: number) => ["seasons", id, "episodes"] as const,
};
export function useSeason(id: number) {
+6 -6
View File
@@ -1,30 +1,30 @@
import { useQuery } from '@tanstack/react-query';
import { statisticsApi } from '@/api/statistics';
import { useQuery } from "@tanstack/react-query";
import { statisticsApi } from "@/api/statistics";
export function useStatistics() {
return useQuery({
queryKey: ['statistics', 'watch-time-all'],
queryKey: ["statistics", "watch-time-all"],
queryFn: statisticsApi.getAllTimeWatchTime,
});
}
export function useYearlyWatchCount(year: number) {
return useQuery({
queryKey: ['statistics', 'watch-count', year],
queryKey: ["statistics", "watch-count", year],
queryFn: () => statisticsApi.getYearlyWatchCount(year),
});
}
export function useYearlyWatchTime(year: number) {
return useQuery({
queryKey: ['statistics', 'watch-time', year],
queryKey: ["statistics", "watch-time", year],
queryFn: () => statisticsApi.getYearlyWatchTime(year),
});
}
export function useWatchdayDistribution() {
return useQuery({
queryKey: ['statistics', 'watch-weekday'],
queryKey: ["statistics", "watch-weekday"],
queryFn: statisticsApi.getWatchdayDistribution,
});
}
+12 -12
View File
@@ -1,9 +1,9 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { tmdbApi } from '@/api/tmdb';
import { useInfiniteQuery } from "@tanstack/react-query";
import { tmdbApi } from "@/api/tmdb";
export function usePopularMovies() {
return useInfiniteQuery({
queryKey: ['tmdb', 'popular', 'movie'],
queryKey: ["tmdb", "popular", "movie"],
queryFn: ({ pageParam }) => tmdbApi.getPopularMovies(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -13,7 +13,7 @@ export function usePopularMovies() {
export function usePopularTv() {
return useInfiniteQuery({
queryKey: ['tmdb', 'popular', 'tv'],
queryKey: ["tmdb", "popular", "tv"],
queryFn: ({ pageParam }) => tmdbApi.getPopularTv(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -23,7 +23,7 @@ export function usePopularTv() {
export function useTrendingMovies() {
return useInfiniteQuery({
queryKey: ['tmdb', 'trending', 'movie'],
queryKey: ["tmdb", "trending", "movie"],
queryFn: ({ pageParam }) => tmdbApi.getTrendingMovies(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -33,7 +33,7 @@ export function useTrendingMovies() {
export function useTrendingTv() {
return useInfiniteQuery({
queryKey: ['tmdb', 'trending', 'tv'],
queryKey: ["tmdb", "trending", "tv"],
queryFn: ({ pageParam }) => tmdbApi.getTrendingTv(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -43,7 +43,7 @@ export function useTrendingTv() {
export function useTopRatedMovies() {
return useInfiniteQuery({
queryKey: ['tmdb', 'top-rated', 'movie'],
queryKey: ["tmdb", "top-rated", "movie"],
queryFn: ({ pageParam }) => tmdbApi.getTopRatedMovies(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -53,7 +53,7 @@ export function useTopRatedMovies() {
export function useTopRatedTv() {
return useInfiniteQuery({
queryKey: ['tmdb', 'top-rated', 'tv'],
queryKey: ["tmdb", "top-rated", "tv"],
queryFn: ({ pageParam }) => tmdbApi.getTopRatedTv(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -63,7 +63,7 @@ export function useTopRatedTv() {
export function useUpcomingMovies() {
return useInfiniteQuery({
queryKey: ['tmdb', 'upcoming', 'movie'],
queryKey: ["tmdb", "upcoming", "movie"],
queryFn: ({ pageParam }) => tmdbApi.getUpcomingMovies(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -73,7 +73,7 @@ export function useUpcomingMovies() {
export function useTmdbSearch(query: string) {
return useInfiniteQuery({
queryKey: ['tmdb', 'search', query],
queryKey: ["tmdb", "search", query],
queryFn: ({ pageParam }) => tmdbApi.search(query, pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -84,7 +84,7 @@ export function useTmdbSearch(query: string) {
export function usePopularPeople() {
return useInfiniteQuery({
queryKey: ['tmdb', 'popular', 'people'],
queryKey: ["tmdb", "popular", "people"],
queryFn: ({ pageParam }) => tmdbApi.getPopularPeople(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
@@ -94,7 +94,7 @@ export function usePopularPeople() {
export function useTmdbSearchPeople(query: string) {
return useInfiniteQuery({
queryKey: ['tmdb', 'search', 'people', query],
queryKey: ["tmdb", "search", "people", query],
queryFn: ({ pageParam }) => tmdbApi.searchPeople(query, pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
+5 -5
View File
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { useLibraryStore } from '@/stores/useLibraryStore';
import type { TmdbEntry } from '@/types';
import { useMemo } from "react";
import { useLibraryStore } from "@/stores/useLibraryStore";
import type { TmdbEntry } from "@/types";
interface TmdbEntryLink {
/** The resolved link — either /entry/:id if in library, or /entry/tmdb/:type/:id */
@@ -20,7 +20,7 @@ export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink {
const libraryEntries = useLibraryStore((s) => s.entries);
return useMemo(() => {
const isTv = entry.media_type === 'tv' || !!entry.name;
const isTv = entry.media_type === "tv" || !!entry.name;
const libraryEntry = Array.from(libraryEntries.values()).find(
(e) => e.entryIds?.tmdb_id === entry.id,
);
@@ -34,7 +34,7 @@ export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink {
}
return {
linkTo: `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`,
linkTo: `/entry/tmdb/${isTv ? "tv" : "movie"}/${entry.id}`,
isInLibrary: false,
libraryEntryId: null,
};
+9 -8
View File
@@ -1,22 +1,23 @@
import axios from 'axios';
import axios from "axios";
const API_BASE_URL = import.meta.env.VITE_ELECTRON === 'true'
? 'http://localhost:4000/api/v1'
: (import.meta.env.VITE_API_URL || '/api/v1');
const API_BASE_URL =
import.meta.env.VITE_ELECTRON === "true"
? "http://localhost:4000/api/v1"
: import.meta.env.VITE_API_URL || "/api/v1";
export const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
},
});
export const getMediaUrl = (
category: string,
type: string,
size: 'preview' | 'full',
file: string
size: "preview" | "full",
file: string,
) => `${API_BASE_URL}/media/${category}/${type}/${size}/${file}`;
export const getTmdbImageUrl = (path: string, size = 'w342') =>
export const getTmdbImageUrl = (path: string, size = "w342") =>
`https://image.tmdb.org/t/p/${size}${path}`;
+37 -32
View File
@@ -1,29 +1,29 @@
import { getMediaUrl, getTmdbImageUrl } from '@/lib/api';
import type { Entry, Collection, Media } from '@/types';
import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
import type { Entry, Collection, Media } from "@/types";
const DEFAULT_POSTER = '/images/default-poster.png';
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')
? 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
(m: Media) => m.type === "poster" && m.is_selected,
);
if (selectedPoster?.path) {
return getMediaUrl('entries', 'posters', 'preview', selectedPoster.path);
return getMediaUrl("entries", "posters", "preview", selectedPoster.path);
}
}
// Fallback to TMDB poster
if (entry.poster_path) {
return getTmdbImageUrl(entry.poster_path, 'w300');
return getTmdbImageUrl(entry.poster_path, "w300");
}
return DEFAULT_POSTER;
@@ -32,28 +32,23 @@ export function getPosterUrl(entry: Entry): string {
export function getBackdropUrl(entry: Entry): string {
if (entry.medias) {
const selectedBackdrop = entry.medias.find(
(m: Media) => m.type === 'backdrop' && m.is_selected
(m: Media) => m.type === "backdrop" && m.is_selected,
);
if (selectedBackdrop?.path) {
return getMediaUrl(
'entries',
'backdrops',
'full',
selectedBackdrop.path
);
return getMediaUrl("entries", "backdrops", "full", selectedBackdrop.path);
}
}
if (entry.banner_path) {
return getTmdbImageUrl(entry.banner_path, 'w1280');
return getTmdbImageUrl(entry.banner_path, "w1280");
}
return '';
return "";
}
export function getTmdbPosterUrl(
posterPath: string | null,
size = 'w342'
size = "w342",
): string {
if (!posterPath) return DEFAULT_POSTER;
return getTmdbImageUrl(posterPath, size);
@@ -62,14 +57,19 @@ export function getTmdbPosterUrl(
export function getCollectionBackdropUrl(collection: Collection): string {
if (collection.medias) {
const selectedBackdrop = collection.medias.find(
(m: Media) => m.type === 'backdrop' && m.is_selected
(m: Media) => m.type === "backdrop" && m.is_selected,
);
if (selectedBackdrop?.path) {
return getMediaUrl('collections', 'backdrops', 'full', selectedBackdrop.path);
return getMediaUrl(
"collections",
"backdrops",
"full",
selectedBackdrop.path,
);
}
}
if (collection.backdrop_path) {
return getTmdbImageUrl(collection.backdrop_path, 'w780');
return getTmdbImageUrl(collection.backdrop_path, "w780");
}
return getCollectionPosterUrl(collection);
}
@@ -77,42 +77,47 @@ export function getCollectionBackdropUrl(collection: Collection): string {
export function getCollectionPosterUrl(collection: Collection): string {
if (collection.medias) {
const selectedPoster = collection.medias.find(
(m: Media) => m.type === 'poster' && m.is_selected
(m: Media) => m.type === "poster" && m.is_selected,
);
if (selectedPoster?.path) {
return getMediaUrl('collections', 'posters', 'preview', selectedPoster.path);
return getMediaUrl(
"collections",
"posters",
"preview",
selectedPoster.path,
);
}
}
if (collection.poster_path) {
return getTmdbImageUrl(collection.poster_path, 'w342');
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');
if (!profilePath) return "/images/default-profile.png";
return getTmdbImageUrl(profilePath, "w185");
}
export function formatRuntime(minutes: number | null): string {
if (!minutes) return '';
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',
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 '';
if (!dateStr) return "";
return new Date(dateStr).getFullYear().toString();
}
+13 -2
View File
@@ -1,4 +1,15 @@
export type { StreamingProvider, StreamingServer, StreamRequest, StreamResponse, StreamError, PlayerEvent, WatchProgressData, AutoMarkWatchedConfig, StreamingState, MediaType } from './types';
export type {
StreamingProvider,
StreamingServer,
StreamRequest,
StreamResponse,
StreamError,
PlayerEvent,
WatchProgressData,
AutoMarkWatchedConfig,
StreamingState,
MediaType,
} from "./types";
export {
getAllServers,
getProviderForServer,
@@ -23,4 +34,4 @@ export {
isConsideredWatched,
isValidEmbedUrl,
isValidEventOrigin,
} from './streaming-manager';
} from "./streaming-manager";
@@ -1,42 +1,46 @@
import type { StreamingProvider, StreamingServer, StreamRequest } from '../types';
import type {
StreamingProvider,
StreamingServer,
StreamRequest,
} from "../types";
const ANYEMBED_SERVERS: StreamingServer[] = [
{
id: 'anyembed-1',
name: 'AnyEmbed (Server 1)',
provider: 'anyembed',
id: "anyembed-1",
name: "AnyEmbed (Server 1)",
provider: "anyembed",
serverIndex: 1,
supportsEvents: false,
supportsProgress: false,
},
{
id: 'anyembed-2',
name: 'AnyEmbed (Server 2)',
provider: 'anyembed',
id: "anyembed-2",
name: "AnyEmbed (Server 2)",
provider: "anyembed",
serverIndex: 2,
supportsEvents: false,
supportsProgress: false,
},
{
id: 'anyembed-3',
name: 'AnyEmbed (Server 3)',
provider: 'anyembed',
id: "anyembed-3",
name: "AnyEmbed (Server 3)",
provider: "anyembed",
serverIndex: 3,
supportsEvents: false,
supportsProgress: false,
},
{
id: 'anyembed-4',
name: 'AnyEmbed (Server 4)',
provider: 'anyembed',
id: "anyembed-4",
name: "AnyEmbed (Server 4)",
provider: "anyembed",
serverIndex: 4,
supportsEvents: false,
supportsProgress: false,
},
{
id: 'anyembed-5',
name: 'AnyEmbed (Server 5)',
provider: 'anyembed',
id: "anyembed-5",
name: "AnyEmbed (Server 5)",
provider: "anyembed",
serverIndex: 5,
supportsEvents: false,
supportsProgress: false,
@@ -44,8 +48,8 @@ const ANYEMBED_SERVERS: StreamingServer[] = [
];
export const anyembedProvider: StreamingProvider = {
id: 'anyembed',
name: 'AnyEmbed',
id: "anyembed",
name: "AnyEmbed",
servers: ANYEMBED_SERVERS,
getStreamUrl(request: StreamRequest, server: StreamingServer): string {
@@ -53,7 +57,7 @@ export const anyembedProvider: StreamingProvider = {
const id = request.imdbId || String(request.tmdbId);
let basePath: string;
if (request.type === 'movie') {
if (request.type === "movie") {
basePath = `/movie/${id}`;
} else {
basePath = `/tv/${id}/${request.season}/${request.episode}`;
@@ -61,18 +65,18 @@ export const anyembedProvider: StreamingProvider = {
const params = new URLSearchParams();
if (server.serverIndex) {
params.set('server', String(server.serverIndex));
params.set("server", String(server.serverIndex));
}
const query = params.toString();
return `https://anyembed.xyz${basePath}${query ? `?${query}` : ''}`;
return `https://anyembed.xyz${basePath}${query ? `?${query}` : ""}`;
},
getSandboxPolicy(): string {
return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';
return "allow-scripts allow-same-origin allow-forms allow-popups allow-presentation";
},
getAllowedFeatures(): string {
return 'autoplay; fullscreen; picture-in-picture; encrypted-media';
return "autoplay; fullscreen; picture-in-picture; encrypted-media";
},
};
@@ -1,3 +1,3 @@
export { vidlinkProvider } from './vidlink';
export { vidkingProvider } from './vidking';
export { anyembedProvider } from './anyembed';
export { vidlinkProvider } from "./vidlink";
export { vidkingProvider } from "./vidking";
export { anyembedProvider } from "./anyembed";
@@ -1,32 +1,36 @@
import type { StreamingProvider, StreamingServer, StreamRequest } from '../types';
import type {
StreamingProvider,
StreamingServer,
StreamRequest,
} from "../types";
const VIDKING_SERVERS: StreamingServer[] = [
{
id: 'vidking-default',
name: 'VidKing',
provider: 'vidking',
id: "vidking-default",
name: "VidKing",
provider: "vidking",
supportsEvents: true,
supportsProgress: true,
},
];
export const vidkingProvider: StreamingProvider = {
id: 'vidking',
name: 'VidKing',
id: "vidking",
name: "VidKing",
servers: VIDKING_SERVERS,
getStreamUrl(request: StreamRequest, _server: StreamingServer): string {
const params = new URLSearchParams();
params.set('autoPlay', 'true');
params.set('nextEpisode', 'true');
params.set('episodeSelector', 'true');
params.set("autoPlay", "true");
params.set("nextEpisode", "true");
params.set("episodeSelector", "true");
if (request.startAt && request.startAt > 0) {
params.set('progress', String(Math.floor(request.startAt)));
params.set("progress", String(Math.floor(request.startAt)));
}
let basePath: string;
if (request.type === 'movie') {
if (request.type === "movie") {
basePath = `/embed/movie/${request.tmdbId}`;
} else {
basePath = `/embed/tv/${request.tmdbId}/${request.season}/${request.episode}`;
@@ -36,10 +40,10 @@ export const vidkingProvider: StreamingProvider = {
},
getSandboxPolicy(): string {
return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';
return "allow-scripts allow-same-origin allow-forms allow-popups allow-presentation";
},
getAllowedFeatures(): string {
return 'autoplay; fullscreen; picture-in-picture; encrypted-media';
return "autoplay; fullscreen; picture-in-picture; encrypted-media";
},
};
@@ -1,17 +1,21 @@
import type { StreamingProvider, StreamingServer, StreamRequest } from '../types';
import type {
StreamingProvider,
StreamingServer,
StreamRequest,
} from "../types";
const VIDLINK_SERVERS: StreamingServer[] = [
{
id: 'vidlink-default',
name: 'VidLink (Default)',
provider: 'vidlink',
id: "vidlink-default",
name: "VidLink (Default)",
provider: "vidlink",
supportsEvents: true,
supportsProgress: true,
},
{
id: 'vidlink-jw',
name: 'VidLink (JW Player)',
provider: 'vidlink',
id: "vidlink-jw",
name: "VidLink (JW Player)",
provider: "vidlink",
serverIndex: 2,
supportsEvents: true,
supportsProgress: true,
@@ -19,27 +23,27 @@ const VIDLINK_SERVERS: StreamingServer[] = [
];
export const vidlinkProvider: StreamingProvider = {
id: 'vidlink',
name: 'VidLink',
id: "vidlink",
name: "VidLink",
servers: VIDLINK_SERVERS,
getStreamUrl(request: StreamRequest, server: StreamingServer): string {
const params = new URLSearchParams();
params.set('autoplay', 'true');
params.set('title', 'false');
params.set('poster', 'true');
params.set('nextbutton', 'true');
params.set("autoplay", "true");
params.set("title", "false");
params.set("poster", "true");
params.set("nextbutton", "true");
if (server.serverIndex === 2) {
params.set('player', 'jw');
params.set("player", "jw");
}
if (request.startAt && request.startAt > 0) {
params.set('startAt', String(Math.floor(request.startAt)));
params.set("startAt", String(Math.floor(request.startAt)));
}
let basePath: string;
if (request.type === 'movie') {
if (request.type === "movie") {
basePath = `/movie/${request.tmdbId}`;
} else {
basePath = `/tv/${request.tmdbId}/${request.season}/${request.episode}`;
@@ -49,10 +53,10 @@ export const vidlinkProvider: StreamingProvider = {
},
getSandboxPolicy(): string {
return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';
return "allow-scripts allow-same-origin allow-forms allow-popups allow-presentation";
},
getAllowedFeatures(): string {
return 'autoplay; fullscreen; picture-in-picture; encrypted-media';
return "autoplay; fullscreen; picture-in-picture; encrypted-media";
},
};
@@ -7,15 +7,19 @@ import type {
WatchProgressData,
AutoMarkWatchedConfig,
PlayerEvent,
} from './types';
import { vidlinkProvider, vidkingProvider, anyembedProvider } from './providers';
} from "./types";
import {
vidlinkProvider,
vidkingProvider,
anyembedProvider,
} from "./providers";
const STORAGE_KEYS = {
PREFERRED_SERVER: 'showy_preferred_server',
WATCH_PROGRESS: 'showy_watch_progress',
AUTO_MARK_WATCHED: 'showy_auto_mark_watched',
AUTO_MARK_PROMPT_SHOWN: 'showy_auto_mark_prompt_shown',
WATCH_LOGS: 'showy_watch_logs',
PREFERRED_SERVER: "showy_preferred_server",
WATCH_PROGRESS: "showy_watch_progress",
AUTO_MARK_WATCHED: "showy_auto_mark_watched",
AUTO_MARK_PROMPT_SHOWN: "showy_auto_mark_prompt_shown",
WATCH_LOGS: "showy_watch_logs",
} as const;
/** All registered streaming providers */
@@ -31,7 +35,9 @@ export function getAllServers(): StreamingServer[] {
}
/** Get a provider by server ID */
export function getProviderForServer(serverId: string): StreamingProvider | undefined {
export function getProviderForServer(
serverId: string,
): StreamingProvider | undefined {
return providers.find((p) => p.servers.some((s) => s.id === serverId));
}
@@ -41,13 +47,16 @@ export function getServerById(serverId: string): StreamingServer | undefined {
}
/** Build a stream URL for the given request and server */
export function getStreamUrl(request: StreamRequest, server: StreamingServer): StreamResponse | StreamError {
export function getStreamUrl(
request: StreamRequest,
server: StreamingServer,
): StreamResponse | StreamError {
const provider = getProviderForServer(server.id);
if (!provider) {
return {
server,
message: 'Provider not found for this server',
code: 'UNAVAILABLE',
message: "Provider not found for this server",
code: "UNAVAILABLE",
};
}
@@ -55,16 +64,16 @@ export function getStreamUrl(request: StreamRequest, server: StreamingServer): S
if (!request.tmdbId && !request.imdbId) {
return {
server,
message: 'A valid TMDB or IMDB ID is required',
code: 'INVALID_ID',
message: "A valid TMDB or IMDB ID is required",
code: "INVALID_ID",
};
}
if (request.type === 'tv' && (!request.season || !request.episode)) {
if (request.type === "tv" && (!request.season || !request.episode)) {
return {
server,
message: 'Season and episode numbers are required for TV shows',
code: 'MISSING_EPISODE',
message: "Season and episode numbers are required for TV shows",
code: "MISSING_EPISODE",
};
}
@@ -74,27 +83,29 @@ export function getStreamUrl(request: StreamRequest, server: StreamingServer): S
} catch {
return {
server,
message: 'Failed to build stream URL',
code: 'UNKNOWN',
message: "Failed to build stream URL",
code: "UNKNOWN",
};
}
}
/** Check if a response is an error */
export function isStreamError(result: StreamResponse | StreamError): result is StreamError {
return 'code' in result;
export function isStreamError(
result: StreamResponse | StreamError,
): result is StreamError {
return "code" in result;
}
/** Get iframe sandbox policy for a server */
export function getServerSandboxPolicy(serverId: string): string {
const provider = getProviderForServer(serverId);
return provider?.getSandboxPolicy() ?? 'allow-scripts allow-same-origin';
return provider?.getSandboxPolicy() ?? "allow-scripts allow-same-origin";
}
/** Get iframe allowed features for a server */
export function getServerAllowedFeatures(serverId: string): string {
const provider = getProviderForServer(serverId);
return provider?.getAllowedFeatures() ?? 'autoplay; fullscreen';
return provider?.getAllowedFeatures() ?? "autoplay; fullscreen";
}
// --- Persistence ---
@@ -140,7 +151,9 @@ export function getWatchProgress(): Record<string, WatchProgressData> {
}
/** Get watch progress for a specific entry */
export function getEntryWatchProgress(tmdbId: number): WatchProgressData | null {
export function getEntryWatchProgress(
tmdbId: number,
): WatchProgressData | null {
const progress = getWatchProgress();
return progress[String(tmdbId)] || null;
}
@@ -165,7 +178,7 @@ function getEpisodeKey(season: number, episode: number): string {
export function updateProgressFromEvent(
event: PlayerEvent,
title: string,
posterPath?: string
posterPath?: string,
): void {
const existing = getEntryWatchProgress(event.tmdbId);
@@ -180,7 +193,7 @@ export function updateProgressFromEvent(
...(existing?.showProgress ? { showProgress: existing.showProgress } : {}),
};
if (event.mediaType === 'tv' && event.season && event.episode) {
if (event.mediaType === "tv" && event.season && event.episode) {
data.lastSeasonWatched = event.season;
data.lastEpisodeWatched = event.episode;
const key = getEpisodeKey(event.season, event.episode);
@@ -213,7 +226,10 @@ export function getAutoMarkWatchedConfig(): AutoMarkWatchedConfig {
/** Save auto-mark-watched config */
export function setAutoMarkWatchedConfig(config: AutoMarkWatchedConfig): void {
try {
localStorage.setItem(STORAGE_KEYS.AUTO_MARK_WATCHED, JSON.stringify(config));
localStorage.setItem(
STORAGE_KEYS.AUTO_MARK_WATCHED,
JSON.stringify(config),
);
} catch {
// Storage not available
}
@@ -222,7 +238,7 @@ export function setAutoMarkWatchedConfig(config: AutoMarkWatchedConfig): void {
/** Check if the auto-mark prompt has been shown */
export function hasAutoMarkPromptBeenShown(): boolean {
try {
return localStorage.getItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN) === 'true';
return localStorage.getItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN) === "true";
} catch {
return false;
}
@@ -231,7 +247,7 @@ export function hasAutoMarkPromptBeenShown(): boolean {
/** Mark that the auto-mark prompt has been shown */
export function markAutoMarkPromptShown(): void {
try {
localStorage.setItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN, 'true');
localStorage.setItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN, "true");
} catch {
// Storage not available
}
@@ -241,7 +257,7 @@ export function markAutoMarkPromptShown(): void {
interface WatchLog {
tmdbId: number;
type: 'movie' | 'tv';
type: "movie" | "tv";
title: string;
season?: number;
episode?: number;
@@ -274,7 +290,11 @@ export function getWatchLogs(): WatchLog[] {
}
/** Check if an episode/movie is considered "watched" based on progress */
export function isConsideredWatched(watched: number, duration: number, threshold = 90): boolean {
export function isConsideredWatched(
watched: number,
duration: number,
threshold = 90,
): boolean {
if (duration <= 0) return false;
const percent = (watched / duration) * 100;
return percent >= threshold;
@@ -283,9 +303,9 @@ export function isConsideredWatched(watched: number, duration: number, threshold
// --- URL Validation ---
const ALLOWED_ORIGINS = [
'https://vidlink.pro',
'https://www.vidking.net',
'https://anyembed.xyz',
"https://vidlink.pro",
"https://www.vidking.net",
"https://anyembed.xyz",
];
/** Validate that an embed URL is from an allowed origin */
+18 -9
View File
@@ -1,6 +1,6 @@
// Streaming system types
export type MediaType = 'movie' | 'tv';
export type MediaType = "movie" | "tv";
export interface StreamingServer {
id: string;
@@ -34,11 +34,17 @@ export interface StreamResponse {
export interface StreamError {
server: StreamingServer;
message: string;
code: 'INVALID_ID' | 'MISSING_EPISODE' | 'TIMEOUT' | 'NETWORK' | 'UNAVAILABLE' | 'UNKNOWN';
code:
| "INVALID_ID"
| "MISSING_EPISODE"
| "TIMEOUT"
| "NETWORK"
| "UNAVAILABLE"
| "UNKNOWN";
}
export interface PlayerEvent {
event: 'play' | 'pause' | 'seeked' | 'ended' | 'timeupdate';
event: "play" | "pause" | "seeked" | "ended" | "timeupdate";
currentTime: number;
duration: number;
mediaType: MediaType;
@@ -61,12 +67,15 @@ export interface WatchProgressData {
lastSeasonWatched?: number;
lastEpisodeWatched?: number;
/** Per-episode progress for TV shows */
showProgress?: Record<string, {
season: number;
episode: number;
watched: number;
duration: number;
}>;
showProgress?: Record<
string,
{
season: number;
episode: number;
watched: number;
duration: number;
}
>;
lastUpdated: number;
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}
+6 -6
View File
@@ -1,10 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import { App } from './App'
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import { App } from "./App";
createRoot(document.getElementById('root')!).render(
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
)
);
+143 -64
View File
@@ -1,31 +1,56 @@
import { useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, getDay, addMonths, subMonths, isSameDay } from 'date-fns';
import { ChevronLeft, ChevronRight, LayoutGrid, List } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useEpisodesByMonth } from '@/hooks/useEpisodes';
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip';
import { getTmdbPosterUrl } from '@/lib/media-utils';
import type { Episode } from '@/types';
import { useState, useMemo } from "react";
import { Link } from "react-router-dom";
import {
format,
startOfMonth,
endOfMonth,
eachDayOfInterval,
getDay,
addMonths,
subMonths,
isSameDay,
} from "date-fns";
import { ChevronLeft, ChevronRight, LayoutGrid, List } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useEpisodesByMonth } from "@/hooks/useEpisodes";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
TooltipProvider,
} from "@/components/ui/tooltip";
import { getTmdbPosterUrl } from "@/lib/media-utils";
import type { Episode } from "@/types";
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
export function CalendarPage() {
const [currentDate, setCurrentDate] = useState(new Date());
const [viewMode, setViewMode] = useState<'grid' | 'list'>(
() => (typeof window !== 'undefined' && window.innerWidth < 640 ? 'list' : 'grid')
const [viewMode, setViewMode] = useState<"grid" | "list">(() =>
typeof window !== "undefined" && window.innerWidth < 640 ? "list" : "grid",
);
const [selectedDay, setSelectedDay] = useState<{ date: Date; episodes: Episode[] } | null>(null);
const [selectedDay, setSelectedDay] = useState<{
date: Date;
episodes: Episode[];
} | null>(null);
const monthStart = startOfMonth(currentDate);
const monthEnd = endOfMonth(currentDate);
const startDateStr = format(monthStart, 'yyyy-MM-dd');
const endDateStr = format(monthEnd, 'yyyy-MM-dd');
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 days = useMemo(
() => eachDayOfInterval({ start: monthStart, end: monthEnd }),
[monthStart, monthEnd],
);
const startDayOfWeek = getDay(monthStart);
// Group episodes by date
@@ -33,7 +58,7 @@ export function CalendarPage() {
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 key = format(new Date(ep.air_date), "yyyy-MM-dd");
const existing = map.get(key) || [];
existing.push(ep);
map.set(key, existing);
@@ -54,7 +79,7 @@ export function CalendarPage() {
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="min-w-35 text-center font-medium">
{format(currentDate, 'MMMM yyyy')}
{format(currentDate, "MMMM yyyy")}
</span>
<Button
variant="outline"
@@ -67,10 +92,18 @@ export function CalendarPage() {
<Button
variant="outline"
size="icon"
onClick={() => setViewMode((v) => (v === 'grid' ? 'list' : 'grid'))}
title={viewMode === 'grid' ? 'Switch to list view' : 'Switch to grid view'}
onClick={() => setViewMode((v) => (v === "grid" ? "list" : "grid"))}
title={
viewMode === "grid"
? "Switch to list view"
: "Switch to grid view"
}
>
{viewMode === 'grid' ? <List className="h-4 w-4" /> : <LayoutGrid className="h-4 w-4" />}
{viewMode === "grid" ? (
<List className="h-4 w-4" />
) : (
<LayoutGrid className="h-4 w-4" />
)}
</Button>
</div>
</div>
@@ -84,12 +117,15 @@ export function CalendarPage() {
onClose={() => setSelectedDay(null)}
/>
)}
{viewMode === 'grid' ? (
{viewMode === "grid" ? (
<div className="flex flex-col flex-1 rounded-lg border border-border overflow-hidden min-h-0">
{/* Day headers */}
<div className="grid grid-cols-7 bg-muted/50 shrink-0">
{DAYS.map((day) => (
<div key={day} className="px-2 py-2 text-center text-xs font-medium text-muted-foreground">
<div
key={day}
className="px-2 py-2 text-center text-xs font-medium text-muted-foreground"
>
{day}
</div>
))}
@@ -99,34 +135,44 @@ export function CalendarPage() {
<div className="grid grid-cols-7 grid-rows-6 flex-1 min-h-0">
{/* Empty cells for offset */}
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} className="border-t border-r border-border bg-muted/20" />
<div
key={`empty-${i}`}
className="border-t border-r border-border bg-muted/20"
/>
))}
{days.map((day) => {
const key = format(day, 'yyyy-MM-dd');
const key = format(day, "yyyy-MM-dd");
const dayEpisodes = episodesByDate.get(key) || [];
const isToday = isSameDay(day, new Date());
return (
<div
key={key}
onClick={() => dayEpisodes.length > 0 && setSelectedDay({ date: day, episodes: dayEpisodes })}
onClick={() =>
dayEpisodes.length > 0 &&
setSelectedDay({ date: day, episodes: dayEpisodes })
}
className={`border-t border-r border-border p-1 overflow-hidden flex flex-col min-h-0 ${
isToday ? 'bg-primary/5' : ''
} ${dayEpisodes.length > 0 ? 'cursor-pointer hover:bg-accent/30 transition-colors' : ''}`}
isToday ? "bg-primary/5" : ""
} ${dayEpisodes.length > 0 ? "cursor-pointer hover:bg-accent/30 transition-colors" : ""}`}
>
<span
className={`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] mb-0.5 ${
isToday
? 'bg-primary text-primary-foreground font-bold'
: 'text-muted-foreground'
? "bg-primary text-primary-foreground font-bold"
: "text-muted-foreground"
}`}
>
{format(day, 'd')}
{format(day, "d")}
</span>
<div className="flex gap-0.5 flex-1 min-h-0 overflow-hidden items-start">
{dayEpisodes.slice(0, 3).map((ep) => (
<EpisodeCalendarItem key={ep.id} episode={ep} variant="grid" />
<EpisodeCalendarItem
key={ep.id}
episode={ep}
variant="grid"
/>
))}
{dayEpisodes.length > 3 && (
<span className="text-[9px] text-muted-foreground shrink-0 self-end pb-0.5">
@@ -143,7 +189,7 @@ export function CalendarPage() {
/* List / Agenda view */
<div className="flex flex-col flex-1 overflow-y-auto min-h-0 gap-1">
{days.map((day) => {
const key = format(day, 'yyyy-MM-dd');
const key = format(day, "yyyy-MM-dd");
const dayEpisodes = episodesByDate.get(key) || [];
const isToday = isSameDay(day, new Date());
@@ -152,34 +198,39 @@ export function CalendarPage() {
key={key}
className={`rounded-lg border ${
isToday
? 'border-primary/30 bg-primary/5'
? "border-primary/30 bg-primary/5"
: dayEpisodes.length > 0
? 'border-border'
: 'border-transparent'
? "border-border"
: "border-transparent"
}`}
>
<div
className={`flex items-center gap-3 px-3 py-2 ${
dayEpisodes.length > 0 ? 'border-b border-border/40' : ''
dayEpisodes.length > 0 ? "border-b border-border/40" : ""
}`}
>
<span
className={`inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-sm ${
isToday
? 'bg-primary text-primary-foreground font-bold'
: 'text-muted-foreground'
? "bg-primary text-primary-foreground font-bold"
: "text-muted-foreground"
}`}
>
{format(day, 'd')}
{format(day, "d")}
</span>
<span className={`text-sm ${
isToday ? 'font-medium text-foreground' : 'text-muted-foreground'
}`}>
{format(day, 'EEEE, MMM d')}
<span
className={`text-sm ${
isToday
? "font-medium text-foreground"
: "text-muted-foreground"
}`}
>
{format(day, "EEEE, MMM d")}
</span>
{dayEpisodes.length > 0 && (
<span className="ml-auto text-xs text-muted-foreground">
{dayEpisodes.length} ep{dayEpisodes.length !== 1 ? 's' : ''}
{dayEpisodes.length} ep
{dayEpisodes.length !== 1 ? "s" : ""}
</span>
)}
</div>
@@ -200,14 +251,20 @@ export function CalendarPage() {
);
}
function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; variant?: 'grid' | 'list' | 'dialog' }) {
function EpisodeCalendarItem({
episode,
variant = "list",
}: {
episode: Episode;
variant?: "grid" | "list" | "dialog";
}) {
type EpisodeWithEntry = Episode & {
entry?: { id: number; title?: string; poster_path?: string | null };
};
const ep = episode as EpisodeWithEntry;
const entry = ep.entry;
const entryId = entry?.id;
const entryTitle = entry?.title ?? '';
const entryTitle = entry?.title ?? "";
// Hide episodes with no known entry title
if (!entryTitle) return null;
@@ -215,18 +272,17 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
const seasonId = episode.season_id;
const seasonNumber = episode.season?.season_number ?? null;
const seasonLabel = seasonNumber != null
? `S${String(seasonNumber).padStart(2, '0')}`
: '';
const episodeLabel = `E${String(episode.episode_number).padStart(2, '0')}`;
const seasonLabel =
seasonNumber != null ? `S${String(seasonNumber).padStart(2, "0")}` : "";
const episodeLabel = `E${String(episode.episode_number).padStart(2, "0")}`;
const thumbSrc = entry?.poster_path
? getTmdbPosterUrl(entry.poster_path, 'w92')
? getTmdbPosterUrl(entry.poster_path, "w92")
: undefined;
const isMovie = entry && !(entry as any).is_tvseries;
if (variant === 'grid') {
if (variant === "grid") {
const gridContent = (
<div className="w-14 shrink-0 rounded overflow-hidden bg-primary/10 hover:bg-primary/20 transition-colors cursor-pointer">
{thumbSrc ? (
@@ -237,7 +293,9 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
/>
) : (
<div className="w-full aspect-2/3 bg-muted/40 flex items-center justify-center">
<span className="text-[7px] text-muted-foreground text-center px-0.5 leading-tight">{entryTitle}</span>
<span className="text-[7px] text-muted-foreground text-center px-0.5 leading-tight">
{entryTitle}
</span>
</div>
)}
<p className="text-[7px] text-center text-muted-foreground tabular-nums py-0.5 leading-tight truncate px-0.5">
@@ -250,7 +308,10 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
<Tooltip>
<TooltipTrigger asChild>
{entryId ? (
<Link to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`} className="block">
<Link
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="block"
>
{gridContent}
</Link>
) : (
@@ -274,7 +335,7 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
);
}
if (variant === 'dialog') {
if (variant === "dialog") {
const dialogContent = (
<div className="rounded-lg overflow-hidden bg-primary/10 hover:bg-primary/20 transition-colors cursor-pointer">
{thumbSrc ? (
@@ -285,25 +346,35 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
/>
) : (
<div className="w-full aspect-2/3 bg-muted/40 flex items-center justify-center p-2">
<span className="text-xs text-muted-foreground text-center leading-tight">{entryTitle}</span>
<span className="text-xs text-muted-foreground text-center leading-tight">
{entryTitle}
</span>
</div>
)}
<div className="p-1.5">
<p className="text-xs font-medium leading-tight truncate">{entryTitle}</p>
<p className="text-xs font-medium leading-tight truncate">
{entryTitle}
</p>
{!isMovie && (
<p className="text-[10px] text-muted-foreground tabular-nums leading-tight mt-0.5">
{seasonLabel}{episodeLabel}
{seasonLabel}
{episodeLabel}
</p>
)}
{episode.name && (
<p className="text-[10px] text-muted-foreground leading-tight truncate mt-0.5">{episode.name}</p>
<p className="text-[10px] text-muted-foreground leading-tight truncate mt-0.5">
{episode.name}
</p>
)}
</div>
</div>
);
return entryId ? (
<Link to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`} className="block">
<Link
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="block"
>
{dialogContent}
</Link>
) : (
@@ -362,12 +433,20 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
);
}
function DayDialog({ date, episodes, onClose }: { date: Date; episodes: Episode[]; onClose: () => void }) {
function DayDialog({
date,
episodes,
onClose,
}: {
date: Date;
episodes: Episode[];
onClose: () => void;
}) {
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{format(date, 'EEEE, MMMM d')}</DialogTitle>
<DialogTitle>{format(date, "EEEE, MMMM d")}</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 max-h-[70vh] overflow-y-auto pr-1">
{episodes.map((ep) => (
+19 -14
View File
@@ -1,26 +1,26 @@
import { useState, useMemo, useCallback, useEffect } from 'react';
import { useCollections } from '@/hooks/useCollections';
import { useDebounce } from '@/hooks/useDebounce';
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';
import { useState, useMemo, useCallback, useEffect } from "react";
import { useCollections } from "@/hooks/useCollections";
import { useDebounce } from "@/hooks/useDebounce";
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";
const PAGE_SIZE = 24;
export function CollectionsPage() {
const { data: collections = [], isLoading } = useCollections();
const [search, setSearch] = useState('');
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [filter, setFilter] = useState<'all' | 'official' | 'custom'>('all');
const [filter, setFilter] = useState<"all" | "official" | "custom">("all");
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const filtered = useMemo(() => {
let result = collections;
if (filter === 'official') {
if (filter === "official") {
result = result.filter((c) => !c.is_user_collection);
} else if (filter === 'custom') {
} else if (filter === "custom") {
result = result.filter((c) => c.is_user_collection);
}
@@ -38,7 +38,7 @@ export function CollectionsPage() {
const paginatedCollections = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
[filtered, visibleCount],
);
const hasMore = visibleCount < filtered.length;
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
@@ -60,7 +60,7 @@ export function CollectionsPage() {
<Tabs
value={filter}
onValueChange={(v) => setFilter(v as 'all' | 'official' | 'custom')}
onValueChange={(v) => setFilter(v as "all" | "official" | "custom")}
>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
@@ -70,7 +70,12 @@ export function CollectionsPage() {
</Tabs>
</div>
<CollectionsGrid collections={paginatedCollections} isLoading={isLoading} hasMore={hasMore} onLoadMore={loadMore} />
<CollectionsGrid
collections={paginatedCollections}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={loadMore}
/>
</div>
);
}
+48 -33
View File
@@ -1,19 +1,19 @@
import { useMemo, useState } 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';
import { WatchActivityChart } from '@/components/dashboard/WatchActivityChart';
import { WatchTimeChart } from '@/components/dashboard/WatchTimeChart';
import { RatingsChart } from '@/components/dashboard/RatingsChart';
import { TopGenresChart } from '@/components/dashboard/TopGenresChart';
import { CouchDayChart } from '@/components/dashboard/CouchDayChart';
import { LibraryGrowthChart } from '@/components/dashboard/LibraryGrowthChart';
import { MediaTypeChart } from '@/components/dashboard/MediaTypeChart';
import { useMemo, useState } 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";
import { WatchActivityChart } from "@/components/dashboard/WatchActivityChart";
import { WatchTimeChart } from "@/components/dashboard/WatchTimeChart";
import { RatingsChart } from "@/components/dashboard/RatingsChart";
import { TopGenresChart } from "@/components/dashboard/TopGenresChart";
import { CouchDayChart } from "@/components/dashboard/CouchDayChart";
import { LibraryGrowthChart } from "@/components/dashboard/LibraryGrowthChart";
import { MediaTypeChart } from "@/components/dashboard/MediaTypeChart";
export function DashboardPage() {
useLibrary();
@@ -21,43 +21,58 @@ export function DashboardPage() {
const allEntries = useLibraryEntries();
const [watchYear, setWatchYear] = useState(new Date().getFullYear());
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 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',
title: "Movies",
value: movies.length,
icon: Film,
color: 'text-blue-500',
color: "text-blue-500",
},
{
title: 'TV Series',
title: "TV Series",
value: tvSeries.length,
icon: Tv,
color: 'text-green-500',
color: "text-green-500",
},
{
title: 'Favorites',
title: "Favorites",
value: favorites.length,
icon: Heart,
color: 'text-red-500',
color: "text-red-500",
},
{
title: 'Watchlist',
title: "Watchlist",
value: watchlist.length,
icon: ListVideo,
color: 'text-purple-500',
color: "text-purple-500",
},
{
title: 'Watch Time',
title: "Watch Time",
value: stats
? formatRuntime((parseInt(stats.series || '0') || 0) + (parseInt(stats.movies || '0') || 0))
: '0h',
? formatRuntime(
(parseInt(stats.series || "0") || 0) +
(parseInt(stats.movies || "0") || 0),
)
: "0h",
icon: Clock,
color: 'text-orange-500',
color: "text-orange-500",
},
];
@@ -108,7 +123,7 @@ export function DashboardPage() {
.sort(
(a, b) =>
new Date(b.date_last_seen!).getTime() -
new Date(a.date_last_seen!).getTime()
new Date(a.date_last_seen!).getTime(),
)
.slice(0, 14)
.map((entry, index) => (
+34 -28
View File
@@ -1,41 +1,41 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import { useInfiniteQuery } from '@tanstack/react-query';
import { tmdbApi } from '@/api/tmdb';
import { useLibrary } from '@/hooks/useEntries';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { EntryCard, EntryCardSkeleton } from '@/components/entries/EntryCard';
import { Loader2 } from 'lucide-react';
import type { TmdbEntry, TmdbPaginatedResponse } from '@/types';
import { useState, useEffect, useRef, useCallback } from "react";
import { useParams } from "react-router-dom";
import { useInfiniteQuery } from "@tanstack/react-query";
import { tmdbApi } from "@/api/tmdb";
import { useLibrary } from "@/hooks/useEntries";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { EntryCard, EntryCardSkeleton } from "@/components/entries/EntryCard";
import { Loader2 } from "lucide-react";
import type { TmdbEntry, TmdbPaginatedResponse } from "@/types";
const CATEGORY_LABELS: Record<string, string> = {
trending: 'Trending',
popular: 'Popular',
'top-rated': 'Top Rated',
upcoming: 'Upcoming',
trending: "Trending",
popular: "Popular",
"top-rated": "Top Rated",
upcoming: "Upcoming",
};
type MediaTab = 'movie' | 'tv';
type MediaTab = "movie" | "tv";
function useCategoryQuery(category: string, mediaType: MediaTab) {
return useInfiniteQuery<TmdbPaginatedResponse<TmdbEntry>>({
queryKey: ['tmdb', category, mediaType],
queryKey: ["tmdb", category, mediaType],
queryFn: ({ pageParam }) => {
const page = pageParam as number;
switch (category) {
case 'trending':
return mediaType === 'movie'
case "trending":
return mediaType === "movie"
? tmdbApi.getTrendingMovies(page)
: tmdbApi.getTrendingTv(page);
case 'popular':
return mediaType === 'movie'
case "popular":
return mediaType === "movie"
? tmdbApi.getPopularMovies(page)
: tmdbApi.getPopularTv(page);
case 'top-rated':
return mediaType === 'movie'
case "top-rated":
return mediaType === "movie"
? tmdbApi.getTopRatedMovies(page)
: tmdbApi.getTopRatedTv(page);
case 'upcoming':
case "upcoming":
return tmdbApi.getUpcomingMovies(page);
default:
return tmdbApi.getPopularMovies(page);
@@ -48,20 +48,24 @@ function useCategoryQuery(category: string, mediaType: MediaTab) {
}
export function DiscoverPage() {
const { category = 'trending' } = useParams<{ category: string }>();
const [mediaType, setMediaType] = useState<MediaTab>('movie');
const { category = "trending" } = useParams<{ category: string }>();
const [mediaType, setMediaType] = useState<MediaTab>("movie");
const sentinelRef = useRef<HTMLDivElement>(null);
useLibrary();
const isUpcoming = category === 'upcoming';
const isUpcoming = category === "upcoming";
const query = useCategoryQuery(category, mediaType);
const entries = query.data?.pages.flatMap((p) => p.results) ?? [];
// Infinite scroll via IntersectionObserver
const handleIntersect = useCallback(
(entries: IntersectionObserverEntry[]) => {
if (entries[0]?.isIntersecting && query.hasNextPage && !query.isFetchingNextPage) {
if (
entries[0]?.isIntersecting &&
query.hasNextPage &&
!query.isFetchingNextPage
) {
query.fetchNextPage();
}
},
@@ -71,12 +75,14 @@ export function DiscoverPage() {
useEffect(() => {
const el = sentinelRef.current;
if (!el) return;
const observer = new IntersectionObserver(handleIntersect, { rootMargin: '400px' });
const observer = new IntersectionObserver(handleIntersect, {
rootMargin: "400px",
});
observer.observe(el);
return () => observer.disconnect();
}, [handleIntersect]);
const title = CATEGORY_LABELS[category] || 'Discover';
const title = CATEGORY_LABELS[category] || "Discover";
return (
<div className="space-y-6 animate-page-enter">
+97 -57
View File
@@ -1,69 +1,83 @@
import { useState, useMemo, useEffect, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useEntry, useEntryCredits } from '@/hooks/useEntries';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useState, useMemo, useEffect, useRef } from "react";
import { useParams, Link } from "react-router-dom";
import { useEntry, useEntryCredits } from "@/hooks/useEntries";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { getProfileUrl } from '@/lib/media-utils';
import { ArrowUpDown } from 'lucide-react';
import type { Credit } from '@/types';
} from "@/components/ui/select";
import { getProfileUrl } from "@/lib/media-utils";
import { ArrowUpDown } from "lucide-react";
import type { Credit } from "@/types";
type SortField = 'order' | 'popularity' | 'name' | 'birthday' | 'gender' | 'episode_count';
type SortDir = 'asc' | 'desc';
type CastFilter = 'all' | 'cast' | 'crew';
type SortField =
| "order"
| "popularity"
| "name"
| "birthday"
| "gender"
| "episode_count";
type SortDir = "asc" | "desc";
type CastFilter = "all" | "cast" | "crew";
const PAGE_SIZE = 24;
const SORT_LABELS: Record<SortField, string> = {
order: 'Credit Order',
popularity: 'Popularity',
name: 'Name',
birthday: 'Birthday',
gender: 'Gender',
episode_count: 'Episodes',
order: "Credit Order",
popularity: "Popularity",
name: "Name",
birthday: "Birthday",
gender: "Gender",
episode_count: "Episodes",
};
const FILTER_LABELS: Record<CastFilter, string> = {
all: 'All',
cast: 'Cast',
crew: 'Crew',
all: "All",
cast: "Cast",
crew: "Crew",
};
function sortCredits(credits: Credit[], field: SortField, dir: SortDir): Credit[] {
function sortCredits(
credits: Credit[],
field: SortField,
dir: SortDir,
): Credit[] {
return [...credits].sort((a, b) => {
let cmp = 0;
switch (field) {
case 'order':
case "order":
cmp = (a.order ?? 9999) - (b.order ?? 9999);
break;
case 'popularity':
case "popularity":
cmp = (b.people?.popularity ?? 0) - (a.people?.popularity ?? 0);
break;
case 'name':
cmp = (a.people?.name ?? '').localeCompare(b.people?.name ?? '');
case "name":
cmp = (a.people?.name ?? "").localeCompare(b.people?.name ?? "");
break;
case 'birthday': {
const da = a.people?.birthday ? new Date(a.people.birthday).getTime() : 0;
const db = b.people?.birthday ? new Date(b.people.birthday).getTime() : 0;
case "birthday": {
const da = a.people?.birthday
? new Date(a.people.birthday).getTime()
: 0;
const db = b.people?.birthday
? new Date(b.people.birthday).getTime()
: 0;
cmp = da - db;
break;
}
case 'gender':
case "gender":
cmp = (a.people?.gender ?? 0) - (b.people?.gender ?? 0);
break;
case 'episode_count':
case "episode_count":
cmp = (b.episode_count ?? 0) - (a.episode_count ?? 0);
break;
}
return dir === 'asc' ? cmp : -cmp;
return dir === "asc" ? cmp : -cmp;
});
}
@@ -71,38 +85,51 @@ export function EntryCastsPage() {
const { id } = useParams<{ id: string }>();
const entryId = parseInt(id!, 10);
const { data: entry, isLoading } = useEntry(entryId);
const { data: allCredits = [], isLoading: creditsLoading } = useEntryCredits(entryId);
const { data: allCredits = [], isLoading: creditsLoading } =
useEntryCredits(entryId);
const [sortField, setSortField] = useState<SortField>('episode_count');
const [sortDir, setSortDir] = useState<SortDir>('asc');
const [filter, setFilter] = useState<CastFilter>('cast');
const [search, setSearch] = useState('');
const [sortField, setSortField] = useState<SortField>("episode_count");
const [sortDir, setSortDir] = useState<SortDir>("asc");
const [filter, setFilter] = useState<CastFilter>("cast");
const [search, setSearch] = useState("");
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const filtered = useMemo(() => {
if (!allCredits) return [];
let result = allCredits;
if (filter === 'cast') result = result.filter((c) => c.cast_type === 'cast');
else if (filter === 'crew') result = result.filter((c) => c.cast_type === 'crew');
if (filter === "cast")
result = result.filter((c) => c.cast_type === "cast");
else if (filter === "crew")
result = result.filter((c) => c.cast_type === "crew");
if (search.trim()) {
const q = search.trim().toLowerCase();
result = result.filter((c) => {
const name = c.people?.name?.toLowerCase() ?? '';
const role = (c.cast_type === 'cast' ? c.character : (c.job || c.department))?.toLowerCase() ?? '';
const name = c.people?.name?.toLowerCase() ?? "";
const role =
(c.cast_type === "cast"
? c.character
: c.job || c.department
)?.toLowerCase() ?? "";
return name.includes(q) || role.includes(q);
});
}
return result;
}, [allCredits, filter, search]);
const sorted = useMemo(() => sortCredits(filtered, sortField, sortDir), [filtered, sortField, sortDir]);
const sorted = useMemo(
() => sortCredits(filtered, sortField, sortDir),
[filtered, sortField, sortDir],
);
// Reset visible window whenever filter/sort/search changes
useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [filter, sortField, sortDir, search]);
const visible = useMemo(() => sorted.slice(0, visibleCount), [sorted, visibleCount]);
const visible = useMemo(
() => sorted.slice(0, visibleCount),
[sorted, visibleCount],
);
const hasMore = visibleCount < sorted.length;
// IntersectionObserver-based lazy load on scroll
@@ -117,7 +144,7 @@ export function EntryCastsPage() {
setVisibleCount((c) => Math.min(c + PAGE_SIZE, sorted.length));
}
},
{ rootMargin: '400px 0px' }
{ rootMargin: "400px 0px" },
);
observer.observe(node);
return () => observer.disconnect();
@@ -165,12 +192,15 @@ export function EntryCastsPage() {
className="w-48"
/>
<span className="text-sm text-muted-foreground whitespace-nowrap">
{sorted.length} {sorted.length === 1 ? 'credit' : 'credits'}
{sorted.length} {sorted.length === 1 ? "credit" : "credits"}
</span>
{/* Right: filter + sort */}
<div className="flex items-center gap-3 ml-auto">
<Select value={filter} onValueChange={(v) => setFilter(v as CastFilter)}>
<Select
value={filter}
onValueChange={(v) => setFilter(v as CastFilter)}
>
<SelectTrigger className="w-32">
<SelectValue>{FILTER_LABELS[filter]}</SelectValue>
</SelectTrigger>
@@ -181,7 +211,10 @@ export function EntryCastsPage() {
</SelectContent>
</Select>
<Select value={sortField} onValueChange={(v) => setSortField(v as SortField)}>
<Select
value={sortField}
onValueChange={(v) => setSortField(v as SortField)}
>
<SelectTrigger className="w-40">
<SelectValue>{SORT_LABELS[sortField]}</SelectValue>
</SelectTrigger>
@@ -199,7 +232,7 @@ export function EntryCastsPage() {
variant="ghost"
size="icon"
className="h-9 w-9"
onClick={() => setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))}
onClick={() => setSortDir((d) => (d === "asc" ? "desc" : "asc"))}
>
<ArrowUpDown className="h-4 w-4" />
</Button>
@@ -208,7 +241,9 @@ export function EntryCastsPage() {
{/* Grid */}
{sorted.length === 0 ? (
<p className="text-center text-muted-foreground py-12">No credits found.</p>
<p className="text-center text-muted-foreground py-12">
No credits found.
</p>
) : (
<>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
@@ -219,7 +254,9 @@ export function EntryCastsPage() {
{hasMore && (
<div ref={sentinelRef} className="flex justify-center py-6">
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 w-full">
{Array.from({ length: Math.min(PAGE_SIZE, sorted.length - visibleCount) }).map((_, i) => (
{Array.from({
length: Math.min(PAGE_SIZE, sorted.length - visibleCount),
}).map((_, i) => (
<div key={i} className="flex flex-col items-center gap-2 p-2">
<Skeleton className="h-32 w-32 rounded-full" />
<Skeleton className="h-3 w-16" />
@@ -244,7 +281,7 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) {
: `/people/tmdb/${credit.people?.tmdb_id ?? credit.people_id}`;
const roleLabel =
credit.cast_type === 'cast'
credit.cast_type === "cast"
? credit.character
: credit.job || credit.department;
@@ -257,13 +294,15 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) {
<AvatarImage src={profileUrl} alt={credit.people?.name} />
<AvatarFallback className="text-sm">
{credit.people?.name
?.split(' ')
?.split(" ")
.map((n) => n[0])
.join('')}
.join("")}
</AvatarFallback>
</Avatar>
<div className="min-w-0 w-full">
<p className="text-sm font-medium leading-tight line-clamp-2">{credit.people?.name}</p>
<p className="text-sm font-medium leading-tight line-clamp-2">
{credit.people?.name}
</p>
{roleLabel && (
<p className="text-xs text-muted-foreground leading-tight line-clamp-1 mt-0.5">
{roleLabel}
@@ -271,7 +310,8 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) {
)}
{isTv && credit.episode_count != null && credit.episode_count > 0 && (
<p className="text-xs text-muted-foreground/70 leading-tight mt-0.5">
{credit.episode_count} {credit.episode_count === 1 ? 'episode' : 'episodes'}
{credit.episode_count}{" "}
{credit.episode_count === 1 ? "episode" : "episodes"}
</p>
)}
</div>
+68 -37
View File
@@ -1,26 +1,32 @@
import { useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { seasonsApi } from '@/api/seasons';
import { useSeason } from '@/hooks/useSeasons';
import { useEntry, useEntrySeasons } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { seasonsApi } from "@/api/seasons";
import { useSeason } from "@/hooks/useSeasons";
import { useEntry, useEntrySeasons } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import {
useEpisodeSeenByEpisode,
useDeleteEpisodeSeen,
} from '@/hooks/useEpisodeSeen';
import { StreamingDialog } from '@/components/streaming/StreamingDialog';
import { useStreamingStore } from '@/stores/useStreamingStore';
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 { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog';
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog';
import { CastList } from '@/components/entries/CastList';
import { Eye, ChevronLeft, ChevronRight, Clock, PlayCircle } from 'lucide-react';
import { getTmdbPosterUrl, formatDate, formatRuntime } from '@/lib/media-utils';
import type { Episode, EpisodeSeen } from '@/types';
} from "@/hooks/useEpisodeSeen";
import { StreamingDialog } from "@/components/streaming/StreamingDialog";
import { useStreamingStore } from "@/stores/useStreamingStore";
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 { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { CastList } from "@/components/entries/CastList";
import {
Eye,
ChevronLeft,
ChevronRight,
Clock,
PlayCircle,
} from "lucide-react";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils";
import type { Episode, EpisodeSeen } from "@/types";
export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{
@@ -31,14 +37,16 @@ export function EpisodePage() {
const navigate = useNavigate();
const { data: episodes = [] } = useQuery({
queryKey: ['seasons', parseInt(seasonId!, 10), 'episodes'],
queryKey: ["seasons", parseInt(seasonId!, 10), "episodes"],
queryFn: () => seasonsApi.getEpisodes(parseInt(seasonId!, 10)),
});
const { data: season } = useSeason(parseInt(seasonId!, 10));
const { data: entry } = useEntry(parseInt(entryId!, 10));
const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10));
const entryTitle = entry?.title ?? useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const entryTitle =
entry?.title ??
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const seasonNumber = season?.season_number;
const { initialize, play } = useStreamingStore();
@@ -46,7 +54,9 @@ export function EpisodePage() {
const epId = parseInt(episodeId!, 10);
const entryIdNum = parseInt(entryId!, 10);
const episode: Episode | undefined = episodes.find((ep: Episode) => ep.id === epId);
const episode: Episode | undefined = episodes.find(
(ep: Episode) => ep.id === epId,
);
const { data: watchHistory = [] } = useEpisodeSeenByEpisode(epId);
const deleteEpisodeSeen = useDeleteEpisodeSeen();
@@ -56,7 +66,8 @@ export function EpisodePage() {
// Find prev/next episode
const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId);
const prevEpisode: Episode | undefined = currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const prevEpisode: Episode | undefined =
currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const nextEpisode: Episode | undefined =
currentIndex < episodes.length - 1 ? episodes[currentIndex + 1] : undefined;
@@ -78,24 +89,27 @@ export function EpisodePage() {
to={`/entry/${entryId}`}
className="hover:text-foreground transition-colors truncate max-w-50"
>
{entryTitle || 'Entry'}
{entryTitle || "Entry"}
</Link>
<span>/</span>
<Link
to={`/entry/${entryId}/season/${seasonId}`}
className="hover:text-foreground transition-colors"
>
Season {seasonNumber ?? '?'}
Season {seasonNumber ?? "?"}
</Link>
<span>/</span>
<span className="text-foreground font-medium">Episode {episode.episode_number}</span>
<span className="text-foreground font-medium">
Episode {episode.episode_number}
</span>
</div>
{/* Top bar: nav breadcrumb + Mark Watched */}
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="font-medium text-foreground">
S{String(seasonNumber ?? 0).padStart(2, '0')} E{String(episode.episode_number).padStart(2, '0')}
S{String(seasonNumber ?? 0).padStart(2, "0")} E
{String(episode.episode_number).padStart(2, "0")}
</span>
</div>
<Button size="sm" onClick={() => setShowAddDialog(true)}>
@@ -112,7 +126,7 @@ export function EpisodePage() {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
type: 'tv',
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: seasonNumber,
@@ -122,14 +136,16 @@ export function EpisodePage() {
}}
>
<img
src={getTmdbPosterUrl(episode.still_path, 'w1280')}
src={getTmdbPosterUrl(episode.still_path, "w1280")}
alt={episode.name}
className="w-full max-h-96 object-cover transition-[filter] group-hover:brightness-50"
/>
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<div className="flex items-center gap-2 bg-black/60 backdrop-blur-sm rounded-full px-5 py-2.5">
<PlayCircle className="h-6 w-6 text-white" />
<span className="text-white font-medium text-sm">Watch Episode</span>
<span className="text-white font-medium text-sm">
Watch Episode
</span>
</div>
</div>
</div>
@@ -171,7 +187,9 @@ export function EpisodePage() {
<EpisodeWatchHistory
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as EpisodeSeen | undefined;
const rec = watchHistory.find((r) => r.id === id) as
| EpisodeSeen
| undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
@@ -188,7 +206,9 @@ export function EpisodePage() {
size="sm"
className="flex items-center gap-1 max-w-60"
onClick={() =>
navigate(`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`)
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`,
)
}
>
<ChevronLeft className="h-4 w-4 shrink-0" />
@@ -205,7 +225,9 @@ export function EpisodePage() {
size="sm"
className="flex items-center gap-1 max-w-60 ml-auto"
onClick={() =>
navigate(`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`)
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`,
)
}
>
<span className="truncate">
@@ -234,7 +256,9 @@ export function EpisodePage() {
{editRecord && (
<EpisodeSeenEditDialog
open={!!editRecord}
onOpenChange={(open) => { if (!open) setEditRecord(null); }}
onOpenChange={(open) => {
if (!open) setEditRecord(null);
}}
mode="edit"
record={editRecord}
entryId={entryIdNum}
@@ -245,14 +269,21 @@ export function EpisodePage() {
{/* Delete confirm dialog */}
<ConfirmDialog
open={deleteTarget !== null}
onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null);
}}
title="Delete Watch Record"
description="Are you sure you want to remove this watch record? This cannot be undone."
confirmLabel="Delete"
variant="destructive"
onConfirm={() => {
if (deleteTarget !== null) {
deleteEpisodeSeen.mutate({ id: deleteTarget, entryId: entryIdNum, episodeId: epId, seasonId: parseInt(seasonId!, 10) });
deleteEpisodeSeen.mutate({
id: deleteTarget,
entryId: entryIdNum,
episodeId: epId,
seasonId: parseInt(seasonId!, 10),
});
setDeleteTarget(null);
}
}}
+35 -29
View File
@@ -1,22 +1,26 @@
import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { useDebounce } from '@/hooks/useDebounce';
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';
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
import { useLibrary } from "@/hooks/useEntries";
import { useLibraryEntries } from "@/stores/useLibraryStore";
import { useDebounce } from "@/hooks/useDebounce";
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";
const PAGE_SIZE = 36;
export function MediaPage() {
const { isLoading } = useLibrary();
const [search, setSearch] = useState('');
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [mediaType, setMediaType] = useState<'all' | 'poster' | 'backdrop' | 'logo'>('all');
const [customFilter, setCustomFilter] = useState<'all' | 'custom' | 'official'>('custom');
const [mediaType, setMediaType] = useState<
"all" | "poster" | "backdrop" | "logo"
>("all");
const [customFilter, setCustomFilter] = useState<
"all" | "custom" | "official"
>("custom");
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const entries = useLibraryEntries();
@@ -34,7 +38,7 @@ export function MediaPage() {
if (node) observerRef.current.observe(node);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isLoading]
[isLoading],
);
useEffect(() => {
@@ -54,13 +58,13 @@ export function MediaPage() {
const filtered = useMemo(() => {
let result = allMedias;
if (mediaType !== 'all') {
if (mediaType !== "all") {
result = result.filter((m) => m.type === mediaType);
}
if (customFilter === 'custom') {
if (customFilter === "custom") {
result = result.filter((m) => m.is_custom);
} else if (customFilter === 'official') {
} else if (customFilter === "official") {
result = result.filter((m) => !m.is_custom);
}
@@ -78,7 +82,7 @@ export function MediaPage() {
const paginatedMedia = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
[filtered, visibleCount],
);
const hasMore = visibleCount < filtered.length;
@@ -129,9 +133,9 @@ export function MediaPage() {
<Skeleton
key={i}
className={
mediaType === 'backdrop'
? 'aspect-video w-full rounded-lg'
: 'aspect-[2/3] w-full rounded-lg'
mediaType === "backdrop"
? "aspect-video w-full rounded-lg"
: "aspect-[2/3] w-full rounded-lg"
}
/>
))}
@@ -143,27 +147,29 @@ export function MediaPage() {
) : (
<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'
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"
}`}
>
{paginatedMedia.map((media, index) => (
<div
key={media.id}
ref={index === paginatedMedia.length - 1 ? lastItemRef : undefined}
ref={
index === paginatedMedia.length - 1 ? lastItemRef : undefined
}
className="group relative overflow-hidden rounded-lg bg-muted"
>
<img
src={getMediaUrl(
'entries',
"entries",
`${media.type}s`,
'preview',
media.path
"preview",
media.path,
)}
alt={media.entryTitle}
className={`w-full object-cover ${
media.type === 'backdrop' ? 'aspect-video' : 'aspect-[2/3]'
media.type === "backdrop" ? "aspect-video" : "aspect-[2/3]"
}`}
loading="lazy"
/>
+50 -26
View File
@@ -1,22 +1,22 @@
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { usePopularPeople, useTmdbSearchPeople } from '@/hooks/useTmdb';
import { useLocalPeopleInfinite } from '@/hooks/usePeople';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Search, Heart } from 'lucide-react';
import { getProfileUrl } from '@/lib/media-utils';
import { useState, useCallback, useRef, useEffect, useMemo } from "react";
import { Link } from "react-router-dom";
import { usePopularPeople, useTmdbSearchPeople } from "@/hooks/useTmdb";
import { useLocalPeopleInfinite } from "@/hooks/usePeople";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Search, Heart } from "lucide-react";
import { getProfileUrl } from "@/lib/media-utils";
type PeopleFilter = 'all' | 'favorite';
type PeopleFilter = "all" | "favorite";
export function PeoplePage() {
const [search, setSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [filter, setFilter] = useState<PeopleFilter>('all');
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [filter, setFilter] = useState<PeopleFilter>("all");
const [localOnly, setLocalOnly] = useState(false);
// Debounce search input
@@ -28,16 +28,21 @@ export function PeoplePage() {
const isSearching = debouncedSearch.length > 0;
const popularQuery = usePopularPeople();
const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? '' : debouncedSearch);
const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? "" : debouncedSearch);
// Paginated local people (handles both search and browse)
const localPeopleQuery = useLocalPeopleInfinite(
localOnly ? debouncedSearch : '',
localOnly ? debouncedSearch : "",
localOnly,
);
// For TMDB mode, use infinite scroll queries
const activeQuery = isSearching && !localOnly ? tmdbSearchQuery : !localOnly ? popularQuery : null;
const activeQuery =
isSearching && !localOnly
? tmdbSearchQuery
: !localOnly
? popularQuery
: null;
const tmdbPeople = activeQuery?.data?.pages.flatMap((p) => p.results) ?? [];
// Flatten paginated local results
@@ -49,7 +54,7 @@ export function PeoplePage() {
// Apply client-side favorite filter
const filteredLocalPeople = useMemo(() => {
if (!localOnly) return [];
if (filter === 'favorite') {
if (filter === "favorite") {
return allLocalPeople.filter((p: any) => p.favorite);
}
return allLocalPeople;
@@ -68,16 +73,31 @@ export function PeoplePage() {
observerRef.current = new IntersectionObserver((entries) => {
if (!entries[0].isIntersecting) return;
if (localOnly) {
if (localPeopleQuery.hasNextPage && !localPeopleQuery.isFetchingNextPage) {
if (
localPeopleQuery.hasNextPage &&
!localPeopleQuery.isFetchingNextPage
) {
localPeopleQuery.fetchNextPage();
}
} else if (activeQuery && !activeQuery.isFetchingNextPage && activeQuery.hasNextPage) {
} else if (
activeQuery &&
!activeQuery.isFetchingNextPage &&
activeQuery.hasNextPage
) {
activeQuery.fetchNextPage();
}
});
observerRef.current.observe(node);
},
[localOnly, localPeopleQuery.hasNextPage, localPeopleQuery.isFetchingNextPage, localPeopleQuery.fetchNextPage, activeQuery?.isFetchingNextPage, activeQuery?.hasNextPage, activeQuery?.fetchNextPage]
[
localOnly,
localPeopleQuery.hasNextPage,
localPeopleQuery.isFetchingNextPage,
localPeopleQuery.fetchNextPage,
activeQuery?.isFetchingNextPage,
activeQuery?.hasNextPage,
activeQuery?.fetchNextPage,
],
);
useEffect(() => {
@@ -160,7 +180,11 @@ export function PeoplePage() {
style={{ animationDelay: `${Math.min(index * 20, 300)}ms` }}
>
<Link
to={localOnly ? `/people/${person.id}` : `/people/tmdb/${person.id}`}
to={
localOnly
? `/people/${person.id}`
: `/people/tmdb/${person.id}`
}
className="group flex flex-col items-center gap-2 text-center"
>
<div className="relative">
@@ -171,9 +195,9 @@ export function PeoplePage() {
/>
<AvatarFallback>
{person.name
.split(' ')
.split(" ")
.map((n: string) => n[0])
.join('')}
.join("")}
</AvatarFallback>
</Avatar>
{person.favorite && (
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff. Show more