feat: watchlist (premium), mobile bottom nav
Build & Push Docker Image / build (push) Successful in 2m35s

This commit is contained in:
opencode
2026-08-02 13:00:10 +02:00
parent c77610786b
commit d033b20dfb
14 changed files with 383 additions and 12 deletions
+44 -3
View File
@@ -1,11 +1,11 @@
import { Router, type IRouter, type Request } from "express";
import { Issuer, generators, type Client } from "openid-client";
import bcrypt from "bcryptjs";
import { eq } from "drizzle-orm";
import { eq, and, inArray, isNull } from "drizzle-orm";
import { z } from "zod";
import { db, usersTable } from "@workspace/db";
import { db, usersTable, toolsTable, ratingsTable } from "@workspace/db";
import { logger } from "../lib/logger";
import { getEntitlements } from "../middleware/feature";
import { getEntitlements, requireFeature } from "../middleware/feature";
const router: IRouter = Router();
@@ -301,6 +301,7 @@ async function resolveDbUser(u: SessionUser) {
const PreferenceSchema = z.object({
view: z.enum(["grid", "table", "rows"]).optional(),
density: z.enum(["cozy", "compact"]).optional(),
watchlist: z.array(z.number().int().positive()).max(50).optional(),
});
router.get("/auth/me/preferences", async (req, res): Promise<void> => {
@@ -316,6 +317,46 @@ router.get("/auth/me/preferences", async (req, res): Promise<void> => {
res.json(dbUser.preferences ?? {});
});
router.get("/auth/me/watchlist", requireFeature("watchlist"), async (req, res): Promise<void> => {
const dbUser = await resolveDbUser(req.session.user!);
if (!dbUser) {
res.status(401).json({ error: "User not found" });
return;
}
const ids = (dbUser.preferences?.watchlist ?? []).filter((id) => Number.isInteger(id));
if (ids.length === 0) {
res.json([]);
return;
}
const tools = await db
.select()
.from(toolsTable)
.where(and(isNull(toolsTable.deletedAt), inArray(toolsTable.id, ids)));
const ratings = await db
.select({ toolId: ratingsTable.toolId, usefulness: ratingsTable.usefulness, usability: ratingsTable.usability })
.from(ratingsTable)
.where(inArray(ratingsTable.toolId, tools.map((t) => t.id)));
const byTool = new Map<number, { usefulness: number; usability: number }[]>();
for (const r of ratings) {
const list = byTool.get(r.toolId) ?? [];
list.push({ usefulness: r.usefulness, usability: r.usability });
byTool.set(r.toolId, list);
}
const byId = new Map(tools.map((t) => [t.id, t]));
const ordered = ids
.filter((id) => byId.has(id))
.map((id) => {
const tool = byId.get(id)!;
const toolRatings = byTool.get(id) ?? [];
const ratingCount = toolRatings.length;
const avgUsefulness = ratingCount > 0 ? toolRatings.reduce((s, r) => s + r.usefulness, 0) / ratingCount : null;
const avgUsability = ratingCount > 0 ? toolRatings.reduce((s, r) => s + r.usability, 0) / ratingCount : null;
const avgCombined = avgUsefulness != null && avgUsability != null ? (avgUsefulness + avgUsability) / 2 : null;
return { ...tool, ratingCount, avgUsefulness, avgUsability, avgCombined };
});
res.json(ordered);
});
router.put("/auth/me/preferences", async (req, res): Promise<void> => {
if (!req.session.user) {
res.status(401).json({ error: "Not authenticated" });
+2
View File
@@ -14,6 +14,7 @@ import Admin from "@/pages/admin";
import Redundancy from "@/pages/redundancy";
import Trash from "@/pages/trash";
import Compare from "@/pages/compare";
import Watchlist from "@/pages/watchlist";
import Login from "@/pages/login";
import NotFound from "@/pages/not-found";
@@ -36,6 +37,7 @@ function Router() {
<Route path="/tools/:id/edit" component={ToolEdit} />
<Route path="/tools/:id" component={ToolDetail} />
<Route path="/compare" component={Compare} />
<Route path="/watchlist" component={Watchlist} />
<Route path="/analytics" component={Analytics} />
<Route path="/admin" component={Admin} />
<Route path="/admin/redundancy" component={Redundancy} />
+30 -2
View File
@@ -1,5 +1,5 @@
import { Link, useLocation } from "wouter";
import { LayoutDashboard, Wrench, PlusCircle, BarChart3, LogIn, LogOut, User, ShieldCheck, AlertTriangle, Trash2 } from "lucide-react";
import { LayoutDashboard, Wrench, PlusCircle, BarChart3, LogIn, LogOut, User, ShieldCheck, AlertTriangle, Trash2, Bookmark } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { useGetVersion, getGetVersionQueryKey } from "@workspace/api-client-react";
import { Button } from "@/components/ui/button";
@@ -19,6 +19,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
{ href: "/tools", label: "Browse Tools", icon: Wrench },
{ href: "/tools/new", label: "Add Tool", icon: PlusCircle },
{ href: "/analytics", label: "Analytics", icon: BarChart3 },
...(hasFeature("watchlist") ? [{ href: "/watchlist", label: "Watchlist", icon: Bookmark }] : []),
...(hasFeature("trash") ? [{ href: "/trash", label: "Trash", icon: Trash2 }] : []),
...(isAdmin ? [{ href: "/admin", label: "Admin", icon: ShieldCheck }] : []),
...(isAdmin ? [{ href: "/admin/redundancy", label: "Redundancy", icon: AlertTriangle }] : []),
@@ -28,6 +29,14 @@ export function Layout({ children }: { children: React.ReactNode }) {
(link) => location === link.href || (link.href !== "/" && location.startsWith(link.href)),
);
const mobileLinks = [
{ href: "/", label: "Home", icon: LayoutDashboard },
{ href: "/tools", label: "Tools", icon: Wrench },
...(hasFeature("watchlist") ? [{ href: "/watchlist", label: "Watchlist", icon: Bookmark }] : []),
...(hasFeature("trash") ? [{ href: "/trash", label: "Trash", icon: Trash2 }] : []),
{ href: "/analytics", label: "Analytics", icon: BarChart3 },
].slice(0, 5);
return (
<div className="flex min-h-screen bg-background text-foreground">
<CommandPalette />
@@ -149,10 +158,29 @@ export function Layout({ children }: { children: React.ReactNode }) {
)}
</div>
</header>
<div className="flex-1 p-6 md:p-8 overflow-auto">
<div className="flex-1 p-6 md:p-8 overflow-auto pb-24 md:pb-8">
{children}
</div>
</main>
<nav className="md:hidden fixed bottom-0 inset-x-0 z-40 border-t bg-card/95 backdrop-blur flex">
{mobileLinks.map((link) => {
const isActive = location === link.href || (link.href !== "/" && location.startsWith(link.href));
const Icon = link.icon;
return (
<Link
key={link.href}
href={link.href}
className={`flex-1 flex flex-col items-center gap-0.5 py-2.5 text-[10px] font-medium transition-colors ${
isActive ? "text-primary" : "text-muted-foreground hover:text-foreground"
}`}
>
<Icon className="w-5 h-5" />
{link.label}
</Link>
);
})}
</nav>
</div>
);
}
@@ -1,7 +1,7 @@
import { ToolWithStats } from "@workspace/api-client-react";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Star, MessageSquare, Wrench, Scale } from "lucide-react";
import { Star, MessageSquare, Wrench, Scale, Bookmark } from "lucide-react";
import { Link } from "wouter";
import { MiniBars } from "@/components/mini-bars";
import { cn } from "@/lib/utils";
@@ -9,9 +9,11 @@ import { cn } from "@/lib/utils";
export function ToolCard({
tool,
compare,
watchlist,
}: {
tool: ToolWithStats;
compare?: { selected: boolean; onToggle: () => void };
watchlist?: { watched: boolean; onToggle: () => void };
}) {
return (
<Card className="hover-elevate transition-all flex flex-col h-full cursor-pointer hover:border-primary/50">
@@ -70,8 +72,27 @@ export function ToolCard({
</div>
</div>
</div>
<div className={cn("items-center gap-3", compare ? "flex" : "")}>
<MiniBars usefulness={tool.avgUsefulness} usability={tool.avgUsability} className={compare ? "flex-1" : undefined} />
<div className={cn("items-center gap-3", (compare || watchlist) ? "flex" : "")}>
<MiniBars usefulness={tool.avgUsefulness} usability={tool.avgUsability} className={(compare || watchlist) ? "flex-1" : undefined} />
{watchlist && (
<button
type="button"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
watchlist.onToggle();
}}
title={watchlist.watched ? "Remove from watchlist" : "Add to watchlist"}
className={cn(
"shrink-0 w-8 h-8 rounded-md border flex items-center justify-center transition-colors",
watchlist.watched
? "bg-primary text-primary-foreground border-primary"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Bookmark className={cn("w-4 h-4", watchlist.watched && "fill-current")} />
</button>
)}
{compare && (
<button
type="button"
@@ -0,0 +1,49 @@
import {
useGetMePreferences,
useUpdateMePreferences,
getGetMePreferencesQueryKey,
getGetMeWatchlistQueryKey,
} from "@workspace/api-client-react";
import { useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
export function useWatchlist() {
const { isAuthenticated, hasFeature } = useAuth();
const queryClient = useQueryClient();
const canWatchlist = isAuthenticated && hasFeature("watchlist");
const { data: prefs, isLoading } = useGetMePreferences({
query: { queryKey: getGetMePreferencesQueryKey(), enabled: canWatchlist, retry: false },
});
const update = useUpdateMePreferences();
const watchlist = prefs?.watchlist ?? [];
function invalidate() {
queryClient.invalidateQueries({ queryKey: getGetMePreferencesQueryKey() });
queryClient.invalidateQueries({ queryKey: getGetMeWatchlistQueryKey() });
}
function toggle(id: number) {
const next = watchlist.includes(id) ? watchlist.filter((x) => x !== id) : [...watchlist, id];
update.mutate(
{ data: { watchlist: next } },
{
onSuccess: () => invalidate(),
onError: () => invalidate(),
},
);
}
const isWatched = (id: number) => watchlist.includes(id);
return {
watchlist,
toggle,
isWatched,
canWatchlist,
isLoading: canWatchlist && isLoading,
};
}
+15 -1
View File
@@ -41,9 +41,11 @@ import {
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line, Legend } from "recharts";
import { ExternalLink, Star, ArrowLeft, Plus, Pencil, Trash2, Link as LinkIcon, DollarSign, Euro } from "lucide-react";
import { ExternalLink, Star, ArrowLeft, Plus, Pencil, Trash2, Link as LinkIcon, DollarSign, Euro, Bookmark } from "lucide-react";
import { Link } from "wouter";
import { useAuth } from "@/hooks/use-auth";
import { useWatchlist } from "@/hooks/use-watchlist";
import { cn } from "@/lib/utils";
import { useDeleteTool, getListToolsQueryKey } from "@workspace/api-client-react";
import {
AlertDialog,
@@ -77,6 +79,7 @@ export default function ToolDetail() {
const [deleteOpen, setDeleteOpen] = useState(false);
const { user, isAdmin, hasFeature } = useAuth();
const { isWatched, toggle: toggleWatchlist, canWatchlist } = useWatchlist();
const canManageCosts = hasFeature("costs");
const hasTrash = hasFeature("trash");
const deleteTool = useDeleteTool();
@@ -355,6 +358,17 @@ export default function ToolDetail() {
Based on {tool.ratingCount} reviews
</div>
{canWatchlist && (
<Button
variant={isWatched(id) ? "default" : "outline"}
className="w-full gap-2"
onClick={() => toggleWatchlist(Number(id))}
>
<Bookmark className={cn("w-4 h-4", isWatched(id) && "fill-current")} />
{isWatched(id) ? "Saved to watchlist" : "Save to watchlist"}
</Button>
)}
{tool.websiteUrl && (
<Button asChild className="w-full mt-2" variant="outline">
<a href={tool.websiteUrl} target="_blank" rel="noopener noreferrer">
@@ -17,6 +17,7 @@ import { FilterPopover } from "@/components/filter-popover";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { useBrowsePreferences, isViewMode, isDensity } from "@/hooks/use-browse-preferences";
import { useAuth } from "@/hooks/use-auth";
import { useWatchlist } from "@/hooks/use-watchlist";
import { CompareBar } from "@/components/compare-bar";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
@@ -87,6 +88,7 @@ export default function ToolsBrowse() {
const { serverView, serverDensity, localView, localDensity, persist } = useBrowsePreferences();
const { hasFeature } = useAuth();
const { isWatched, toggle: toggleWatchlist, canWatchlist } = useWatchlist();
const [compareIds, setCompareIds] = useState<number[]>([]);
const [compareUpsellOpen, setCompareUpsellOpen] = useState(false);
@@ -402,6 +404,7 @@ export default function ToolsBrowse() {
key={tool.id}
tool={tool}
compare={{ selected: compareIds.includes(tool.id), onToggle: () => toggleCompare(tool.id) }}
watchlist={canWatchlist ? { watched: isWatched(tool.id), onToggle: () => toggleWatchlist(tool.id) } : undefined}
/>
))}
</div>
@@ -0,0 +1,76 @@
import {
useGetMeWatchlist,
getGetMeWatchlistQueryKey,
} from "@workspace/api-client-react";
import { useAuth } from "@/hooks/use-auth";
import { useWatchlist } from "@/hooks/use-watchlist";
import { Layout } from "@/components/layout";
import { ToolCard } from "@/components/tool-card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { ShieldAlert, Bookmark } from "lucide-react";
export default function Watchlist() {
const { hasFeature, isLoading: authLoading } = useAuth();
const { toggle } = useWatchlist();
const canWatchlist = hasFeature("watchlist");
const { data: tools, isLoading: loading } = useGetMeWatchlist({
query: { queryKey: getGetMeWatchlistQueryKey(), enabled: canWatchlist },
});
if (!authLoading && !canWatchlist) {
return (
<Layout>
<div className="flex flex-col items-center justify-center py-20 gap-4">
<ShieldAlert className="w-12 h-12 text-muted-foreground" />
<h2 className="text-2xl font-bold">Watchlist requires a higher tier</h2>
<p className="text-muted-foreground">Saving tools to your watchlist is available to Premium and Enterprise users.</p>
<Button variant="outline" asChild>
<a href="/tools">Back to tools</a>
</Button>
</div>
</Layout>
);
}
const list = tools ?? [];
return (
<Layout>
<div className="space-y-6 pb-10">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-2">Watchlist</h1>
<p className="text-muted-foreground">Tools you saved for later, with live scores.</p>
</div>
{loading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{[1, 2, 3, 4].map((i) => <Skeleton key={i} className="h-[200px] w-full rounded-xl" />)}
</div>
) : list.length === 0 ? (
<div className="bg-muted/30 border border-dashed rounded-xl py-24 flex flex-col items-center justify-center text-center gap-3">
<Bookmark className="w-8 h-8 text-muted-foreground" />
<h3 className="text-xl font-medium">Your watchlist is empty</h3>
<p className="text-muted-foreground max-w-md mx-auto">
Browse tools and click the bookmark to save them here.
</p>
<Button variant="outline" asChild>
<a href="/tools">Browse tools</a>
</Button>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{list.map((tool) => (
<ToolCard
key={tool.id}
tool={tool}
watchlist={{ watched: true, onToggle: () => toggle(tool.id) }}
/>
))}
</div>
)}
</div>
</Layout>
);
}