Author SHA1 Message Date
X4Lo 3144bd96c9 Add Tauri v2 desktop app alongside Electron
- New tauri/ project: frameless 1280x800 window, loads the Vite dev
  server in dev and tauri/frontend_build in release builds.
- Starts the backend on launch (node server.js in dev, pkg backend.exe
  sidecar in release) and stops it on exit through a Windows job
  object; reuses a backend already listening on port 4000.
- Custom title bar works in Tauri (minimize, maximize, close, drag
  region) with the matching window capabilities.
- react_frontend: dev:tauri / build:tauri scripts, shared platform
  flags so Electron and Tauri builds both use the local API and hash
  router. Web and Electron builds are unchanged.
- tauri/README.md: prerequisites, dev, build, and gaps vs Electron.
2026-11-05 18:27:40 +00:00
X4Lo 06bf902ad3 Merge pull request 'Redesign season and episode pages, add list/card views' (#7) from feat/season-episode-redesign into master
Reviewed-on: #7
2026-11-05 17:49:19 +00:00
X4Lo be248d7513 Redesign season and episode pages, add list/card views 2026-11-05 17:48:44 +00:00
X4Lo d0cd1cd94b Merge pull request 'Add history page with list, timeline and year in review' (#6) from feat/history-page into master
Reviewed-on: #6
2026-11-05 16:21:09 +00:00
36 changed files with 6497 additions and 552 deletions

No files matched your search

+3
View File
@@ -6,6 +6,8 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"dev:tauri": "cross-env VITE_TAURI=true vite",
"build:tauri": "cross-env VITE_TAURI=true vite build --outDir ../tauri/frontend_build --emptyOutDir",
"build:electron": "cross-env VITE_ELECTRON=true vite build --outDir ../electron/frontend_build", "build:electron": "cross-env VITE_ELECTRON=true vite build --outDir ../electron/frontend_build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview"
@@ -15,6 +17,7 @@
"@fontsource-variable/geist": "^5.2.8", "@fontsource-variable/geist": "^5.2.8",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.2.2",
"@tanstack/react-query": "^5.95.2", "@tanstack/react-query": "^5.95.2",
"@tauri-apps/api": "^2.12.4",
"axios": "^1.14.0", "axios": "^1.14.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
+8
View File
@@ -51,6 +51,9 @@ importers:
'@tanstack/react-query': '@tanstack/react-query':
specifier: ^5.95.2 specifier: ^5.95.2
version: 5.100.8(react@19.2.5) version: 5.100.8(react@19.2.5)
'@tauri-apps/api':
specifier: ^2.12.4
version: 2.12.4
axios: axios:
specifier: ^1.20.0 specifier: ^1.20.0
version: 1.21.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0) version: 1.21.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0)
@@ -798,6 +801,9 @@ packages:
peerDependencies: peerDependencies:
react: ^18 || ^19 react: ^18 || ^19
'@tauri-apps/api@2.12.4':
resolution: {integrity: sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==}
'@ts-morph/common@0.27.0': '@ts-morph/common@0.27.0':
resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==} resolution: {integrity: sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ==}
@@ -3435,6 +3441,8 @@ snapshots:
'@tanstack/query-core': 5.100.8 '@tanstack/query-core': 5.100.8
react: 19.2.5 react: 19.2.5
'@tauri-apps/api@2.12.4': {}
'@ts-morph/common@0.27.0': '@ts-morph/common@0.27.0':
dependencies: dependencies:
fast-glob: 3.3.3 fast-glob: 3.3.3
@@ -0,0 +1,178 @@
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
/**
* Full-bleed hero used by the season and episode pages: a backdrop that fades
* into the page, with content laid over it (same look as the entry page).
*/
export function DetailHero({
backdrop,
children,
}: {
backdrop: string | null | undefined;
children: ReactNode;
}) {
return (
<section className="relative -mx-4 -mt-4 md:-mx-6 md:-mt-6">
<div className="absolute inset-0 overflow-hidden">
{backdrop ? (
<img
src={backdrop}
alt=""
className="h-full w-full object-cover object-top"
/>
) : (
<div className="h-full w-full bg-linear-to-br from-primary/30 via-primary/10 to-background" />
)}
<div className="absolute inset-0 bg-linear-to-t from-background via-background/75 to-background/10" />
<div className="absolute inset-0 bg-linear-to-r from-background/90 via-background/40 to-transparent" />
</div>
<div className="relative mx-auto max-w-6xl px-4 pb-8 pt-24 md:px-6 sm:pt-40">
{children}
</div>
</section>
);
}
export function MetaItem({ children }: { children: ReactNode }) {
return (
<span className="inline-flex items-center gap-3">
<span className="h-1 w-1 rounded-full bg-muted-foreground/50" />
<span>{children}</span>
</span>
);
}
export function HeroChip({ children }: { children: ReactNode }) {
return (
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-background/60 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wider text-muted-foreground backdrop-blur [&_svg]:h-3 [&_svg]:w-3">
{children}
</span>
);
}
export function IconAction({
label,
onClick,
disabled,
active,
children,
}: {
label: string;
onClick: () => void;
disabled?: boolean;
active?: boolean;
children: ReactNode;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="icon-lg"
onClick={onClick}
disabled={disabled}
aria-label={label}
aria-pressed={active}
className={`h-11 w-11 rounded-full border-border/60 bg-background/60 backdrop-blur ${active ? "border-foreground/20 bg-accent" : ""}`}
/>
}
>
{children}
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
/** Round icon link with a tooltip (same look as IconAction). */
export function IconLink({
label,
to,
children,
}: {
label: string;
to: string;
children: ReactNode;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Link
to={to}
aria-label={label}
className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-border/60 bg-background/60 backdrop-blur transition-colors hover:bg-accent"
/>
}
>
{children}
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
export function DetailSection({
title,
action,
children,
}: {
title: string;
action?: ReactNode;
children: ReactNode;
}) {
return (
<section className="space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="text-lg font-semibold">{title}</h3>
{action}
</div>
{children}
</section>
);
}
export function DetailCard({
title,
children,
}: {
title: string;
children: ReactNode;
}) {
return (
<div className="rounded-xl border border-border/60 bg-card/50 p-4">
<h3 className="mb-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
{title}
</h3>
{children}
</div>
);
}
export function DetailRow({
icon,
label,
children,
}: {
icon: ReactNode;
label: string;
children: ReactNode;
}) {
return (
<div className="flex items-start justify-between gap-4 text-sm">
<dt className="flex items-center gap-2 text-muted-foreground [&_svg]:h-3.5 [&_svg]:w-3.5">
{icon}
{label}
</dt>
<dd className="text-right font-medium">{children}</dd>
</div>
);
}
@@ -0,0 +1,324 @@
import { Link } from "react-router-dom";
import {
CheckCircle2,
Clock,
Eye,
LayoutGrid,
List,
PlayCircle,
Star,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils";
import {
isEpisodeUpcoming,
isEpisodeWatched,
type EpisodeView,
} from "@/lib/episodes";
import type { Episode, EpisodeSeen } from "@/types";
interface EpisodeActions {
entryId: number;
seasonId: number;
onPlay: (episode: Episode) => void;
onMarkWatched: (episode: Episode) => void;
}
/** List/cards toggle for the season page's episodes header. */
export function EpisodeViewToggle({
view,
onChange,
}: {
view: EpisodeView;
onChange: (view: EpisodeView) => void;
}) {
return (
<div className="flex items-center rounded-lg border border-border/60 p-0.5">
{(
[
{ value: "list", label: "List view", Icon: List },
{ value: "cards", label: "Card view", Icon: LayoutGrid },
] as const
).map(({ value, label, Icon }) => (
<Button
key={value}
variant={view === value ? "secondary" : "ghost"}
size="icon-sm"
aria-label={label}
aria-pressed={view === value}
title={label}
onClick={() => onChange(value)}
>
<Icon />
</Button>
))}
</div>
);
}
export function SeasonEpisodes({
episodes,
view,
...actions
}: EpisodeActions & { episodes: Episode[]; view: EpisodeView }) {
if (view === "cards") {
return (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{episodes.map((ep) => (
<EpisodeCard key={ep.id} episode={ep} {...actions} />
))}
</div>
);
}
return (
<div className="space-y-2">
{episodes.map((ep) => (
<EpisodeRow key={ep.id} episode={ep} {...actions} />
))}
</div>
);
}
function episodeHref(entryId: number, seasonId: number, ep: Episode) {
return `/entry/${entryId}/season/${seasonId}/episode/${ep.id}`;
}
function stop(ev: React.MouseEvent, fn: () => void) {
ev.preventDefault();
ev.stopPropagation();
fn();
}
function SeenLabel({ episode }: { episode: Episode }) {
const dates = (episode.episodeSeens ?? []).map(
(s: EpisodeSeen) => s.date_seen,
);
if (dates.length === 0) return null;
if (dates.length === 1) {
return (
<span className="text-green-600 dark:text-green-400">
Seen {formatDate(dates[0])}
</span>
);
}
return (
<Tooltip>
<TooltipTrigger
render={
<span className="cursor-default text-green-600 underline decoration-dotted dark:text-green-400" />
}
>
Seen {dates.length} times
</TooltipTrigger>
<TooltipContent>
<div className="space-y-0.5 text-xs">
{dates.map((d, i) => (
<p key={i}>{formatDate(d)}</p>
))}
</div>
</TooltipContent>
</Tooltip>
);
}
function EpisodeMeta({ episode }: { episode: Episode }) {
return (
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
{episode.air_date && <span>{formatDate(episode.air_date)}</span>}
{episode.runtime ? (
<span className="inline-flex items-center gap-0.5">
<Clock className="h-3 w-3" />
{formatRuntime(episode.runtime)}
</span>
) : null}
{episode.tmdb_rating ? (
<span className="inline-flex items-center gap-0.5 tabular-nums">
<Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
{episode.tmdb_rating.toFixed(1)}
</span>
) : null}
<SeenLabel episode={episode} />
</div>
);
}
function TypeBadge({ episode }: { episode: Episode }) {
if (isEpisodeUpcoming(episode)) {
return (
<span className="rounded bg-sky-500/15 px-1.5 py-px text-[10px] font-semibold uppercase text-sky-600 dark:text-sky-400">
Upcoming
</span>
);
}
if (
episode.episode_type === "finale" ||
episode.episode_type === "mid_season"
) {
return (
<span className="rounded bg-violet-500/15 px-1.5 py-px text-[10px] font-semibold uppercase text-violet-600 dark:text-violet-400">
{episode.episode_type === "finale" ? "Finale" : "Mid-season"}
</span>
);
}
return null;
}
function Still({
episode,
size,
className,
onPlay,
}: {
episode: Episode;
size: string;
className: string;
onPlay: () => void;
}) {
return (
<div
className={`group/thumb relative shrink-0 cursor-pointer overflow-hidden bg-muted ${className}`}
onClick={(ev) => stop(ev, onPlay)}
role="button"
aria-label={`Play episode ${episode.episode_number}`}
>
{episode.still_path ? (
<img
src={getTmdbPosterUrl(episode.still_path, size)}
alt={episode.name}
loading="lazy"
className="h-full w-full object-cover transition duration-300 group-hover/thumb:scale-[1.03] group-hover/thumb:brightness-50"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
No image
</div>
)}
<div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover/thumb:opacity-100">
<PlayCircle className="h-9 w-9 text-white drop-shadow-lg" />
</div>
</div>
);
}
function WatchButton({
episode,
onClick,
}: {
episode: Episode;
onClick: () => void;
}) {
const watched = isEpisodeWatched(episode);
return (
<Button
size="icon"
variant={watched ? "secondary" : "outline"}
className="h-8 w-8 shrink-0"
aria-label={watched ? "Watch again" : "Mark as watched"}
title={watched ? "Add another watch" : "Mark as watched"}
onClick={(ev) => stop(ev, onClick)}
>
<Eye className="h-4 w-4" />
</Button>
);
}
function EpisodeRow({
episode,
entryId,
seasonId,
onPlay,
onMarkWatched,
}: EpisodeActions & { episode: Episode }) {
const watched = isEpisodeWatched(episode);
return (
<Link
to={episodeHref(entryId, seasonId, episode)}
className={`flex items-center gap-3 rounded-xl border p-2 transition-colors hover:bg-accent/40 sm:gap-4 sm:p-2.5 ${
watched ? "border-green-500/25 bg-green-500/[0.03]" : "border-border/60"
}`}
>
<Still
episode={episode}
size="w300"
className="h-16 w-28 rounded-lg sm:h-20 sm:w-36"
onPlay={() => onPlay(episode)}
/>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className="text-xs font-semibold text-muted-foreground tabular-nums">
E{episode.episode_number}
</span>
<span className="truncate font-medium">{episode.name}</span>
{watched && (
<CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />
)}
<TypeBadge episode={episode} />
</div>
<EpisodeMeta episode={episode} />
{episode.overview && (
<p className="line-clamp-2 text-xs text-muted-foreground">
{episode.overview}
</p>
)}
</div>
<WatchButton episode={episode} onClick={() => onMarkWatched(episode)} />
</Link>
);
}
function EpisodeCard({
episode,
entryId,
seasonId,
onPlay,
onMarkWatched,
}: EpisodeActions & { episode: Episode }) {
const watched = isEpisodeWatched(episode);
return (
<Link
to={episodeHref(entryId, seasonId, episode)}
className="group flex flex-col overflow-hidden rounded-xl border border-border/60 bg-card/50 transition-colors hover:bg-accent/40"
>
<div className="relative">
<Still
episode={episode}
size="w780"
className="aspect-video w-full"
onPlay={() => onPlay(episode)}
/>
<span className="pointer-events-none absolute left-2 top-2 rounded-md bg-black/65 px-2 py-0.5 text-xs font-bold text-white tabular-nums backdrop-blur">
E{episode.episode_number}
</span>
{watched && (
<span className="pointer-events-none absolute right-2 top-2 inline-flex items-center gap-1 rounded-full bg-green-500/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow">
<CheckCircle2 className="h-3 w-3" />
Watched
</span>
)}
</div>
<div className="flex flex-1 flex-col gap-1.5 p-3">
<div className="flex items-start justify-between gap-2">
<p className="line-clamp-1 font-semibold">{episode.name}</p>
<TypeBadge episode={episode} />
</div>
<EpisodeMeta episode={episode} />
{episode.overview && (
<p className="line-clamp-3 text-xs text-muted-foreground">
{episode.overview}
</p>
)}
<div className="mt-auto flex justify-end pt-1">
<WatchButton
episode={episode}
onClick={() => onMarkWatched(episode)}
/>
</div>
</div>
</Link>
);
}
@@ -1,9 +1,16 @@
import { useState } from "react"; import { useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { ChevronDown, ChevronUp, Play } from "lucide-react"; import { Check, ChevronDown, ChevronUp, Eye } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog"; import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { EpisodeViewToggle } from "@/components/entries/SeasonEpisodes";
import {
isEpisodeWatched,
loadSeasonView,
saveSeasonView,
type EpisodeView,
} from "@/lib/episodes";
import { getYear, getTmdbPosterUrl } from "@/lib/media-utils"; import { getYear, getTmdbPosterUrl } from "@/lib/media-utils";
import type { Season } from "@/types"; import type { Season } from "@/types";
@@ -12,8 +19,18 @@ interface SeasonsContainerProps {
entryId: number; entryId: number;
} }
// How many seasons show before "Show all", per view
const COLLAPSED = { list: 2, cards: 4 } as const;
export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) { export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
const [view, setView] = useState<EpisodeView>(loadSeasonView);
const [markingSeason, setMarkingSeason] = useState<Season | null>(null);
const changeView = (next: EpisodeView) => {
setView(next);
saveSeasonView(next);
};
// Sort: specials (season 0) at bottom, rest latest to oldest // Sort: specials (season 0) at bottom, rest latest to oldest
const sorted = [...seasons].sort((a, b) => { const sorted = [...seasons].sort((a, b) => {
@@ -22,17 +39,42 @@ export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
return b.season_number - a.season_number; return b.season_number - a.season_number;
}); });
const display = expanded ? sorted : sorted.slice(0, 2); const limit = COLLAPSED[view];
const display = expanded ? sorted : sorted.slice(0, limit);
const nextToMark = markingSeason ? nextUnwatched(markingSeason) : undefined;
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<h3 className="text-lg font-semibold">Seasons</h3> <div className="flex items-center justify-between gap-3">
<div className="space-y-2"> <h3 className="text-lg font-semibold">Seasons</h3>
{display.map((season) => ( <EpisodeViewToggle view={view} onChange={changeView} />
<SeasonItem key={season.id} season={season} entryId={entryId} />
))}
</div> </div>
{sorted.length > 2 && (
{view === "cards" ? (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-4">
{display.map((season) => (
<SeasonCard
key={season.id}
season={season}
entryId={entryId}
onMarkWatched={() => setMarkingSeason(season)}
/>
))}
</div>
) : (
<div className="space-y-2">
{display.map((season) => (
<SeasonRow
key={season.id}
season={season}
entryId={entryId}
onMarkWatched={() => setMarkingSeason(season)}
/>
))}
</div>
)}
{sorted.length > limit && (
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
@@ -51,87 +93,208 @@ export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
)} )}
</Button> </Button>
)} )}
{/* Marks the season's next unwatched episode */}
{nextToMark && (
<EpisodeSeenEditDialog
open={!!markingSeason}
onOpenChange={(open) => {
if (!open) setMarkingSeason(null);
}}
mode="create"
episodeId={nextToMark.id}
entryId={entryId}
/>
)}
</div> </div>
); );
} }
function SeasonItem({ season, entryId }: { season: Season; entryId: number }) { function seasonProgress(season: Season) {
const [dialogOpen, setDialogOpen] = useState(false); const watched = season.episodes?.filter(isEpisodeWatched).length ?? 0;
const watchedCount = const total = season.episode_count || season.episodes?.length || 0;
season.episodes?.filter( return {
(ep) => watched,
ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0), total,
).length ?? 0; percent: total > 0 ? (watched / total) * 100 : 0,
const totalEpisodes = season.episode_count || season.episodes?.length || 0; };
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0; }
const nextUnwatched = season.episodes function nextUnwatched(season: Season) {
return season.episodes
?.slice() ?.slice()
.sort((a, b) => a.episode_number - b.episode_number) .sort((a, b) => a.episode_number - b.episode_number)
.find( .find((ep) => !isEpisodeWatched(ep));
(ep) => }
!ep.date_first_seen &&
(!ep.episodeSeens || ep.episodeSeens.length === 0), function stop(ev: React.MouseEvent, fn: () => void) {
); ev.preventDefault();
ev.stopPropagation();
fn();
}
function SeasonRow({
season,
entryId,
onMarkWatched,
}: {
season: Season;
entryId: number;
onMarkWatched: () => void;
}) {
const { watched, total, percent } = seasonProgress(season);
const canMark = !!nextUnwatched(season);
return ( return (
<> <Link
<Link to={`/entry/${entryId}/season/${season.id}`}
to={`/entry/${entryId}/season/${season.id}`} className="flex items-center gap-4 rounded-lg border border-border p-3 transition-colors hover:bg-accent/50"
className="flex items-center gap-4 rounded-lg border border-border p-3 transition-colors hover:bg-accent/50" >
> <div className="h-16 w-11 shrink-0 overflow-hidden rounded bg-muted">
{/* Poster thumbnail */} <img
<div className="h-16 w-11 shrink-0 overflow-hidden rounded bg-muted"> src={getTmdbPosterUrl(season.poster_path, "w92")}
<img alt={season.name}
src={getTmdbPosterUrl(season.poster_path, "w92")} className="h-full w-full object-cover"
alt={season.name} loading="lazy"
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-sm truncate">{season.name}</span>
<span className="text-xs text-muted-foreground">
{getYear(season.air_date)}
</span>
</div>
<div className="flex items-center gap-2 mt-1">
<Progress value={progress} className="h-1.5 flex-1" />
<span className="text-xs text-muted-foreground shrink-0">
{watchedCount}/{totalEpisodes}
</span>
</div>
</div>
{/* Quick watch button - opens dialog */}
{nextUnwatched && (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setDialogOpen(true);
}}
>
<Play className="h-4 w-4" />
</Button>
)}
</Link>
{nextUnwatched && dialogOpen && (
<EpisodeSeenEditDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
mode="create"
episodeId={nextUnwatched.id}
entryId={entryId}
/> />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{season.name}</span>
<span className="text-xs text-muted-foreground">
{getYear(season.air_date)}
</span>
</div>
<div className="mt-1 flex items-center gap-2">
<Progress value={percent} className="h-1.5 flex-1" />
<span className="shrink-0 text-xs text-muted-foreground">
{watched}/{total}
</span>
</div>
</div>
{canMark && (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
aria-label="Mark next episode as watched"
title="Mark next episode as watched"
onClick={(e) => stop(e, onMarkWatched)}
>
<Eye className="h-4 w-4" />
</Button>
)} )}
</> </Link>
);
}
function SeasonCard({
season,
entryId,
onMarkWatched,
}: {
season: Season;
entryId: number;
onMarkWatched: () => void;
}) {
const { watched, total, percent } = seasonProgress(season);
const canMark = !!nextUnwatched(season);
return (
<Link
to={`/entry/${entryId}/season/${season.id}`}
className="group flex flex-col overflow-hidden rounded-xl border border-border/60 bg-card/50 transition-colors hover:bg-accent/40"
>
<div className="aspect-2/3 overflow-hidden bg-muted">
<img
src={getTmdbPosterUrl(season.poster_path, "w342")}
alt={season.name}
loading="lazy"
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"
/>
</div>
<div className="flex items-center gap-2 p-2.5">
<div className="min-w-0 flex-1">
<p className="line-clamp-1 text-sm font-semibold">{season.name}</p>
<p className="text-xs text-muted-foreground tabular-nums">
{[getYear(season.air_date), `${watched}/${total} eps`]
.filter(Boolean)
.join(" · ")}
</p>
</div>
<ProgressRing
percent={percent}
done={total > 0 && watched >= total}
onClick={canMark ? (e) => stop(e, onMarkWatched) : undefined}
/>
</div>
</Link>
);
}
/** Circular progress with the mark-as-watched button in the middle. */
function ProgressRing({
percent,
done,
onClick,
}: {
percent: number;
done: boolean;
onClick?: (e: React.MouseEvent) => void;
}) {
const size = 44;
const stroke = 3.5;
const radius = (size - stroke) / 2;
const circumference = 2 * Math.PI * radius;
const offset = circumference * (1 - Math.min(100, percent) / 100);
return (
<div
className="relative shrink-0"
style={{ width: size, height: size }}
title={`${Math.round(percent)}% watched`}
>
<svg width={size} height={size} className="-rotate-90" aria-hidden="true">
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
strokeWidth={stroke}
className="stroke-muted"
/>
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={circumference}
strokeDashoffset={offset}
className={`transition-[stroke-dashoffset] duration-500 ${
done ? "stroke-green-500" : "stroke-primary"
}`}
/>
</svg>
{done ? (
<span className="absolute inset-0 flex items-center justify-center text-green-500">
<Check className="h-4 w-4" />
</span>
) : (
<button
type="button"
onClick={onClick}
disabled={!onClick}
aria-label="Mark next episode as watched"
title="Mark next episode as watched"
className="absolute inset-1.5 flex items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none"
>
<Eye className="h-4 w-4" />
</button>
)}
</div>
); );
} }
@@ -12,9 +12,7 @@ import { Sidebar, MobileSidebarContent } from "./Sidebar";
import { TitleBar } from "./TitleBar"; import { TitleBar } from "./TitleBar";
import { CommandPalette } from "@/components/CommandPalette"; import { CommandPalette } from "@/components/CommandPalette";
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore"; import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
import { isDesktop } from "@/lib/platform";
const isElectron =
import.meta.env.VITE_ELECTRON === "true" || !!window.electron?.isElectron;
export function AppLayout() { export function AppLayout() {
const [mobileOpen, setMobileOpen] = useState(false); const [mobileOpen, setMobileOpen] = useState(false);
@@ -62,7 +60,7 @@ export function AppLayout() {
return ( return (
<div className="flex h-screen flex-col overflow-hidden"> <div className="flex h-screen flex-col overflow-hidden">
{isElectron && <TitleBar />} {isDesktop && <TitleBar />}
<CommandPalette /> <CommandPalette />
<div className="flex flex-1 overflow-hidden"> <div className="flex flex-1 overflow-hidden">
@@ -1,17 +1,36 @@
import { Minus, Square, X } from "lucide-react"; import { Minus, Square, X } from "lucide-react";
import { isTauri } from "@/lib/platform";
// Loaded only inside the Tauri shell so web and Electron bundles don't pull it in eagerly.
const tauriWindow = async () => {
const { getCurrentWindow } = await import("@tauri-apps/api/window");
return getCurrentWindow();
};
const minimize = () =>
isTauri
? void tauriWindow().then((w) => w.minimize())
: window.electron?.windowControls.minimize();
const maximize = () =>
isTauri
? void tauriWindow().then((w) => w.toggleMaximize())
: window.electron?.windowControls.maximize();
const close = () =>
isTauri
? void tauriWindow().then((w) => w.close())
: window.electron?.windowControls.close();
export function TitleBar() { export function TitleBar() {
const minimize = () => window.electron?.windowControls.minimize();
const maximize = () => window.electron?.windowControls.maximize();
const close = () => window.electron?.windowControls.close();
return ( return (
// Electron drags via -webkit-app-region; Tauri via data-tauri-drag-region,
// which only applies to the element that carries it (not its children).
<div <div
data-tauri-drag-region
className="flex h-14 select-none items-center justify-between border-b border-border bg-background" className="flex h-14 select-none items-center justify-between border-b border-border bg-background"
style={{ WebkitAppRegion: "drag" } as React.CSSProperties} style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
> >
<div className="flex items-center gap-2 pl-3"> <div data-tauri-drag-region className="flex h-full flex-1 items-center gap-2 pl-3">
<span className="text-xs font-semibold tracking-wide text-foreground/80"> <span className="pointer-events-none text-xs font-semibold tracking-wide text-foreground/80">
SHOWY SHOWY
</span> </span>
</div> </div>
+2 -1
View File
@@ -1,8 +1,9 @@
import axios from 'axios'; import axios from 'axios';
import { useAuthStore } from '@/stores/useAuthStore'; import { useAuthStore } from '@/stores/useAuthStore';
import { isDesktopBuild } from '@/lib/platform';
const API_BASE_URL = const API_BASE_URL =
import.meta.env.VITE_ELECTRON === 'true' isDesktopBuild
? 'http://localhost:4000/api/v1' ? 'http://localhost:4000/api/v1'
: import.meta.env.VITE_API_URL || '/api/v1'; : import.meta.env.VITE_API_URL || '/api/v1';
+37
View File
@@ -0,0 +1,37 @@
import type { Episode } from "@/types";
export const isEpisodeWatched = (ep: Episode) =>
!!ep.date_first_seen || (ep.episodeSeens?.length ?? 0) > 0;
export const isEpisodeUpcoming = (ep: Episode) =>
!!ep.air_date && new Date(ep.air_date).getTime() > Date.now();
/** First aired episode not watched yet (what "Continue" should play). */
export const nextUnwatchedEpisode = (episodes: Episode[]) =>
episodes.find((ep) => !isEpisodeWatched(ep) && !isEpisodeUpcoming(ep));
export type EpisodeView = "list" | "cards";
/** Remembered list/cards choice (per browser); falls back to list. */
function loadView(key: string): EpisodeView {
try {
return localStorage.getItem(key) === "cards" ? "cards" : "list";
} catch {
return "list";
}
}
function saveView(key: string, view: EpisodeView) {
try {
localStorage.setItem(key, view);
} catch {
// storage unavailable (private mode); the choice just isn't remembered
}
}
export const loadEpisodeView = () => loadView("showy.episodeView");
export const saveEpisodeView = (view: EpisodeView) =>
saveView("showy.episodeView", view);
export const loadSeasonView = () => loadView("showy.seasonView");
export const saveSeasonView = (view: EpisodeView) =>
saveView("showy.seasonView", view);
+18
View File
@@ -0,0 +1,18 @@
// Which shell the frontend runs in. The build-time flags come from the
// build:electron / build:tauri / dev:tauri scripts; the runtime checks cover
// dev mode, where the shell loads the plain Vite dev server.
export const isTauri =
import.meta.env.VITE_TAURI === "true" ||
(typeof window !== "undefined" && "__TAURI_INTERNALS__" in window);
export const isElectron =
import.meta.env.VITE_ELECTRON === "true" ||
(typeof window !== "undefined" && !!window.electron?.isElectron);
/** Built for a desktop shell: local backend on :4000, hash routing, custom title bar. */
export const isDesktopBuild =
import.meta.env.VITE_ELECTRON === "true" || import.meta.env.VITE_TAURI === "true";
/** Running inside a desktop shell (Electron or Tauri). */
export const isDesktop = isElectron || isTauri;
+368 -209
View File
@@ -1,8 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom"; import { useParams, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query"; import { useSeason, useSeasonEpisodes } from "@/hooks/useSeasons";
import { seasonsApi } from "@/api/seasons";
import { useSeason } from "@/hooks/useSeasons";
import { useEntry, useEntrySeasons } from "@/hooks/useEntries"; import { useEntry, useEntrySeasons } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore"; import { useLibraryStore } from "@/stores/useLibraryStore";
import { import {
@@ -13,19 +11,39 @@ import { StreamingDialog } from "@/components/streaming/StreamingDialog";
import { useStreamingStore } from "@/stores/useStreamingStore"; import { useStreamingStore } from "@/stores/useStreamingStore";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { EpisodeWatchHistory } from "@/components/entries/EpisodeWatchHistory"; import { EpisodeWatchHistory } from "@/components/entries/EpisodeWatchHistory";
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog"; import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog"; import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { CastList } from "@/components/entries/CastList"; import { CastList } from "@/components/entries/CastList";
import { import {
Eye, DetailCard,
DetailHero,
DetailRow,
DetailSection,
HeroChip,
IconLink,
MetaItem,
} from "@/components/entries/DetailHero";
import {
CalendarDays,
CheckCircle2,
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
Clock, Clock,
PlayCircle, Eye,
Hash,
ListVideo,
Play,
Star,
Tv,
} from "lucide-react"; } from "lucide-react";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils"; import { isEpisodeUpcoming, isEpisodeWatched } from "@/lib/episodes";
import {
getBackdropUrl,
getTmdbPosterUrl,
formatDate,
formatRuntime,
} from "@/lib/media-utils";
import type { Credit, Episode, EpisodePerson, EpisodeSeen } from "@/types"; import type { Credit, Episode, EpisodePerson, EpisodeSeen } from "@/types";
/** Stored guest star → the Credit shape CastList renders (links via TMDB id). */ /** Stored guest star → the Credit shape CastList renders (links via TMDB id). */
@@ -47,32 +65,29 @@ function toGuestCredit(guest: EpisodePerson): Credit {
}; };
} }
const pad = (n: number | null | undefined) => String(n ?? 0).padStart(2, "0");
export function EpisodePage() { export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{ const { entryId, seasonId, episodeId } = useParams<{
entryId: string; entryId: string;
seasonId: string; seasonId: string;
episodeId: string; episodeId: string;
}>(); }>();
const navigate = useNavigate(); const entryIdNum = parseInt(entryId!, 10);
const seasonIdNum = parseInt(seasonId!, 10);
const epId = parseInt(episodeId!, 10);
const { data: episodes = [] } = useQuery({ const { data: episodes = [] } = useSeasonEpisodes(seasonIdNum);
queryKey: ["seasons", parseInt(seasonId!, 10), "episodes"], const { data: season } = useSeason(seasonIdNum);
queryFn: () => seasonsApi.getEpisodes(parseInt(seasonId!, 10)), const { data: entry } = useEntry(entryIdNum);
}); const { data: entrySeasons } = useEntrySeasons(entryIdNum);
const libraryEntry = useLibraryStore((s) => s.entries.get(entryIdNum));
const { data: season } = useSeason(parseInt(seasonId!, 10)); const show = entry ?? libraryEntry;
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 seasonNumber = season?.season_number; const seasonNumber = season?.season_number;
const { initialize, play } = useStreamingStore(); const { initialize, play } = useStreamingStore();
const [streamingOpen, setStreamingOpen] = useState(false); const [streamingOpen, setStreamingOpen] = useState(false);
const epId = parseInt(episodeId!, 10);
const entryIdNum = parseInt(entryId!, 10);
const episode: Episode | undefined = episodes.find( const episode: Episode | undefined = episodes.find(
(ep: Episode) => ep.id === epId, (ep: Episode) => ep.id === epId,
); );
@@ -83,215 +98,320 @@ export function EpisodePage() {
const [deleteTarget, setDeleteTarget] = useState<number | null>(null); const [deleteTarget, setDeleteTarget] = useState<number | null>(null);
const [showAddDialog, setShowAddDialog] = useState(false); const [showAddDialog, setShowAddDialog] = useState(false);
// Find prev/next episode
const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId); const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId);
const prevEpisode: Episode | undefined = const prevEpisode: Episode | undefined =
currentIndex > 0 ? episodes[currentIndex - 1] : undefined; currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const nextEpisode: Episode | undefined = const nextEpisode: Episode | undefined =
currentIndex < episodes.length - 1 ? episodes[currentIndex + 1] : undefined; currentIndex >= 0 && currentIndex < episodes.length - 1
? episodes[currentIndex + 1]
: undefined;
const episodeHref = (ep: Episode) =>
`/entry/${entryId}/season/${seasonId}/episode/${ep.id}`;
if (!episode) { if (!episode) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<Skeleton className="h-48 w-full rounded-lg" /> <Skeleton className="-mx-4 -mt-4 h-80 md:-mx-6 md:-mt-6" />
<Skeleton className="h-6 w-48" /> <div className="mx-auto max-w-6xl space-y-3">
<Skeleton className="h-4 w-80" /> <Skeleton className="h-6 w-48" />
<Skeleton className="h-20 w-full" />
</div>
</div> </div>
); );
} }
const canPlay = !!entry?.entryIds?.tmdb_id && !!seasonNumber;
const watchEpisode = () => {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: seasonNumber,
episode: episode.episode_number,
});
setStreamingOpen(true);
};
const watched = isEpisodeWatched(episode);
const upcoming = isEpisodeUpcoming(episode);
const backdrop = episode.still_path
? getTmdbPosterUrl(episode.still_path, "original")
: show
? getBackdropUrl(show)
: null;
const crewBy = (job: "Director" | "Writer") =>
(episode.crew ?? []).filter(
(c, i, all) =>
(job === "Writer"
? c.department === "Writing"
: c.job === "Director") &&
all.findIndex((o) => o.id === c.id && o.department === c.department) ===
i,
);
const directors = crewBy("Director");
const writers = crewBy("Writer");
return ( return (
<div className="space-y-8 mx-auto max-w-4xl"> <div className="animate-page-enter">
{/* Breadcrumb: Title / Season x / Episode x */} <DetailHero backdrop={backdrop}>
<div className="flex items-center gap-1.5 text-sm text-muted-foreground"> <div className="max-w-3xl space-y-4 text-center sm:text-left">
<Link <div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
to={`/entry/${entryId}`} <Link to={`/entry/${entryId}`}>
className="hover:text-foreground transition-colors truncate max-w-50" <HeroChip>
> <Tv />
{entryTitle || "Entry"} {show?.title ?? "Show"}
</Link> </HeroChip>
<span>/</span> </Link>
<Link <Link to={`/entry/${entryId}/season/${seasonId}`}>
to={`/entry/${entryId}/season/${seasonId}`} <HeroChip>Season {seasonNumber ?? "?"}</HeroChip>
className="hover:text-foreground transition-colors" </Link>
> <span className="rounded border border-foreground/30 px-1.5 py-px text-xs font-semibold tracking-wide tabular-nums">
Season {seasonNumber ?? "?"} S{pad(seasonNumber)}E{pad(episode.episode_number)}
</Link> </span>
<span>/</span> {episode.episode_type === "finale" && (
<span className="text-foreground font-medium"> <span className="rounded bg-violet-500/15 px-1.5 py-px text-xs font-semibold uppercase text-violet-600 dark:text-violet-400">
Episode {episode.episode_number} Finale
</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")}
</span>
</div>
<Button size="sm" onClick={() => setShowAddDialog(true)}>
<Eye className="mr-1.5 h-4 w-4" />
Mark as Watched
</Button>
</div>
{/* High-quality thumbnail — click to watch */}
{episode.still_path && (
<div
className="relative overflow-hidden rounded-xl cursor-pointer group"
onClick={() => {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: seasonNumber,
episode: episode.episode_number,
});
setStreamingOpen(true);
}}
>
<img
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>
</div> )}
{upcoming && (
<span className="rounded bg-sky-500/15 px-1.5 py-px text-xs font-semibold uppercase text-sky-600 dark:text-sky-400">
Upcoming
</span>
)}
{watched && (
<span className="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2.5 py-0.5 text-xs font-medium text-green-600 dark:text-green-400">
<CheckCircle2 className="h-3 w-3" /> Watched
</span>
)}
</div>
<h1 className="select-text text-4xl font-extrabold leading-[1.05] tracking-tight text-balance sm:text-5xl">
{episode.name}
</h1>
<div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-sm text-muted-foreground sm:justify-start">
{episode.air_date && (
<span className="font-medium text-foreground/90">
{formatDate(episode.air_date)}
</span>
)}
{episode.runtime ? (
<MetaItem>{formatRuntime(episode.runtime)}</MetaItem>
) : null}
{episode.tmdb_rating ? (
<MetaItem>
<span className="inline-flex items-center gap-1 tabular-nums">
<Star className="h-3.5 w-3.5 fill-yellow-400 text-yellow-400" />
{episode.tmdb_rating.toFixed(1)}
{episode.tmdb_vote_count ? (
<span className="text-xs">
({episode.tmdb_vote_count} votes)
</span>
) : null}
</span>
</MetaItem>
) : null}
</div>
<div className="flex flex-wrap items-center justify-center gap-2 pt-1 sm:justify-start">
<Button
size="lg"
className="h-11 gap-2 px-6"
onClick={watchEpisode}
disabled={!canPlay}
>
<Play className="h-4 w-4 fill-current" />
Watch episode
</Button>
<Button
size="lg"
variant="outline"
className="h-11 gap-2 border-border/60 bg-background/60 px-5 backdrop-blur"
onClick={() => setShowAddDialog(true)}
>
<Eye className="h-4 w-4" />
{watched ? "Watch again" : "Mark as watched"}
</Button>
{prevEpisode && (
<IconLink
to={episodeHref(prevEpisode)}
label={`Previous: E${prevEpisode.episode_number}`}
>
<ChevronLeft className="h-4 w-4" />
</IconLink>
)}
{nextEpisode && (
<IconLink
to={episodeHref(nextEpisode)}
label={`Next: E${nextEpisode.episode_number}`}
>
<ChevronRight className="h-4 w-4" />
</IconLink>
)}
</div> </div>
</div> </div>
)} </DetailHero>
{/* Info */} <div className="mx-auto mt-4 grid max-w-6xl gap-10 lg:grid-cols-[minmax(0,1fr)_300px]">
<div className="space-y-3"> <div className="min-w-0 space-y-10">
<h1 className="text-2xl font-bold">{episode.name}</h1> {(episode.overview || directors.length > 0 || writers.length > 0) && (
<DetailSection title="Overview">
{episode.overview && (
<p className="select-text max-w-prose text-[15px] leading-relaxed text-foreground/85">
{episode.overview}
</p>
)}
{(directors.length > 0 || writers.length > 0) && (
<div className="space-y-1 text-sm">
{[
{ label: "Directed by", people: directors },
{ label: "Written by", people: writers },
]
.filter((g) => g.people.length > 0)
.map((g) => (
<p key={g.label} className="text-muted-foreground">
{g.label}{" "}
{g.people.map((p, i) => (
<span key={p.id}>
{i > 0 && ", "}
<Link
to={`/people/tmdb/${p.id}`}
className="font-medium text-foreground hover:underline"
>
{p.name}
</Link>
</span>
))}
</p>
))}
</div>
)}
</DetailSection>
)}
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground"> {episode.guest_stars && episode.guest_stars.length > 0 && (
{episode.air_date && <span>{formatDate(episode.air_date)}</span>} <CastList
{episode.runtime && ( title="Guest Stars"
<span className="flex items-center gap-1"> credits={episode.guest_stars.map(toGuestCredit)}
<Clock className="h-3 w-3" /> />
{formatRuntime(episode.runtime)} )}
</span>
{watchHistory.length > 0 && (
<EpisodeWatchHistory
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as
EpisodeSeen | undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
/>
)}
{/* Prev / Next */}
{(prevEpisode || nextEpisode) && (
<div className="grid gap-3 sm:grid-cols-2">
{prevEpisode ? (
<NeighbourCard
episode={prevEpisode}
href={episodeHref(prevEpisode)}
direction="prev"
/>
) : (
<div className="hidden sm:block" />
)}
{nextEpisode && (
<NeighbourCard
episode={nextEpisode}
href={episodeHref(nextEpisode)}
direction="next"
/>
)}
</div>
)} )}
</div> </div>
{episode.overview && ( {/* Sidebar */}
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl"> <aside className="space-y-4 lg:sticky lg:top-6 lg:self-start">
{episode.overview} <DetailCard title="Details">
</p> <dl className="space-y-2.5">
)} {episode.air_date && (
<DetailRow icon={<CalendarDays />} label="Aired">
{formatDate(episode.air_date)}
</DetailRow>
)}
{episode.runtime ? (
<DetailRow icon={<Clock />} label="Runtime">
{formatRuntime(episode.runtime)}
</DetailRow>
) : null}
{episode.tmdb_rating ? (
<DetailRow icon={<Star />} label="TMDB">
{episode.tmdb_rating.toFixed(1)}/10
</DetailRow>
) : null}
{episode.production_code && (
<DetailRow icon={<Hash />} label="Prod. code">
{episode.production_code}
</DetailRow>
)}
<DetailRow icon={<Eye />} label="Watched">
{watchHistory.length > 0
? watchHistory.length === 1
? formatDate(watchHistory[0].date_seen)
: `${watchHistory.length}× · last ${formatDate(
watchHistory
.map((r) => r.date_seen)
.filter(Boolean)
.sort()
.at(-1) ?? null,
)}`
: "Not yet"}
</DetailRow>
</dl>
</DetailCard>
{episode.crew && episode.crew.length > 0 && ( {episodes.length > 1 && (
<div className="space-y-1 text-sm"> <DetailCard title={`Season ${seasonNumber ?? ""} episodes`}>
{(["Director", "Writer"] as const).map((job) => { <ol className="-mx-1 max-h-96 space-y-0.5 overflow-y-auto">
const people = episode.crew!.filter( {episodes.map((ep) => {
(c, i, all) => const current = ep.id === episode.id;
(job === "Writer" return (
? c.department === "Writing" <li key={ep.id}>
: c.job === "Director") &&
all.findIndex(
(o) => o.id === c.id && o.department === c.department,
) === i,
);
if (people.length === 0) return null;
return (
<p key={job} className="text-muted-foreground">
{job === "Director" ? "Directed by" : "Written by"}{" "}
{people.map((p, i) => (
<span key={p.id}>
{i > 0 && ", "}
<Link <Link
to={`/people/tmdb/${p.id}`} to={episodeHref(ep)}
className="font-medium text-foreground hover:underline" aria-current={current ? "page" : undefined}
className={`flex items-center gap-2 rounded-md px-1.5 py-1.5 text-sm transition-colors ${
current
? "bg-accent font-semibold"
: "hover:bg-accent/50"
}`}
> >
{p.name} <span className="w-7 shrink-0 text-xs text-muted-foreground tabular-nums">
E{ep.episode_number}
</span>
<span className="line-clamp-1 flex-1">{ep.name}</span>
{isEpisodeWatched(ep) && (
<CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-green-500" />
)}
</Link> </Link>
</span> </li>
))} );
</p> })}
); </ol>
})} <Link
</div> to={`/entry/${entryId}/season/${seasonId}`}
)} className="mt-3 inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
</div> >
<ListVideo className="h-3 w-3" /> Open season
{/* Guest Stars (stored from TMDB; link to their TMDB person page) */} </Link>
{episode.guest_stars && episode.guest_stars.length > 0 && ( </DetailCard>
<> )}
<Separator /> </aside>
<CastList
title="Guest Stars"
credits={episode.guest_stars.map(toGuestCredit)}
/>
</>
)}
{/* Watch History */}
{watchHistory.length > 0 && (
<>
<Separator />
<EpisodeWatchHistory
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as
EpisodeSeen | undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
/>
</>
)}
{/* Prev / Next navigation */}
<Separator />
<div className="flex items-center justify-between gap-2">
{prevEpisode ? (
<Button
variant="outline"
size="sm"
className="flex items-center gap-1 max-w-60"
onClick={() =>
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`,
)
}
>
<ChevronLeft className="h-4 w-4 shrink-0" />
<span className="truncate">
E{prevEpisode.episode_number}: {prevEpisode.name}
</span>
</Button>
) : (
<div />
)}
{nextEpisode ? (
<Button
variant="outline"
size="sm"
className="flex items-center gap-1 max-w-60 ml-auto"
onClick={() =>
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`,
)
}
>
<span className="truncate">
E{nextEpisode.episode_number}: {nextEpisode.name}
</span>
<ChevronRight className="h-4 w-4 shrink-0" />
</Button>
) : (
<div />
)}
</div> </div>
{/* Add watch record dialog */} {/* Add watch record dialog */}
@@ -302,7 +422,7 @@ export function EpisodePage() {
mode="create" mode="create"
episodeId={episode.id} episodeId={episode.id}
entryId={entryIdNum} entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)} seasonId={seasonIdNum}
/> />
)} )}
@@ -316,7 +436,7 @@ export function EpisodePage() {
mode="edit" mode="edit"
record={editRecord} record={editRecord}
entryId={entryIdNum} entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)} seasonId={seasonIdNum}
/> />
)} )}
@@ -336,7 +456,7 @@ export function EpisodePage() {
id: deleteTarget, id: deleteTarget,
entryId: entryIdNum, entryId: entryIdNum,
episodeId: epId, episodeId: epId,
seasonId: parseInt(seasonId!, 10), seasonId: seasonIdNum,
}); });
setDeleteTarget(null); setDeleteTarget(null);
} }
@@ -358,3 +478,42 @@ export function EpisodePage() {
</div> </div>
); );
} }
function NeighbourCard({
episode,
href,
direction,
}: {
episode: Episode;
href: string;
direction: "prev" | "next";
}) {
return (
<Link
to={href}
className={`group flex items-center gap-3 rounded-xl border border-border/60 bg-card/50 p-2 transition-colors hover:bg-accent/40 ${
direction === "next" ? "flex-row-reverse text-right" : ""
}`}
>
<div className="h-16 w-28 shrink-0 overflow-hidden rounded-lg bg-muted">
{episode.still_path && (
<img
src={getTmdbPosterUrl(episode.still_path, "w300")}
alt=""
loading="lazy"
className="h-full w-full object-cover transition-transform group-hover:scale-[1.04]"
/>
)}
</div>
<div className="min-w-0 flex-1">
<p className="inline-flex items-center gap-1 text-xs text-muted-foreground">
{direction === "prev" && <ChevronLeft className="h-3 w-3" />}
{direction === "prev" ? "Previous" : "Next"} · E
{episode.episode_number}
{direction === "next" && <ChevronRight className="h-3 w-3" />}
</p>
<p className="line-clamp-1 font-medium">{episode.name}</p>
</div>
</Link>
);
}
+227 -250
View File
@@ -15,7 +15,6 @@ import { useStreamingStore } from "@/stores/useStreamingStore";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { StarRating } from "@/components/ui/star-rating";
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -23,51 +22,77 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu";
import { import {
Eye, ArrowLeft,
CheckCircle2,
ListChecks, ListChecks,
PlayCircle, MoreHorizontal,
Ellipsis, Play,
RefreshCw, RefreshCw,
Star, Star,
Tv,
CheckCircle2,
} from "lucide-react"; } from "lucide-react";
import { import {
Tooltip, DetailHero,
TooltipContent, DetailSection,
TooltipProvider, HeroChip,
TooltipTrigger, IconAction,
} from "@/components/ui/tooltip"; MetaItem,
import { getTmdbPosterUrl, getYear, formatDate } from "@/lib/media-utils"; } from "@/components/entries/DetailHero";
import type { Episode, EpisodeSeen } from "@/types"; import {
EpisodeViewToggle,
SeasonEpisodes,
} from "@/components/entries/SeasonEpisodes";
import {
isEpisodeWatched,
loadEpisodeView,
nextUnwatchedEpisode,
saveEpisodeView,
type EpisodeView,
} from "@/lib/episodes";
import {
getBackdropUrl,
getTmdbPosterUrl,
getYear,
formatDate,
formatRuntime,
} from "@/lib/media-utils";
import type { Episode } from "@/types";
export function SeasonPage() { export function SeasonPage() {
const { entryId, seasonId } = useParams<{ const { entryId, seasonId } = useParams<{
entryId: string; entryId: string;
seasonId: string; seasonId: string;
}>(); }>();
const { data: season, isLoading } = useSeason(parseInt(seasonId!, 10)); const entryIdNum = parseInt(entryId!, 10);
const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10)); const seasonIdNum = parseInt(seasonId!, 10);
const { data: entry } = useEntry(parseInt(entryId!, 10)); const { data: season, isLoading } = useSeason(seasonIdNum);
const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10)); const { data: episodes = [] } = useSeasonEpisodes(seasonIdNum);
const entryTitle = const { data: entry } = useEntry(entryIdNum);
entry?.title ?? const { data: entrySeasons } = useEntrySeasons(entryIdNum);
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title; const libraryEntry = useLibraryStore((s) => s.entries.get(entryIdNum));
const show = entry ?? libraryEntry;
const { initialize, play } = useStreamingStore(); const { initialize, play } = useStreamingStore();
const refreshSeason = useRefreshSeason(); const refreshSeason = useRefreshSeason();
const [dialogEpisode, setDialogEpisode] = useState<Episode | null>(null); const [dialogEpisode, setDialogEpisode] = useState<Episode | null>(null);
const [showMarkAllDialog, setShowMarkAllDialog] = useState(false); const [showMarkAllDialog, setShowMarkAllDialog] = useState(false);
const [showRatingDialog, setShowRatingDialog] = useState(false); const [showRatingDialog, setShowRatingDialog] = useState(false);
const [streamingOpen, setStreamingOpen] = useState(false); const [streamingOpen, setStreamingOpen] = useState(false);
const [view, setView] = useState<EpisodeView>(loadEpisodeView);
const handleWatchEpisode = (season: number, episodeNumber: number) => { const changeView = (next: EpisodeView) => {
if (!entry?.entryIds?.tmdb_id) return; setView(next);
saveEpisodeView(next);
};
const handleWatchEpisode = (episode: Episode) => {
if (!entry?.entryIds?.tmdb_id || !season) return;
initialize(); initialize();
play({ play({
type: "tv", type: "tv",
tmdbId: entry.entryIds.tmdb_id, tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined, imdbId: entry.entryIds?.imdb_id || undefined,
season, season: season.season_number,
episode: episodeNumber, episode: episode.episode_number,
}); });
setStreamingOpen(true); setStreamingOpen(true);
}; };
@@ -75,245 +100,199 @@ export function SeasonPage() {
if (isLoading || !season) { if (isLoading || !season) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex gap-6"> <Skeleton className="-mx-4 -mt-4 h-72 md:-mx-6 md:-mt-6" />
<Skeleton className="h-56 w-36 shrink-0 rounded-lg" /> <div className="mx-auto max-w-6xl space-y-3">
<div className="flex-1 space-y-3"> {Array.from({ length: 5 }).map((_, i) => (
<Skeleton className="h-6 w-48" /> <Skeleton key={i} className="h-20 w-full rounded-xl" />
<Skeleton className="h-4 w-32" /> ))}
<Skeleton className="h-4 w-64" />
</div>
</div> </div>
</div> </div>
); );
} }
const watchedCount = episodes.filter( const watchedCount = episodes.filter(isEpisodeWatched).length;
(ep: Episode) =>
ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0),
).length;
const totalEpisodes = episodes.length; const totalEpisodes = episodes.length;
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0; const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0;
const totalRuntime = episodes.reduce((sum, ep) => sum + (ep.runtime ?? 0), 0);
const airDates = episodes
.map((ep) => ep.air_date)
.filter(Boolean)
.sort() as string[];
const nextUp = nextUnwatchedEpisode(episodes);
const userRating = season.user_rating ?? 0;
const backdrop = show ? getBackdropUrl(show) : null;
return ( return (
<div className="space-y-8 animate-page-enter mx-auto max-w-4xl"> <div className="animate-page-enter">
{/* Breadcrumb: Title / Season x */} <DetailHero backdrop={backdrop}>
<div className="flex items-center gap-1.5 text-sm text-muted-foreground">
<Link <Link
to={`/entry/${entryId}`} to={`/entry/${entryId}`}
className="hover:text-foreground transition-colors truncate max-w-50" className="mb-6 inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-background/60 py-1 pl-2 pr-3 text-sm font-medium backdrop-blur transition-colors hover:bg-accent"
> >
{entryTitle || "Entry"} <ArrowLeft className="h-4 w-4" />
Back to {show?.title ?? "show"}
</Link> </Link>
<span>/</span> <div className="flex flex-col items-center gap-6 sm:flex-row sm:items-end sm:gap-8">
<span className="text-foreground font-medium"> <img
Season {season.season_number} src={getTmdbPosterUrl(season.poster_path, "w500")}
</span> alt={season.name}
</div> className="aspect-2/3 w-36 shrink-0 rounded-xl object-cover shadow-2xl shadow-black/50 ring-1 ring-white/10 sm:w-48 lg:w-52"
/>
{/* Header */} <div className="min-w-0 flex-1 space-y-4 text-center sm:text-left">
<div className="flex flex-col gap-4 sm:flex-row sm:gap-6"> <div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
<img <Link to={`/entry/${entryId}`}>
src={getTmdbPosterUrl(season.poster_path, "w185")} <HeroChip>
alt={season.name} <Tv />
className="h-40 w-28 shrink-0 rounded-lg object-cover shadow-lg self-center sm:self-start sm:h-56 sm:w-36" {show?.title ?? "Show"}
/> </HeroChip>
<div className="flex-1 flex flex-col justify-center space-y-3"> </Link>
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4"> <HeroChip>Season {season.season_number}</HeroChip>
<h1 className="text-xl font-bold sm:text-2xl">{season.name}</h1> {progress === 100 && totalEpisodes > 0 && (
{/* Actions dropdown — top right */} <span className="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2.5 py-0.5 text-xs font-medium text-green-600 dark:text-green-400">
<DropdownMenu> <CheckCircle2 className="h-3 w-3" /> Completed
<DropdownMenuTrigger asChild> </span>
)}
</div>
<h1 className="select-text text-4xl font-extrabold leading-[1.05] tracking-tight text-balance sm:text-5xl">
{season.name}
</h1>
<div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-sm text-muted-foreground sm:justify-start">
{season.air_date && (
<span className="font-medium text-foreground/90">
{getYear(season.air_date)}
</span>
)}
<MetaItem>
{totalEpisodes} {totalEpisodes === 1 ? "episode" : "episodes"}
</MetaItem>
{totalRuntime > 0 && (
<MetaItem>{formatRuntime(totalRuntime)}</MetaItem>
)}
{airDates.length > 1 && (
<MetaItem>
{formatDate(airDates[0])} – {formatDate(airDates.at(-1)!)}
</MetaItem>
)}
</div>
{/* Ratings + progress */}
<div className="flex flex-wrap items-center justify-center gap-x-5 gap-y-3 sm:justify-start">
<button
type="button"
onClick={() => setShowRatingDialog(true)}
className="inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-background/60 px-3 py-1 text-sm backdrop-blur transition-colors hover:bg-accent"
>
<Star
className={`h-4 w-4 ${userRating > 0 ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground"}`}
/>
{userRating > 0 ? (
<span className="font-semibold tabular-nums">
{userRating}/10
</span>
) : (
<span className="text-muted-foreground">Rate season</span>
)}
</button>
{season.tmdb_rating ? (
<span className="text-sm text-muted-foreground tabular-nums">
TMDB{" "}
<span className="font-semibold text-sky-500">
{season.tmdb_rating.toFixed(1)}
</span>
</span>
) : null}
<div className="flex w-56 items-center gap-2">
<Progress value={progress} className="h-2 flex-1" />
<span className="text-xs font-medium tabular-nums text-muted-foreground">
{watchedCount}/{totalEpisodes}
</span>
</div>
</div>
{/* Actions */}
<div className="flex flex-wrap items-center justify-center gap-2 pt-1 sm:justify-start">
{nextUp && (
<Button <Button
size="icon" size="lg"
variant="outline" className="h-11 gap-2 px-6"
className="shrink-0 self-end sm:self-start" onClick={() => handleWatchEpisode(nextUp)}
disabled={!entry?.entryIds?.tmdb_id}
> >
<Ellipsis className="h-4 w-4" /> <Play className="h-4 w-4 fill-current" />
{watchedCount > 0 ? "Continue" : "Start"}: E
{nextUp.episode_number}
</Button> </Button>
</DropdownMenuTrigger> )}
<DropdownMenuContent align="end" className="w-48"> <IconAction
<DropdownMenuItem onClick={() => setShowMarkAllDialog(true)}> label="Mark season watched"
<ListChecks className="mr-2 h-4 w-4" /> onClick={() => setShowMarkAllDialog(true)}
Mark Season Watched >
</DropdownMenuItem> <ListChecks className="h-4 w-4" />
<DropdownMenuItem onClick={() => setShowRatingDialog(true)}> </IconAction>
<Star className="mr-2 h-4 w-4" /> <IconAction
Rate Season label={userRating > 0 ? "Change rating" : "Rate season"}
</DropdownMenuItem> onClick={() => setShowRatingDialog(true)}
<DropdownMenuItem active={userRating > 0}
onClick={() => refreshSeason.mutate(season.id)} >
disabled={refreshSeason.isPending} <Star className="h-4 w-4" />
</IconAction>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="outline"
size="icon-lg"
className="h-11 w-11 rounded-full border-border/60 bg-background/60 backdrop-blur"
aria-label="More actions"
/>
}
> >
<RefreshCw <MoreHorizontal className="h-4 w-4" />
className={`mr-2 h-4 w-4 ${refreshSeason.isPending ? "animate-spin" : ""}`} </DropdownMenuTrigger>
/> <DropdownMenuContent align="end" className="w-48">
Refresh Season <DropdownMenuItem
</DropdownMenuItem> onClick={() => refreshSeason.mutate(season.id)}
</DropdownMenuContent> disabled={refreshSeason.isPending}
</DropdownMenu> >
</div> <RefreshCw
<div className="flex items-center gap-2 text-sm text-muted-foreground"> className={`mr-2 h-4 w-4 ${refreshSeason.isPending ? "animate-spin" : ""}`}
<span>Season {season.season_number}</span> />
{season.air_date && ( {refreshSeason.isPending
<> ? "Refreshing..."
<span>•</span> : "Refresh season"}
<span>{getYear(season.air_date)}</span> </DropdownMenuItem>
</> </DropdownMenuContent>
)} </DropdownMenu>
<span>•</span> </div>
<span>{totalEpisodes} episodes</span>
</div> </div>
</div>
</DetailHero>
{/* Season rating */} <div className="mx-auto mt-4 max-w-6xl space-y-10">
<div className="flex items-center gap-2"> {season.overview && (
<StarRating value={season.user_rating ?? 0} readOnly size="sm" /> <DetailSection title="Overview">
{season.user_rating != null && season.user_rating > 0 && ( <p className="select-text max-w-prose text-[15px] leading-relaxed text-foreground/85">
<span className="text-sm font-medium tabular-nums">
{season.user_rating}/10
</span>
)}
{season.tmdb_rating != null && season.tmdb_rating > 0 && (
<span className="text-xs text-muted-foreground">
TMDB {season.tmdb_rating}
</span>
)}
</div>
{/* Watch progress */}
<div className="flex items-center gap-3 max-w-xs">
<Progress value={progress} className="flex-1 h-2" />
<span className="text-sm font-medium">
{watchedCount}/{totalEpisodes}
</span>
</div>
{season.overview && (
<p className="text-sm text-muted-foreground max-w-lg">
{season.overview} {season.overview}
</p> </p>
)} </DetailSection>
</div> )}
</div>
{/* Episodes */} <DetailSection
<div className="space-y-3"> title="Episodes"
<h3 className="text-lg font-semibold">Episodes</h3> action={<EpisodeViewToggle view={view} onChange={changeView} />}
<div className="space-y-2"> >
{episodes.map((episode: Episode) => { <SeasonEpisodes
const isWatched = episodes={episodes}
!!episode.date_first_seen || view={view}
(episode.episodeSeens && episode.episodeSeens.length > 0); entryId={entryIdNum}
const seenDates = (episode.episodeSeens ?? []).map( seasonId={seasonIdNum}
(s: EpisodeSeen) => s.date_seen, onPlay={handleWatchEpisode}
); onMarkWatched={setDialogEpisode}
/>
return ( </DetailSection>
<Link
key={episode.id}
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="flex gap-3 rounded-lg border border-border p-2 transition-colors hover:bg-accent/50 sm:gap-4 sm:p-3"
>
{/* Thumbnail — click to watch */}
<div
className="relative h-14 w-24 shrink-0 overflow-hidden rounded bg-muted sm:h-16 sm:w-28 group/thumb cursor-pointer"
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
if (!entry?.entryIds?.tmdb_id) return;
handleWatchEpisode(
season.season_number,
episode.episode_number,
);
}}
>
{episode.still_path ? (
<img
src={getTmdbPosterUrl(episode.still_path, "w300")}
alt={episode.name}
className="h-full w-full object-cover transition-[filter] group-hover/thumb:brightness-50"
loading="lazy"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground bg-muted group-hover/thumb:bg-muted/70 transition-colors">
No Image
</div>
)}
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover/thumb:opacity-100 transition-opacity">
<PlayCircle className="h-7 w-7 text-white drop-shadow-lg" />
</div>
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
E{episode.episode_number}
</span>
<span className="text-sm font-medium truncate">
{episode.name}
</span>
{isWatched && (
<CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />
)}
</div>
<div className="flex items-center gap-2 flex-wrap">
{episode.air_date && (
<p className="text-xs text-muted-foreground">
{formatDate(episode.air_date)}
</p>
)}
{seenDates.length > 0 && (
<>
<span className="text-xs text-muted-foreground">•</span>
{seenDates.length === 1 ? (
<span className="text-xs text-green-600 dark:text-green-400">
Seen {formatDate(seenDates[0])}
</span>
) : (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<span className="text-xs text-green-600 dark:text-green-400 cursor-default underline decoration-dotted">
Seen {seenDates.length} times
</span>
</TooltipTrigger>
<TooltipContent>
<div className="space-y-0.5 text-xs">
{seenDates.map((d: string, i: number) => (
<p key={i}>{formatDate(d)}</p>
))}
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</>
)}
</div>
{episode.overview && (
<p className="mt-1 text-xs text-muted-foreground line-clamp-2">
{episode.overview}
</p>
)}
</div>
{/* Watch button — always clickable to add another seen record */}
<Button
size="icon"
variant={isWatched ? "secondary" : "outline"}
className="h-8 w-8 shrink-0 self-center"
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
setDialogEpisode(episode);
}}
>
<Eye className="h-4 w-4" />
</Button>
</Link>
);
})}
</div>
</div> </div>
{/* Episode Seen Dialog */} {/* Episode Seen Dialog */}
@@ -325,8 +304,8 @@ export function SeasonPage() {
}} }}
mode="create" mode="create"
episodeId={dialogEpisode.id} episodeId={dialogEpisode.id}
entryId={parseInt(entryId!, 10)} entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)} seasonId={seasonIdNum}
/> />
)} )}
@@ -334,19 +313,17 @@ export function SeasonPage() {
<MarkSeasonWatchedDialog <MarkSeasonWatchedDialog
open={showMarkAllDialog} open={showMarkAllDialog}
onOpenChange={setShowMarkAllDialog} onOpenChange={setShowMarkAllDialog}
entryId={parseInt(entryId!, 10)} entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)} seasonId={seasonIdNum}
episodes={episodes} episodes={episodes}
/> />
{/* Season Rating dialog */} {/* Season Rating dialog */}
{season && ( <SeasonRatingDialog
<SeasonRatingDialog open={showRatingDialog}
open={showRatingDialog} onOpenChange={setShowRatingDialog}
onOpenChange={setShowRatingDialog} season={season}
season={season} />
/>
)}
{/* Streaming dialog */} {/* Streaming dialog */}
{entry && streamingOpen && ( {entry && streamingOpen && (
+2 -2
View File
@@ -1,6 +1,7 @@
import { createBrowserRouter, createHashRouter } from "react-router-dom"; import { createBrowserRouter, createHashRouter } from "react-router-dom";
import { lazy, Suspense, type ReactNode } from "react"; import { lazy, Suspense, type ReactNode } from "react";
import { AppLayout } from "@/components/layout/AppLayout"; import { AppLayout } from "@/components/layout/AppLayout";
import { isDesktopBuild } from "@/lib/platform";
import { import {
DashboardSkeleton, DashboardSkeleton,
HomeSkeleton, HomeSkeleton,
@@ -117,8 +118,7 @@ function SuspensePage({
); );
} }
const isElectron = import.meta.env.VITE_ELECTRON === "true"; const createRouter = isDesktopBuild ? createHashRouter : createBrowserRouter;
const createRouter = isElectron ? createHashRouter : createBrowserRouter;
export const router = createRouter([ export const router = createRouter([
{ {
+6 -1
View File
@@ -4,10 +4,13 @@ import tailwindcss from '@tailwindcss/vite'
import path from 'path' import path from 'path'
const isElectron = process.env.VITE_ELECTRON === 'true'; const isElectron = process.env.VITE_ELECTRON === 'true';
const isTauri = process.env.VITE_TAURI === 'true';
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
base: isElectron ? './' : '/', base: isElectron || isTauri ? './' : '/',
// Keep Rust/Tauri output visible in the terminal during `tauri dev`.
clearScreen: !isTauri,
plugins: [react(), tailwindcss()], plugins: [react(), tailwindcss()],
resolve: { resolve: {
alias: { alias: {
@@ -16,6 +19,8 @@ export default defineConfig({
}, },
server: { server: {
port: 4200, port: 4200,
// Tauri loads devUrl http://localhost:4200, so never fall back to another port.
strictPort: isTauri,
proxy: { proxy: {
'/api': { '/api': {
target: 'http://showyback.coolguy.space', target: 'http://showyback.coolguy.space',
+6
View File
@@ -0,0 +1,6 @@
node_modules
frontend_build
src-tauri/target
src-tauri/gen
src-tauri/binaries/*
!src-tauri/binaries/.gitkeep
+128
View File
@@ -0,0 +1,128 @@
# Showy — Tauri desktop app
A Tauri v2 shell for Showy, built side by side with the Electron app in `../electron`
(which stays untouched). It loads the React frontend from `../react_frontend` and
starts the Node backend from `../backend` alongside the window.
```
tauri/
├─ package.json # Tauri CLI + scripts
├─ scripts/prepare-sidecar.mjs # copies dist/backend/backend.exe into src-tauri/binaries
├─ frontend_build/ # output of `pnpm build:tauri` (git-ignored)
└─ src-tauri/
├─ tauri.conf.json # window, dev URL, frontend dist, bundle
├─ tauri.bundle.conf.json # adds the backend sidecar; merged in only for `pnpm build`
├─ capabilities/default.json # window permissions for the custom title bar
├─ icons/ # generated from electron/assets/icon.ico
└─ src/
├─ lib.rs # app setup, stops the backend on exit
└─ backend.rs # starts/stops the backend process
```
## Prerequisites (Windows)
- **Rust** (stable, MSVC toolchain): install with [rustup](https://rustup.rs/), target
`x86_64-pc-windows-msvc`.
- **Microsoft C++ Build Tools**: "Desktop development with C++" workload from Visual Studio
Build Tools (needed by the MSVC Rust toolchain).
- **WebView2 runtime**: preinstalled on Windows 11. On Windows 10 install the Evergreen
runtime from Microsoft.
- **Node.js** (22.x is used here) and **pnpm**.
- **Tauri CLI**: installed per project as `@tauri-apps/cli` (`pnpm install` in this folder).
`cargo install tauri-cli --version "^2"` also works if you prefer `cargo tauri ...`.
- For the backend: a running **MySQL** and `backend/settings.json` (see
`backend/settings.json.example`), with dependencies installed in `backend/`.
## Run in dev
```bash
cd react_frontend && pnpm install
cd ../backend && pnpm install
cd ../tauri && pnpm install
pnpm dev
```
`pnpm dev` (= `tauri dev`) does the following:
1. Runs `pnpm --dir ../react_frontend dev:tauri`: Vite on `http://localhost:4200` with
`VITE_TAURI=true` (API base `http://localhost:4000/api/v1`, hash router, custom title bar).
2. Builds and starts the Rust app, which opens the window on the dev server (with hot reload)
and opens DevTools, like Electron's dev mode (set `SHOWY_NO_DEVTOOLS=1` to skip).
3. Starts the backend with `node server.js` in `../backend`. Its output shows in the same
terminal. When the window closes the backend is stopped, and so is anything it spawned (a
Windows job object kills the process tree, even if the app crashes).
If something already listens on port 4000 (e.g. you run `pnpm dev` in `backend/` yourself), the
app does **not** start a second backend and uses the one that is running.
Environment overrides:
| Variable | Effect |
| --- | --- |
| `SHOWY_SKIP_BACKEND=1` | never start a backend |
| `SHOWY_BACKEND_DIR=<path>` | backend folder for dev builds (default `../backend`) |
| `SHOWY_BACKEND_EXE=<path>` | run this executable as the backend (dev or release) |
| `SHOWY_NO_DEVTOOLS=1` | don't open DevTools in dev builds |
The first `tauri dev` compiles all Rust dependencies, which takes several minutes. Later runs
take seconds.
## Build
```bash
cd backend && npm run package # pkg -> dist/backend/backend.exe
cd ../tauri && pnpm build-backend # copies it to src-tauri/binaries/backend-x86_64-pc-windows-msvc.exe
pnpm build # tauri build (runs `pnpm build:tauri` in react_frontend first)
```
Output:
- `src-tauri/target/release/showy.exe`: the app (the sidecar must sit next to it as `backend.exe`).
- `src-tauri/target/release/bundle/nsis/Showy_2.0.0_x64-setup.exe`: an installer that puts
`showy.exe` and `backend.exe` side by side.
In release builds the backend runs without a console, and its output goes to
`%LOCALAPPDATA%\x4lo.showy\logs\backend.log`.
The frontend build for Tauri goes to `tauri/frontend_build`. The web build (`pnpm build`) and
the Electron build (`pnpm build:electron`) are unchanged.
## Frontend changes
- `react_frontend/src/lib/platform.ts`: `isTauri`, `isElectron`, `isDesktop`, `isDesktopBuild`.
- `api.ts` and `router.tsx` use `isDesktopBuild` (Electron **or** Tauri build), so both desktop
builds talk to `localhost:4000` and use the hash router.
- `TitleBar.tsx`: on Tauri the buttons call `@tauri-apps/api/window` (`minimize`,
`toggleMaximize`, `close`), which is loaded lazily. Dragging uses `data-tauri-drag-region`.
Electron keeps using `window.electron.windowControls` and `-webkit-app-region`.
- `vite.config.ts`: `base: './'`, `strictPort` and no screen clearing when `VITE_TAURI=true`.
- New scripts: `dev:tauri`, `build:tauri`.
## Status / missing compared with Electron
Tested on Windows 11 in dev mode: the window opens on the Vite dev server, the backend starts
and answers the webview on port 4000, the title-bar window commands (minimize, maximize/restore,
close) work, and closing the window stops the backend.
Not done yet / differences:
- **The release build has not been tested yet.** It needs `dist/backend/backend.exe`, and there
is a known problem with the pkg backend: `configService.getUserDataPath()` uses `__dirname`,
which points inside pkg's read-only snapshot. So the packaged backend cannot find or create
`settings.json`. The backend needs to read its settings next to the executable
(`path.dirname(process.execPath)` when `process.pkg` is set) or from a folder the shell passes
in, e.g. via `PARENT_PROCESS.tauri_path` (the app data dir, already sent). `sharp` and
`ffmpeg-static` native files also need checking in the pkg build.
- **Backend model**: Electron `require`s `server.js` in its own process. Tauri runs it as a
separate process (`node` in dev, the pkg `backend.exe` in release).
- **`PARENT_PROCESS`**: Electron sends `{ electron_path: userData }`. Tauri sends
`{ tauri_path: <app data dir> }`. The backend doesn't read either today.
- **Generic IPC**: Electron's preload also exposes `window.electron.ipcRenderer`. The frontend
doesn't use it, so Tauri has no equivalent (only window controls).
- **Title bar on the login page**: the window has no native frame, and the login page renders
outside `AppLayout`, so there is no title bar to drag or close the window until you log in.
Electron behaves the same way.
- **Dev API target**: Electron's `npm run dev` loads the plain `vite` dev server, which proxies
`/api` to the remote backend. Tauri dev uses the local backend on port 4000.
- No auto-update, tray icon, single-instance lock or code signing (Electron has none of these
either). The bundle target is NSIS. Electron produces an unpacked `dir` build instead.
+17
View File
@@ -0,0 +1,17 @@
{
"name": "showy_tauri",
"version": "2.0.0",
"private": true,
"description": "Showy Desktop App (Tauri)",
"scripts": {
"tauri": "tauri",
"dev": "tauri dev",
"build-front": "pnpm --dir ../react_frontend build:tauri",
"build-backend": "node scripts/prepare-sidecar.mjs",
"build": "tauri build --config src-tauri/tauri.bundle.conf.json",
"icons": "tauri icon ../electron/assets/icon.ico"
},
"devDependencies": {
"@tauri-apps/cli": "^2.9.0"
}
}
+140
View File
@@ -0,0 +1,140 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
devDependencies:
'@tauri-apps/cli':
specifier: ^2.9.0
version: 2.12.4
packages:
'@tauri-apps/cli-darwin-arm64@2.12.4':
resolution: {integrity: sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@tauri-apps/cli-darwin-x64@2.12.4':
resolution: {integrity: sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
resolution: {integrity: sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
resolution: {integrity: sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
resolution: {integrity: sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
resolution: {integrity: sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
resolution: {integrity: sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-x64-musl@2.12.4':
resolution: {integrity: sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
resolution: {integrity: sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
resolution: {integrity: sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
resolution: {integrity: sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@tauri-apps/cli@2.12.4':
resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}
engines: {node: '>= 10'}
hasBin: true
snapshots:
'@tauri-apps/cli-darwin-arm64@2.12.4':
optional: true
'@tauri-apps/cli-darwin-x64@2.12.4':
optional: true
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
optional: true
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
optional: true
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
optional: true
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
optional: true
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
optional: true
'@tauri-apps/cli-linux-x64-musl@2.12.4':
optional: true
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
optional: true
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
optional: true
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
optional: true
'@tauri-apps/cli@2.12.4':
optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 2.12.4
'@tauri-apps/cli-darwin-x64': 2.12.4
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.4
'@tauri-apps/cli-linux-arm64-gnu': 2.12.4
'@tauri-apps/cli-linux-arm64-musl': 2.12.4
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.4
'@tauri-apps/cli-linux-x64-gnu': 2.12.4
'@tauri-apps/cli-linux-x64-musl': 2.12.4
'@tauri-apps/cli-win32-arm64-msvc': 2.12.4
'@tauri-apps/cli-win32-ia32-msvc': 2.12.4
'@tauri-apps/cli-win32-x64-msvc': 2.12.4
+36
View File
@@ -0,0 +1,36 @@
// Copies the pkg-packaged backend (dist/backend/backend.exe) into
// src-tauri/binaries/ under the name Tauri expects for an external binary:
// backend-<rust target triple>[.exe].
//
// Build the backend first: cd backend && npm run package
import { execSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "..", "..");
const ext = process.platform === "win32" ? ".exe" : "";
const source = join(repoRoot, "dist", "backend", `backend${ext}`);
const triple = execSync("rustc -vV", { encoding: "utf8" })
.split("\n")
.find((line) => line.startsWith("host:"))
?.slice("host:".length)
.trim();
if (!triple) {
console.error("Could not read the Rust host triple from `rustc -vV`.");
process.exit(1);
}
if (!existsSync(source)) {
console.error(`Backend executable not found: ${source}`);
console.error("Build it first: cd backend && npm run package");
process.exit(1);
}
const targetDir = resolve(here, "..", "src-tauri", "binaries");
mkdirSync(targetDir, { recursive: true });
const target = join(targetDir, `backend-${triple}${ext}`);
copyFileSync(source, target);
console.log(`Copied ${source} -> ${target}`);
+4376
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "showy"
version = "2.0.0"
description = "Showy Desktop App"
edition = "2021"
[lib]
name = "showy_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
serde_json = "1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_JobObjects",
"Win32_System_Threading",
] }
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true
View File
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+14
View File
@@ -0,0 +1,14 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Permissions for the main Showy window (custom title bar controls).",
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-internal-toggle-maximize",
"core:window:allow-close",
"core:window:allow-start-dragging"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

+222
View File
@@ -0,0 +1,222 @@
//! Starts the Showy Node backend next to the Tauri window and stops it on exit.
//!
//! - Debug builds (`tauri dev`) run `node server.js` from the repo's `backend/` folder.
//! - Release builds run the `pkg`-packaged `backend.exe` sidecar that the bundler
//! places next to the app executable.
//! - If something already listens on the backend port, nothing is spawned and the
//! app talks to that process (handy when the backend runs in its own terminal).
//!
//! Environment overrides:
//! - `SHOWY_SKIP_BACKEND=1` never spawn a backend
//! - `SHOWY_BACKEND_DIR=<path>` backend folder used in debug builds
//! - `SHOWY_BACKEND_EXE=<path>` run this executable instead (any build)
use std::fs::{self, File};
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::time::Duration;
use tauri::{AppHandle, Manager};
/// The frontend calls `http://localhost:4000/api/v1` in desktop builds.
pub const BACKEND_PORT: u16 = 4000;
#[derive(Default)]
pub struct BackendState {
child: Mutex<Option<Child>>,
#[cfg(windows)]
job: Mutex<Option<job::Job>>,
}
impl BackendState {
pub fn stop(&self) {
if let Some(mut child) = self.child.lock().unwrap().take() {
log(&format!("stopping backend (pid {})", child.id()));
let _ = child.kill();
let _ = child.wait();
}
// Closing the job handle kills anything the backend spawned (e.g. ffmpeg).
#[cfg(windows)]
drop(self.job.lock().unwrap().take());
}
}
pub fn start(app: &AppHandle) -> BackendState {
let state = BackendState::default();
if std::env::var_os("SHOWY_SKIP_BACKEND").is_some() {
log("SHOWY_SKIP_BACKEND is set, not starting the backend");
return state;
}
if port_in_use(BACKEND_PORT) {
log(&format!(
"port {BACKEND_PORT} is already in use, using the backend that is already running"
));
return state;
}
let mut cmd = match backend_command() {
Ok(cmd) => cmd,
Err(err) => {
log(&format!("cannot start backend: {err}"));
return state;
}
};
// Same contract as the Electron shell: tell the backend where the desktop
// app keeps its own data.
let data_dir = app.path().app_data_dir().ok();
cmd.env(
"PARENT_PROCESS",
serde_json::json!({ "tauri_path": data_dir }).to_string(),
);
if cfg!(debug_assertions) {
// Backend logs go to the same terminal as `tauri dev`.
cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
} else {
// No console in release builds: write the backend output to a log file.
let log_file = app.path().app_log_dir().ok().and_then(|dir| {
fs::create_dir_all(&dir).ok()?;
File::create(dir.join("backend.log")).ok()
});
match log_file.and_then(|f| f.try_clone().ok().map(|f2| (f, f2))) {
Some((out, err)) => {
cmd.stdout(out).stderr(err);
}
None => {
cmd.stdout(Stdio::null()).stderr(Stdio::null());
}
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
}
cmd.stdin(Stdio::null());
match cmd.spawn() {
Ok(child) => {
log(&format!("backend started (pid {})", child.id()));
#[cfg(windows)]
if let Some(job) = job::Job::kill_on_close() {
if job.assign(&child) {
*state.job.lock().unwrap() = Some(job);
}
}
*state.child.lock().unwrap() = Some(child);
}
Err(err) => log(&format!("failed to spawn backend: {err}")),
}
state
}
fn backend_command() -> Result<Command, String> {
if let Some(exe) = std::env::var_os("SHOWY_BACKEND_EXE") {
let exe = PathBuf::from(exe);
return exe_command(exe);
}
if cfg!(debug_assertions) {
let dir = std::env::var_os("SHOWY_BACKEND_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../backend")
});
let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
if !dir.join("server.js").is_file() {
return Err(format!("no server.js in {}", dir.display()));
}
let mut cmd = Command::new("node");
cmd.arg("server.js").current_dir(dir);
Ok(cmd)
} else {
let exe_dir = std::env::current_exe()
.map_err(|e| e.to_string())?
.parent()
.map(PathBuf::from)
.ok_or("cannot resolve the app folder")?;
let name = if cfg!(windows) { "backend.exe" } else { "backend" };
exe_command(exe_dir.join(name))
}
}
fn exe_command(exe: PathBuf) -> Result<Command, String> {
if !exe.is_file() {
return Err(format!("backend executable not found: {}", exe.display()));
}
let mut cmd = Command::new(&exe);
if let Some(dir) = exe.parent() {
cmd.current_dir(dir);
}
Ok(cmd)
}
fn port_in_use(port: u16) -> bool {
let addr = SocketAddr::from(([127, 0, 0, 1], port));
TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_ok()
}
fn log(msg: &str) {
eprintln!("[showy] {msg}");
}
/// A Windows job object that kills every process in it when its handle closes,
/// including when the app crashes, so the backend never outlives the window.
#[cfg(windows)]
mod job {
use std::os::windows::io::AsRawHandle;
use std::process::Child;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
pub struct Job(HANDLE);
// The handle is only used behind a Mutex and closed once.
unsafe impl Send for Job {}
impl Job {
pub fn kill_on_close() -> Option<Job> {
unsafe {
let handle = CreateJobObjectW(std::ptr::null(), std::ptr::null());
if handle.is_null() {
return None;
}
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let ok = SetInformationJobObject(
handle,
JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
std::mem::size_of_val(&info) as u32,
);
if ok == 0 {
CloseHandle(handle);
return None;
}
Some(Job(handle))
}
}
pub fn assign(&self, child: &Child) -> bool {
unsafe { AssignProcessToJobObject(self.0, child.as_raw_handle() as HANDLE) != 0 }
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
}
+29
View File
@@ -0,0 +1,29 @@
mod backend;
use tauri::{Manager, RunEvent};
pub fn run() {
let app = tauri::Builder::default()
.setup(|app| {
let state = backend::start(app.handle());
app.manage(state);
#[cfg(debug_assertions)]
if std::env::var("SHOWY_NO_DEVTOOLS").is_err() {
if let Some(window) = app.get_webview_window("main") {
window.open_devtools();
}
}
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building the Showy Tauri app");
app.run(|handle, event| {
if let RunEvent::Exit = event {
if let Some(state) = handle.try_state::<backend::BackendState>() {
state.stop();
}
}
});
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents an additional console window on Windows in release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
showy_lib::run()
}
+6
View File
@@ -0,0 +1,6 @@
{
"$schema": "https://schema.tauri.app/config/2",
"bundle": {
"externalBin": ["binaries/backend"]
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Showy",
"version": "2.0.0",
"identifier": "x4lo.showy",
"build": {
"beforeDevCommand": "pnpm --dir ../react_frontend dev:tauri",
"devUrl": "http://localhost:4200",
"beforeBuildCommand": "pnpm --dir ../react_frontend build:tauri",
"frontendDist": "../frontend_build"
},
"app": {
"windows": [
{
"label": "main",
"title": "Showy",
"width": 1280,
"height": 800,
"minWidth": 900,
"minHeight": 600,
"decorations": false,
"backgroundColor": "#09090b",
"center": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": ["nsis"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}