feat: first commit

This commit is contained in:
sittichok Ouamsiri committed 2026-06-15 21:25:57 +07:00
commit 3395ab6dd3
88 files changed
+10034

No files matched your search

+410
View File
@@ -0,0 +1,410 @@
import { AnimatePresence, motion } from "framer-motion";
import { useCallback, useEffect, useRef, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import { api } from "../lib/api";
import { compactNumber } from "../lib/format";
import type { OwnerStats, ShortLink } from "../lib/types";
import { UrlCard } from "../components/UrlCard";
import { UrlRow } from "../components/UrlRow";
import { Pagination } from "../components/Pagination";
import { PinManager } from "../components/PinManager";
import { EditLinkModal } from "../components/EditLinkModal";
import { DeleteLinkModal } from "../components/DeleteLinkModal";
import { QrModal } from "../components/QrModal";
import { Button } from "../components/ui/Button";
import { useToast } from "../components/ui/Toast";
type View = "comfortable" | "compact";
const PAGE_SIZE: Record<View, number> = { comfortable: 5, compact: 8 };
const pop = {
hidden: { opacity: 0, y: 20, scale: 0.95 },
show: {
opacity: 1,
y: 0,
scale: 1,
transition: { type: "spring", stiffness: 340, damping: 20 },
},
} as const;
function useDebouncedValue<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(t);
}, [value, delay]);
return debounced;
}
function ViewToggle({ view, onChange }: { view: View; onChange: (v: View) => void }) {
const opts: { value: View; icon: string; label: string }[] = [
{ value: "comfortable", icon: "▦", label: "Comfortable view" },
{ value: "compact", icon: "≣", label: "Compact view" },
];
return (
<div className="flex shrink-0 gap-1 rounded-xl border-[1.5px] border-line bg-surface-2 p-1">
{opts.map((o) => (
<button
key={o.value}
onClick={() => onChange(o.value)}
aria-label={o.label}
aria-pressed={view === o.value}
className="focusable relative grid h-8 w-9 place-items-center rounded-lg text-[15px]"
>
{view === o.value && (
<motion.span
layoutId="view-pill"
transition={{ type: "spring", stiffness: 480, damping: 32 }}
className="absolute inset-0 rounded-lg bg-[var(--surface)] shadow-[0_2px_8px_-3px_rgba(0,0,0,0.3)] ring-[1.5px] ring-[var(--ring)]"
/>
)}
<span
className={`relative z-10 ${view === o.value ? "text-ink" : "text-muted"}`}
>
{o.icon}
</span>
</button>
))}
</div>
);
}
export function Dashboard() {
const { user, loading: authLoading } = useAuth();
const navigate = useNavigate();
const toast = useToast();
const [view, setView] = useState<View>(
() => (localStorage.getItem("snip-view") as View) || "comfortable",
);
const [searchParams, setSearchParams] = useSearchParams();
const [pinTarget, setPinTarget] = useState<ShortLink | null>(null);
const [editTarget, setEditTarget] = useState<ShortLink | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ShortLink | null>(null);
const [qrTarget, setQrTarget] = useState<ShortLink | null>(null);
// Server-driven page + aggregate stats (the client never loads all links).
const [pageData, setPageData] = useState<{ items: ShortLink[]; total: number } | null>(null);
const [stats, setStats] = useState<OwnerStats | null>(null);
// Search + page live in the URL (?q=&page=) so they survive a refresh / share.
const query = searchParams.get("q") ?? "";
const debouncedQuery = useDebouncedValue(query, 300);
const rawPage = parseInt(searchParams.get("page") ?? "1", 10);
const requestedPage = Number.isFinite(rawPage) && rawPage > 0 ? rawPage : 1;
const pageSize = PAGE_SIZE[view];
useEffect(() => {
if (!authLoading && !user) navigate("/login");
}, [authLoading, user, navigate]);
useEffect(() => {
localStorage.setItem("snip-view", view);
}, [view]);
// Fetch the current page from the API (debounced search, server pagination).
const reqId = useRef(0);
const loadPage = useCallback(async () => {
if (!user) return;
const id = ++reqId.current;
const res = await api.listLinks({
page: requestedPage,
pageSize,
q: debouncedQuery.trim() || undefined,
});
if (id === reqId.current) {
setPageData({ items: res.items, total: res.total });
}
}, [user, requestedPage, pageSize, debouncedQuery]);
const loadStats = useCallback(async () => {
if (!user) return;
setStats(await api.stats());
}, [user]);
useEffect(() => {
loadPage();
}, [loadPage]);
useEffect(() => {
loadStats();
}, [loadStats]);
const pageCount = pageData ? Math.max(1, Math.ceil(pageData.total / pageSize)) : 1;
const safePage = Math.min(requestedPage, pageCount);
// Keep the URL honest if it points past the last page (deletes, ?page=99…).
useEffect(() => {
if (pageData && requestedPage > pageCount) {
const next = new URLSearchParams(searchParams);
if (pageCount <= 1) next.delete("page");
else next.set("page", String(pageCount));
setSearchParams(next, { replace: true });
}
}, [pageData, requestedPage, pageCount, searchParams, setSearchParams]);
function updateSearch(q: string) {
const next = new URLSearchParams(searchParams);
if (q) next.set("q", q);
else next.delete("q");
next.delete("page"); // a new search jumps back to page 1
setSearchParams(next, { replace: true });
}
function changeView(v: View) {
setView(v);
const next = new URLSearchParams(searchParams);
next.delete("page"); // page sizes differ between views
setSearchParams(next, { replace: true });
}
function goToPage(p: number) {
const next = new URLSearchParams(searchParams);
if (p <= 1) next.delete("page");
else next.set("page", String(p));
setSearchParams(next);
window.scrollTo({ top: 0, behavior: "smooth" });
}
async function handleDeleted(_id: string, message: string) {
setDeleteTarget(null);
toast(message, "info");
await Promise.all([loadPage(), loadStats()]);
}
// Edit / PIN: patch the row in place (totals are unaffected).
function applyUpdate(updated: ShortLink, message: string) {
setPageData((pd) =>
pd
? { ...pd, items: pd.items.map((l) => (l.id === updated.id ? { ...l, ...updated } : l)) }
: pd,
);
toast(message, "success");
}
const items = pageData?.items ?? [];
const total = pageData?.total ?? 0;
const totalLinks = stats?.totalLinks ?? 0;
const statTiles = [
{ label: "Active links", value: compactNumber(totalLinks) },
{ label: "Total clicks", value: compactNumber(stats?.totalClicks ?? 0) },
{
label: "Clicks this week",
value: `+${compactNumber(stats?.weekClicks ?? 0)}`,
accent: true,
},
];
const hasAnyLinks = totalLinks > 0;
return (
<div className="mx-auto max-w-4xl px-4 pb-24 pt-8">
{/* header */}
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ type: "spring", stiffness: 300, damping: 26 }}
className="flex flex-wrap items-end justify-between gap-3"
>
<div>
<h1 className="font-display text-3xl font-bold tracking-tight text-ink sm:text-4xl">
Your links
</h1>
<p className="mt-1 text-sm text-muted">
Search, edit destinations, manage PINs, or retire a link.
</p>
</div>
<Link to="/">
<Button size="md">
<span className="text-lg">+</span> New link
</Button>
</Link>
</motion.div>
{/* stat tiles */}
<div className="mt-6 grid grid-cols-3 gap-3">
{statTiles.map((s, i) => (
<motion.div
key={s.label}
initial={{ opacity: 0, y: 18, scale: 0.94 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{ type: "spring", stiffness: 360, damping: 20, delay: 0.05 * i }}
className="card p-4"
>
<p className="text-[11px] font-medium uppercase tracking-wide text-muted sm:text-xs">
{s.label}
</p>
<p
className={`mt-1 font-display text-2xl font-bold sm:text-3xl ${
s.accent ? "text-accent-ink" : "text-ink"
}`}
>
{s.accent ? (
<span className="rounded-lg bg-accent px-2">{s.value}</span>
) : (
s.value
)}
</p>
</motion.div>
))}
</div>
{/* toolbar: search + view toggle */}
{hasAnyLinks && (
<div className="mt-6 flex items-center gap-2.5">
<div className="flex h-11 flex-1 items-center gap-2 rounded-xl border-[1.5px] border-line bg-surface px-3.5">
<span className="text-muted">⌕</span>
<input
value={query}
onChange={(e) => updateSearch(e.target.value)}
placeholder="Search by code or URL…"
className="h-full w-full bg-transparent text-[15px] text-ink outline-none placeholder:text-muted"
/>
{query && (
<button
onClick={() => updateSearch("")}
aria-label="Clear search"
className="focusable grid h-6 w-6 place-items-center rounded-md text-muted hover:bg-surface-2 hover:text-ink"
>
✕
</button>
)}
</div>
<ViewToggle view={view} onChange={changeView} />
</div>
)}
{/* result meta */}
{hasAnyLinks && (
<p className="mt-3 text-xs text-muted">
{query ? (
<>
<span className="font-semibold text-ink">{total}</span> of {totalLinks}{" "}
{totalLinks === 1 ? "link" : "links"} match “{query}”
</>
) : (
<>
Showing <span className="font-semibold text-ink">{items.length}</span> of{" "}
{totalLinks} {totalLinks === 1 ? "link" : "links"}
</>
)}
</p>
)}
{/* list */}
<div className="mt-4">
{pageData === null ? (
<div className="space-y-4">
{[0, 1, 2].map((i) => (
<div
key={i}
className="card h-28 animate-pulse opacity-60"
style={{ animationDelay: `${i * 120}ms` }}
/>
))}
</div>
) : total === 0 && !debouncedQuery ? (
<motion.div
variants={pop}
initial="hidden"
animate="show"
className="card grid place-items-center gap-3 p-12 text-center"
>
<span className="text-4xl">🪄</span>
<p className="font-display text-xl font-bold text-ink">No links yet</p>
<p className="max-w-xs text-sm text-muted">
Create your first short link and it'll show up here with live click
stats.
</p>
<Link to="/" className="mt-1">
<Button>Create a link</Button>
</Link>
</motion.div>
) : total === 0 ? (
<motion.div
variants={pop}
initial="hidden"
animate="show"
className="card grid place-items-center gap-2 p-10 text-center"
>
<span className="text-3xl">🔍</span>
<p className="font-display text-lg font-bold text-ink">No matches</p>
<p className="text-sm text-muted">Nothing matches “{query}”.</p>
<button
onClick={() => updateSearch("")}
className="focusable mt-1 rounded-lg text-sm font-semibold text-ink underline decoration-accent decoration-2 underline-offset-2"
>
Clear search
</button>
</motion.div>
) : (
<>
<motion.div
layout
className={view === "compact" ? "space-y-2.5" : "space-y-4"}
>
<AnimatePresence mode="popLayout">
{items.map((link) =>
view === "compact" ? (
<UrlRow
key={link.id}
link={link}
onEdit={setEditTarget}
onDelete={setDeleteTarget}
onCopy={() => toast("Copied to clipboard", "success")}
onManagePin={setPinTarget}
onShowQr={setQrTarget}
/>
) : (
<UrlCard
key={link.id}
link={link}
onEdit={setEditTarget}
onDelete={setDeleteTarget}
onCopy={() => toast("Copied to clipboard", "success")}
onManagePin={setPinTarget}
onShowQr={setQrTarget}
/>
),
)}
</AnimatePresence>
</motion.div>
<Pagination page={safePage} pageCount={pageCount} onPage={goToPage} />
</>
)}
</div>
<EditLinkModal
link={editTarget}
onClose={() => setEditTarget(null)}
onSaved={(updated, message) => {
applyUpdate(updated, message);
setEditTarget(null);
}}
/>
<PinManager
link={pinTarget}
onClose={() => setPinTarget(null)}
onSaved={(updated, message) => {
applyUpdate(updated, message);
setPinTarget(null);
}}
/>
<QrModal
link={qrTarget}
onClose={() => setQrTarget(null)}
onCopied={() => toast("Copied to clipboard", "success")}
/>
<DeleteLinkModal
link={deleteTarget}
onClose={() => setDeleteTarget(null)}
onDeleted={handleDeleted}
/>
</div>
);
}