Add Watch Buddies feature
- Created WatchBuddy model - M:N junctions to EntrySeen/EpisodeSeen and Media relation for profile pictures - Full CRUD + search + profile picture upload - WatchBuddySelect multi-select with search and inline create, replaced all seen_with text inputs - WatchBuddiesPage (grid) and WatchBuddyProfilePage (edit form, icon-based contacts, poster-grid watch history, monthly timeline)
This commit is contained in:
1 parent
4313a794ce
commit
e82b905886
28 files changed
+6813
-374
No files matched your search
@@ -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 { WatchBuddySelect } from "@/components/watch-buddy/WatchBuddySelect";
|
||||
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'),
|
||||
seen_with: z.string().optional(),
|
||||
accuracy: z.enum(['EXACT', 'ESTIMATED', 'UNKNOWN']).default('EXACT'),
|
||||
date_seen: z.string().min(1, "Date is required"),
|
||||
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,10 @@ export function EntrySeenDialog({
|
||||
mode,
|
||||
editRecord,
|
||||
}: EntrySeenDialogProps) {
|
||||
const [selectedSeasonId, setSelectedSeasonId] = useState<string>('');
|
||||
const [selectedSeasonId, setSelectedSeasonId] = useState<string>("");
|
||||
const [buddyIds, setBuddyIds] = useState<number[]>(
|
||||
editRecord?.buddies?.map((b) => b.id) ?? [],
|
||||
);
|
||||
|
||||
const isTV = entry.is_tvseries;
|
||||
const seasonList = Array.isArray(seasons) ? seasons : [];
|
||||
@@ -64,15 +67,19 @@ 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?.split("T")[0] ||
|
||||
format(new Date(), "yyyy-MM-dd"),
|
||||
date_seen:
|
||||
editRecord?.date_seen?.split("T")[0] ||
|
||||
format(new Date(), "yyyy-MM-dd"),
|
||||
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();
|
||||
@@ -83,27 +90,28 @@ export function EntrySeenDialog({
|
||||
);
|
||||
|
||||
const onSubmit = (data: Record<string, string | undefined>) => {
|
||||
const acc = (data.accuracy as SeenAccuracy) || 'EXACT';
|
||||
const acc = (data.accuracy as SeenAccuracy) || "EXACT";
|
||||
const buddyIdsToSend = buddyIds;
|
||||
if (isTV && data.episode_id) {
|
||||
createEpisodeSeen.mutate(
|
||||
{
|
||||
entry_id: entry.id,
|
||||
episode_id: parseInt(data.episode_id),
|
||||
date_seen: data.date_seen!,
|
||||
seen_with: data.seen_with || undefined,
|
||||
accuracy: acc,
|
||||
buddy_ids: buddyIdsToSend,
|
||||
},
|
||||
{ onSuccess: () => onOpenChange(false) },
|
||||
);
|
||||
} else if (mode === 'edit' && editRecord) {
|
||||
} else if (mode === "edit" && editRecord) {
|
||||
updateEntrySeen.mutate(
|
||||
{
|
||||
id: editRecord.id,
|
||||
data: {
|
||||
entry_id: entry.id,
|
||||
date_seen: data.date_seen,
|
||||
seen_with: data.seen_with || undefined,
|
||||
accuracy: acc,
|
||||
buddy_ids: buddyIdsToSend,
|
||||
},
|
||||
},
|
||||
{ onSuccess: () => onOpenChange(false) },
|
||||
@@ -113,8 +121,8 @@ export function EntrySeenDialog({
|
||||
{
|
||||
entry_id: entry.id,
|
||||
date_seen: data.date_seen!,
|
||||
seen_with: data.seen_with || undefined,
|
||||
accuracy: acc,
|
||||
buddy_ids: buddyIdsToSend,
|
||||
},
|
||||
{ onSuccess: () => onOpenChange(false) },
|
||||
);
|
||||
@@ -126,7 +134,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">
|
||||
@@ -140,8 +148,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 className="w-full">
|
||||
@@ -152,7 +160,7 @@ export function EntrySeenDialog({
|
||||
(s) => s.id.toString() === selectedSeasonId,
|
||||
);
|
||||
return s?.season_number === 0
|
||||
? 'Specials'
|
||||
? "Specials"
|
||||
: `Season ${s?.season_number}`;
|
||||
})()
|
||||
: null}
|
||||
@@ -168,7 +176,7 @@ export function EntrySeenDialog({
|
||||
.map((s) => (
|
||||
<SelectItem key={s.id} value={s.id.toString()}>
|
||||
{s.season_number === 0
|
||||
? 'Specials'
|
||||
? "Specials"
|
||||
: `Season ${s.season_number}`}
|
||||
</SelectItem>
|
||||
))}
|
||||
@@ -179,14 +187,14 @@ export function EntrySeenDialog({
|
||||
<div className="space-y-2">
|
||||
<Label>Episode</Label>
|
||||
<Select
|
||||
value={watch('episode_id')}
|
||||
onValueChange={(v) => setValue('episode_id', v)}
|
||||
value={watch("episode_id")}
|
||||
onValueChange={(v) => setValue("episode_id", v)}
|
||||
disabled={!selectedSeason}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select episode">
|
||||
{(() => {
|
||||
const epId = watch('episode_id');
|
||||
const epId = watch("episode_id");
|
||||
if (!epId || !selectedSeason?.episodes) return null;
|
||||
const ep = selectedSeason.episodes.find(
|
||||
(e) => e.id.toString() === epId,
|
||||
@@ -227,9 +235,9 @@ export function EntrySeenDialog({
|
||||
<Label>Date Seen</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={watch('date_seen')}
|
||||
value={watch("date_seen")}
|
||||
onChange={(e) => {
|
||||
setValue('date_seen', e.target.value);
|
||||
setValue("date_seen", e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -237,7 +245,7 @@ export function EntrySeenDialog({
|
||||
<Label>Accuracy</Label>
|
||||
<Select
|
||||
value={accuracyValue}
|
||||
onValueChange={(v) => setValue('accuracy', v as SeenAccuracy)}
|
||||
onValueChange={(v) => setValue("accuracy", v as SeenAccuracy)}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
@@ -258,11 +266,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"
|
||||
<Label>Seen With</Label>
|
||||
<WatchBuddySelect
|
||||
selectedIds={buddyIds}
|
||||
onChange={setBuddyIds}
|
||||
initialBuddies={editRecord?.buddies}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -292,7 +300,7 @@ export function EntrySeenDialog({
|
||||
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>
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
useUpdateEpisodeSeen,
|
||||
useCreateEpisodeSeen,
|
||||
} from "@/hooks/useEpisodeSeen";
|
||||
import { WatchBuddySelect } from "@/components/watch-buddy/WatchBuddySelect";
|
||||
import type { EpisodeSeen, SeenAccuracy } from "@/types";
|
||||
|
||||
interface EpisodeSeenEditDialogProps {
|
||||
@@ -52,7 +53,9 @@ export function EpisodeSeenEditDialog({
|
||||
}: 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 [buddyIds, setBuddyIds] = useState<number[]>(
|
||||
record?.buddies?.map((b) => b.id) ?? [],
|
||||
);
|
||||
const [accuracy, setAccuracy] = useState<SeenAccuracy>(
|
||||
record?.accuracy ?? "EXACT",
|
||||
);
|
||||
@@ -62,9 +65,10 @@ export function EpisodeSeenEditDialog({
|
||||
|
||||
const handleSave = () => {
|
||||
if (overrideSubmit) {
|
||||
overrideSubmit(date, seenWith, accuracy);
|
||||
overrideSubmit(date, "", accuracy);
|
||||
return;
|
||||
}
|
||||
const buddyIdsToSend = buddyIds;
|
||||
if (mode === "edit" && record) {
|
||||
updateEpisodeSeen.mutate({
|
||||
id: record.id,
|
||||
@@ -72,8 +76,8 @@ export function EpisodeSeenEditDialog({
|
||||
episode_id: record.episode_id,
|
||||
entry_id: entryId,
|
||||
date_seen: date,
|
||||
seen_with: seenWith || null,
|
||||
accuracy,
|
||||
buddy_ids: buddyIdsToSend,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -83,9 +87,9 @@ export function EpisodeSeenEditDialog({
|
||||
entry_id: entryId,
|
||||
episode_id: epId,
|
||||
date_seen: date,
|
||||
seen_with: seenWith || undefined,
|
||||
accuracy,
|
||||
season_id: seasonId,
|
||||
buddy_ids: buddyIdsToSend,
|
||||
});
|
||||
}
|
||||
onOpenChange(false);
|
||||
@@ -126,12 +130,11 @@ export function EpisodeSeenEditDialog({
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="seen-with">Seen With</Label>
|
||||
<Input
|
||||
id="seen-with"
|
||||
value={seenWith}
|
||||
onChange={(e) => setSeenWith(e.target.value)}
|
||||
placeholder="Optional"
|
||||
<Label>Seen With</Label>
|
||||
<WatchBuddySelect
|
||||
selectedIds={buddyIds}
|
||||
onChange={setBuddyIds}
|
||||
initialBuddies={record?.buddies}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { format } from "date-fns";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -6,7 +7,8 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Trash2, Pencil, Users } from "lucide-react";
|
||||
import type { EntrySeen } from "@/types";
|
||||
|
||||
interface MovieWatchHistoryDialogProps {
|
||||
@@ -15,6 +17,7 @@ interface MovieWatchHistoryDialogProps {
|
||||
entryId: number;
|
||||
watchHistory: EntrySeen[];
|
||||
onDelete: (seenId: number) => void;
|
||||
onEdit?: (record: EntrySeen) => void;
|
||||
}
|
||||
|
||||
export function MovieWatchHistoryDialog({
|
||||
@@ -22,15 +25,16 @@ export function MovieWatchHistoryDialog({
|
||||
onOpenChange,
|
||||
watchHistory,
|
||||
onDelete,
|
||||
onEdit,
|
||||
}: MovieWatchHistoryDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Watch History</DialogTitle>
|
||||
</DialogHeader>
|
||||
{watchHistory.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-4">
|
||||
<p className="py-4 text-sm text-muted-foreground">
|
||||
No watch history yet.
|
||||
</p>
|
||||
) : (
|
||||
@@ -39,7 +43,12 @@ export function MovieWatchHistoryDialog({
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted/50">
|
||||
<th className="px-4 py-2 text-left font-medium">Date</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Seen With</th>
|
||||
<th className="px-4 py-2 text-left font-medium">
|
||||
<span className="flex items-center gap-1">
|
||||
<Users className="h-3 w-3" />
|
||||
Buddies
|
||||
</span>
|
||||
</th>
|
||||
<th className="px-4 py-2 text-right font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -54,11 +63,36 @@ export function MovieWatchHistoryDialog({
|
||||
? format(new Date(record.date_seen), "MMM d, yyyy")
|
||||
: "-"}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-muted-foreground">
|
||||
{record.seen_with || "-"}
|
||||
<td className="px-4 py-2">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{record.buddies && record.buddies.length > 0 ? (
|
||||
record.buddies.map((b) => (
|
||||
<Link key={b.id} to={`/watch-buddies/${b.id}`}>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="text-xs hover:bg-accent cursor-pointer"
|
||||
>
|
||||
{b.name}
|
||||
</Badge>
|
||||
</Link>
|
||||
))
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<div className="flex justify-end">
|
||||
<div className="flex justify-end gap-1">
|
||||
{onEdit && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-7 w-7"
|
||||
onClick={() => onEdit(record)}
|
||||
>
|
||||
<Pencil className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { format } from "date-fns";
|
||||
import { Link } from "react-router-dom";
|
||||
import type { EntrySeen, EpisodeSeen } from "@/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Pencil, Trash2, Users } from "lucide-react";
|
||||
|
||||
interface EpisodeWatchHistoryProps {
|
||||
watchHistory: (EntrySeen | EpisodeSeen)[];
|
||||
@@ -28,7 +30,12 @@ export function EpisodeWatchHistory({
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted/50">
|
||||
<th className="px-4 py-2 text-left font-medium">Date</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Seen With</th>
|
||||
<th className="px-4 py-2 text-left font-medium">
|
||||
<span className="flex items-center gap-1">
|
||||
<Users className="h-3 w-3" />
|
||||
Buddies
|
||||
</span>
|
||||
</th>
|
||||
<th className="px-4 py-2 text-right font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -43,8 +50,23 @@ export function EpisodeWatchHistory({
|
||||
? format(new Date(record.date_seen), "MMM d, yyyy")
|
||||
: "-"}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-muted-foreground">
|
||||
{record.seen_with || "-"}
|
||||
<td className="px-4 py-2">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{record.buddies && record.buddies.length > 0 ? (
|
||||
record.buddies.map((b) => (
|
||||
<Link key={b.id} to={`/watch-buddies/${b.id}`}>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-pointer text-xs hover:bg-accent"
|
||||
>
|
||||
{b.name}
|
||||
</Badge>
|
||||
</Link>
|
||||
))
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<div className="flex justify-end gap-1">
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Image,
|
||||
CalendarDays,
|
||||
Users,
|
||||
UserRoundPlus,
|
||||
Settings,
|
||||
Moon,
|
||||
Sun,
|
||||
@@ -31,6 +32,7 @@ const libraryNav = [
|
||||
const otherNav = [
|
||||
{ to: "/calendar", icon: CalendarDays, label: "Calendar" },
|
||||
{ to: "/people", icon: Users, label: "People" },
|
||||
{ to: "/watch-buddies", icon: UserRoundPlus, label: "Buddies" },
|
||||
];
|
||||
|
||||
function NavItem({
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { watchBuddyApi } from "@/api/watchBuddy";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Loader2, Plus, X, Users } from "lucide-react";
|
||||
import { useDebounce } from "@/hooks/useDebounce";
|
||||
import type { WatchBuddy } from "@/types";
|
||||
|
||||
interface WatchBuddySelectProps {
|
||||
selectedIds: number[];
|
||||
onChange: (ids: number[]) => void;
|
||||
initialBuddies?: WatchBuddy[];
|
||||
}
|
||||
|
||||
export function WatchBuddySelect({
|
||||
selectedIds,
|
||||
onChange,
|
||||
initialBuddies = [],
|
||||
}: WatchBuddySelectProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [localBuddies, setLocalBuddies] = useState<WatchBuddy[]>([]);
|
||||
const debouncedSearch = useDebounce(search, 200);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data: options = [], isLoading } = useQuery({
|
||||
queryKey: ["watch-buddies", debouncedSearch],
|
||||
queryFn: () => watchBuddyApi.search(debouncedSearch || undefined),
|
||||
});
|
||||
|
||||
// Display: initialBuddies + locally created/selected ones
|
||||
const displayed = [
|
||||
...initialBuddies.filter((b) => selectedIds.includes(b.id)),
|
||||
...localBuddies.filter((b) => selectedIds.includes(b.id)),
|
||||
];
|
||||
|
||||
// Check if typed name exactly matches an existing buddy
|
||||
const hasExactMatch =
|
||||
search.trim().length > 0 &&
|
||||
options.some((b) => b.name.toLowerCase() === search.trim().toLowerCase());
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node))
|
||||
setOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", handler);
|
||||
return () => document.removeEventListener("mousedown", handler);
|
||||
}, []);
|
||||
|
||||
const toggle = (id: number) => {
|
||||
const isSelected = selectedIds.includes(id);
|
||||
if (!isSelected) {
|
||||
const buddy = options.find((b) => b.id === id);
|
||||
if (buddy && !localBuddies.some((b) => b.id === id)) {
|
||||
setLocalBuddies((prev) => [...prev, buddy]);
|
||||
}
|
||||
}
|
||||
onChange(
|
||||
isSelected ? selectedIds.filter((i) => i !== id) : [...selectedIds, id],
|
||||
);
|
||||
setSearch("");
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!search.trim()) return;
|
||||
setCreating(true);
|
||||
try {
|
||||
const buddy = await watchBuddyApi.create({ name: search.trim() });
|
||||
queryClient.invalidateQueries({ queryKey: ["watch-buddies"] });
|
||||
setLocalBuddies((prev) => [...prev, buddy]);
|
||||
onChange([...selectedIds, buddy.id]);
|
||||
setSearch("");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(!open)}
|
||||
className="flex min-h-9 w-full flex-wrap items-center gap-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{displayed.length > 0 ? (
|
||||
displayed.map((b) => (
|
||||
<Badge key={b.id} variant="secondary" className="gap-1 text-xs">
|
||||
{b.name}
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onChange(selectedIds.filter((i) => i !== b.id));
|
||||
}}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Users className="h-3.5 w-3.5" />
|
||||
Select buddies
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute z-50 mt-1 w-full rounded-md border border-border bg-popover p-2 shadow-lg">
|
||||
<Input
|
||||
placeholder="Search or type name to create..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="h-8 text-xs mb-2"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<div className="max-h-40 space-y-0.5 overflow-y-auto">
|
||||
{isLoading && (
|
||||
<div className="flex justify-center py-3">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && options.length === 0 && search.trim() && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreate}
|
||||
disabled={creating}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
{creating ? "Creating..." : `Create "${search.trim()}"`}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{!isLoading &&
|
||||
options.map((b) => (
|
||||
<label
|
||||
key={b.id}
|
||||
className={`flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent ${
|
||||
selectedIds.includes(b.id) ? "bg-accent" : ""
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.includes(b.id)}
|
||||
onChange={() => toggle(b.id)}
|
||||
className="h-3.5 w-3.5 rounded"
|
||||
/>
|
||||
{b.name}
|
||||
</label>
|
||||
))}
|
||||
|
||||
{!isLoading &&
|
||||
search.trim() &&
|
||||
!hasExactMatch &&
|
||||
options.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreate}
|
||||
disabled={creating}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
{creating ? "Creating..." : `Create "${search.trim()}"`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user