Add guest cart drawer, Continue handoff, and shared customer login.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Alireza Hassani
2026-08-25 17:33:39 +03:30
co-authored by Cursor
parent ad05241a77
commit 16340c3b48
18 changed files with 1082 additions and 97 deletions
+138
View File
@@ -0,0 +1,138 @@
"use client";
import { useEffect, useRef, useState, type MouseEvent } from "react";
import { businessDashboardUrl, customerDashboardUrl } from "@/lib/customer";
import { useSession } from "@/lib/session";
import { IconChevron, IconUser } from "./Icons";
const itemClass =
"block w-full px-3 py-2.5 text-right text-sm text-ink transition-colors hover:bg-brand-soft hover:text-brand";
export function AccountMenu({
displayName,
isWebsiteAdmin,
onLogout,
compact = false,
}: {
displayName: string;
isWebsiteAdmin: boolean;
onLogout: () => void;
compact?: boolean;
}) {
const [open, setOpen] = useState(false);
const [handoffBusy, setHandoffBusy] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const { getAccessToken } = useSession();
useEffect(() => {
if (!open) return;
const onClickOutside = (event: Event) => {
if (menuRef.current && event.target instanceof Node && !menuRef.current.contains(event.target)) {
setOpen(false);
}
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") setOpen(false);
};
document.addEventListener("mousedown", onClickOutside);
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("mousedown", onClickOutside);
document.removeEventListener("keydown", onKeyDown);
};
}, [open]);
async function openBusinessDashboard(event: MouseEvent<HTMLAnchorElement>) {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) {
return;
}
event.preventDefault();
if (handoffBusy) return;
const baseUrl = businessDashboardUrl();
const popup = window.open("about:blank", "_blank");
setHandoffBusy(true);
try {
const token = getAccessToken();
const res = await fetch("/api/auth/handoff", {
method: "POST",
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
});
if (!res.ok) throw new Error("handoff failed");
const data = (await res.json()) as { ticket?: string };
const url = new URL(baseUrl);
if (data.ticket) url.searchParams.set("handoff", data.ticket);
if (popup) {
popup.opener = null;
popup.location.replace(url.toString());
} else {
window.open(url.toString(), "_blank", "noopener,noreferrer");
}
} catch {
if (popup) popup.location.replace(baseUrl);
else window.open(baseUrl, "_blank", "noopener,noreferrer");
} finally {
setHandoffBusy(false);
setOpen(false);
}
}
return (
<div ref={menuRef} className="relative">
<button
type="button"
onClick={() => setOpen((value) => !value)}
aria-expanded={open}
aria-haspopup="menu"
className={`flex max-w-[12rem] items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-zinc-100 ${
compact ? "w-full justify-between px-0 hover:bg-transparent" : ""
}`}
>
<span className="flex min-w-0 items-center gap-2">
<IconUser />
<span className="truncate font-medium">
{displayName} عزیز
</span>
</span>
<IconChevron className={`w-3.5 h-3.5 shrink-0 transition-transform ${open ? "rotate-90" : "-rotate-90"}`} />
</button>
{open && (
<div
role="menu"
className={`absolute z-50 mt-2 min-w-[11rem] overflow-hidden rounded-2xl border border-black/5 bg-white py-1 shadow-xl ${
compact ? "start-0 end-0" : "start-0"
}`}
>
<a role="menuitem" href={customerDashboardUrl("/profile")} className={itemClass} onClick={() => setOpen(false)}>
پروفایل من
</a>
<a role="menuitem" href={customerDashboardUrl("/orders")} className={itemClass} onClick={() => setOpen(false)}>
سفارشات من
</a>
{isWebsiteAdmin && (
<a
role="menuitem"
href={businessDashboardUrl()}
className={itemClass}
onClick={openBusinessDashboard}
>
{handoffBusy ? "در حال انتقال…" : "مدیریت وبسایت"}
</a>
)}
<button
type="button"
role="menuitem"
className={`${itemClass} text-brand hover:text-[#e51f1f]`}
onClick={() => {
setOpen(false);
onLogout();
}}
>
خروج
</button>
</div>
)}
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
"use client";
import { CartProvider } from "@/lib/cart";
import { SessionProvider } from "@/lib/session";
export function AppProviders({
children,
businessId,
}: {
children: React.ReactNode;
businessId: string;
}) {
return (
<SessionProvider businessId={businessId}>
<CartProvider>{children}</CartProvider>
</SessionProvider>
);
}
+181
View File
@@ -0,0 +1,181 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { customerContinueCheckoutUrl } from "@/lib/customer";
import { useCart } from "@/lib/cart";
import { formatPrice } from "@/lib/format";
import { PLACEHOLDER } from "@/lib/data";
import { useSession } from "@/lib/session";
import { IconClose } from "./Icons";
import { Media } from "./Media";
type Props = {
open: boolean;
onClose: () => void;
};
export function CartPopup({ open, onClose }: Props) {
const { isAuthenticated } = useSession();
const { items, itemCount, total, removeItem, setQuantity } = useCart();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!open) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
};
document.addEventListener("keydown", onKeyDown);
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKeyDown);
document.body.style.overflow = "";
};
}, [open, onClose]);
if (!mounted || !open) return null;
const continueHref = customerContinueCheckoutUrl(isAuthenticated, items);
return createPortal(
<div>
<button type="button" className="fixed inset-0 z-[120] bg-black/40" aria-label="بستن" onClick={onClose} />
<div
role="dialog"
aria-modal="true"
aria-label="سبد خرید"
className="fixed inset-y-0 left-0 z-[130] flex h-dvh w-full max-w-md flex-col bg-white shadow-2xl"
>
<div className="flex items-center justify-between border-b border-black/5 px-5 py-4">
<div>
<h2 className="text-base font-extrabold">سبد خرید</h2>
{itemCount > 0 && (
<p className="mt-0.5 text-xs text-zinc-400">
{itemCount.toLocaleString("fa-IR")} کالا
</p>
)}
</div>
<button
type="button"
onClick={onClose}
aria-label="بستن"
className="grid size-9 place-items-center rounded-full hover:bg-zinc-100"
>
<IconClose className="w-4 h-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto px-5 py-4">
{items.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center text-center">
<p className="text-sm text-zinc-500">سبد خرید شما خالی است</p>
</div>
) : (
<ul className="space-y-4">
{items.map((item) => (
<li key={item.id} className="flex gap-3 border-b border-black/5 pb-4 last:border-0">
<Link
href={item.slug ? `/products/${item.slug}` : "/products"}
onClick={onClose}
className="size-20 shrink-0 overflow-hidden rounded-xl border border-black/5"
>
<Media src={item.image || PLACEHOLDER.product} alt="" className="size-full" sizes="80px" />
</Link>
<div className="min-w-0 flex-1">
<Link
href={item.slug ? `/products/${item.slug}` : "/products"}
onClick={onClose}
className="line-clamp-2 text-sm font-medium leading-6 hover:text-brand"
>
{item.name}
</Link>
<div className="mt-2 flex items-center justify-between gap-2">
<div className="flex items-center overflow-hidden rounded-lg border border-black/10">
<button
type="button"
aria-label="افزایش"
onClick={() => setQuantity(item.id, item.quantity + 1)}
className="grid size-8 place-items-center text-sm hover:bg-zinc-50"
>
+
</button>
<span className="min-w-7 text-center text-xs font-bold">
{item.quantity.toLocaleString("fa-IR")}
</span>
<button
type="button"
aria-label="کاهش"
onClick={() => setQuantity(item.id, item.quantity - 1)}
className="grid size-8 place-items-center text-sm hover:bg-zinc-50"
>
−
</button>
</div>
<div className="flex items-center gap-2">
<span className="text-sm font-bold">
{formatPrice(item.price * item.quantity)}
<span className="mr-0.5 text-[11px] font-normal text-zinc-400">تومان</span>
</span>
<button
type="button"
onClick={() => removeItem(item.id)}
aria-label="حذف"
className="grid size-8 place-items-center rounded-lg text-zinc-400 hover:bg-brand-soft hover:text-brand"
>
<svg viewBox="0 0 24 24" fill="none" className="h-4 w-4" aria-hidden>
<path
d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7M10 11v5M14 11v5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
</div>
</div>
</div>
</li>
))}
</ul>
)}
</div>
<div className="border-t border-black/5 px-5 py-4">
{items.length > 0 && (
<div className="mb-3 flex items-center justify-between text-sm">
<span className="text-zinc-500">جمع کل</span>
<span className="font-extrabold">
{formatPrice(total)}
<span className="mr-0.5 text-xs font-normal text-zinc-400">تومان</span>
</span>
</div>
)}
{items.length > 0 ? (
<a
href={continueHref}
onClick={onClose}
className="flex w-full items-center justify-center rounded-xl bg-brand py-3 text-sm text-white hover:bg-[#e51f1f]"
>
ادامه
</a>
) : (
<button
type="button"
onClick={onClose}
className="flex w-full items-center justify-center rounded-xl bg-brand-soft py-3 text-sm font-medium text-brand"
>
ادامه خرید
</button>
)}
</div>
</div>
</div>,
document.body,
);
}
+49 -28
View File
@@ -2,10 +2,14 @@
import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { cartCount } from "@/lib/cart";
import { useState } from "react";
import { customerLoginUrl } from "@/lib/customer";
import { parentCategories } from "@/lib/data";
import { SITE } from "@/lib/site";
import { useCart } from "@/lib/cart";
import { useSession } from "@/lib/session";
import { AccountMenu } from "./AccountMenu";
import { CartPopup } from "./CartPopup";
import { IconCart, IconChevron, IconClose, IconMenu, IconUser } from "./Icons";
import { SearchBox } from "./SearchBox";
@@ -19,18 +23,11 @@ const nav = [
export function Header() {
const [open, setOpen] = useState(false);
const [mega, setMega] = useState(false);
const [count, setCount] = useState(0);
useEffect(() => {
const sync = () => setCount(cartCount());
sync();
window.addEventListener("cart-updated", sync);
window.addEventListener("storage", sync);
return () => {
window.removeEventListener("cart-updated", sync);
window.removeEventListener("storage", sync);
};
}, []);
const [cartOpen, setCartOpen] = useState(false);
const { itemCount } = useCart();
const { isAuthenticated, user, logout, isWebsiteAdmin } = useSession();
const displayName = user?.firstName?.trim() || "حساب من";
const loginHref = customerLoginUrl("/");
return (
<header className="sticky top-0 z-50 bg-white border-b border-black/5">
@@ -95,19 +92,29 @@ export function Header() {
<SearchBox className="hidden md:block ms-4 max-w-sm flex-1 rounded-full bg-zinc-100 px-3" />
<div className="flex items-center gap-2 ms-auto">
<a
href={SITE.customerUrl}
className="flex items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-zinc-100"
{isAuthenticated ? (
<div className="hidden sm:block">
<AccountMenu displayName={displayName} isWebsiteAdmin={isWebsiteAdmin} onLogout={logout} />
</div>
) : (
<a href={loginHref} className="flex items-center gap-2 rounded-full px-3 py-2 text-sm hover:bg-zinc-100">
<IconUser />
<span className="hidden sm:inline">ورود / ثبت نام</span>
</a>
)}
<button
type="button"
onClick={() => setCartOpen(true)}
aria-label={itemCount > 0 ? `سبد خرید، ${itemCount.toLocaleString("fa-IR")} کالا` : "سبد خرید"}
className="relative grid place-items-center w-10 h-10 rounded-full hover:bg-zinc-100"
>
<IconUser />
<span className="hidden sm:inline">ورود / ثبت نام</span>
</a>
<Link href="/cart" className="relative grid place-items-center w-10 h-10 rounded-full hover:bg-zinc-100">
<IconCart className="w-6 h-6 text-brand" />
<span className="absolute top-1 left-1 grid place-items-center w-4 h-4 rounded-full bg-brand text-[10px] text-white">
{count.toLocaleString("fa-IR")}
</span>
</Link>
{itemCount > 0 && (
<span className="absolute top-1 left-1 grid place-items-center min-w-4 h-4 rounded-full bg-brand px-0.5 text-[10px] text-white">
{itemCount.toLocaleString("fa-IR")}
</span>
)}
</button>
</div>
</div>
@@ -147,13 +154,27 @@ export function Header() {
{item.name}
</Link>
))}
<a href={SITE.customerUrl} className="py-2">
ورود / ثبت نام
</a>
{isAuthenticated ? (
<AccountMenu
displayName={displayName}
isWebsiteAdmin={isWebsiteAdmin}
compact
onLogout={() => {
logout();
setOpen(false);
}}
/>
) : (
<a href={loginHref} className="py-2">
ورود / ثبت نام
</a>
)}
</div>
</aside>
</div>
)}
<CartPopup open={cartOpen} onClose={() => setCartOpen(false)} />
</header>
);
}
+6 -18
View File
@@ -1,9 +1,10 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useState, type FormEvent } from "react";
import type { ApiComment } from "@/lib/api";
import { formatDate } from "@/lib/format";
import { SITE } from "@/lib/site";
import { customerLoginUrl } from "@/lib/customer";
import { useSession } from "@/lib/session";
import { RichContent } from "./RichContent";
type Props = {
@@ -23,26 +24,13 @@ const tabs: Tab[] = [
{ id: "comments", fa: "نظرات", en: "Comments" },
];
function readToken() {
if (typeof window === "undefined") return "";
return (
window.localStorage.getItem("accessToken") ||
window.localStorage.getItem("meshkee_access_token") ||
""
);
}
export function ProductTabs({ productId, descriptionHtml, comments: initialComments }: Props) {
const [tab, setTab] = useState<"description" | "comments">("description");
const [comments, setComments] = useState(initialComments);
const [sent, setSent] = useState(false);
const [sending, setSending] = useState(false);
const [loggedIn, setLoggedIn] = useState(false);
const authorName = "کاربر";
useEffect(() => {
setLoggedIn(Boolean(readToken()));
}, []);
const { isAuthenticated: loggedIn, user } = useSession();
const authorName = user?.firstName?.trim() || "کاربر";
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
@@ -157,7 +145,7 @@ export function ProductTabs({ productId, descriptionHtml, comments: initialComme
<div className="rounded-xl bg-zinc-50 px-4 py-5 text-center">
<p className="text-sm text-zinc-600">برای ثبت نظر ابتدا وارد حساب کاربری شوید.</p>
<a
href={SITE.customerUrl}
href={customerLoginUrl("/")}
className="mt-3 inline-block text-sm text-brand"
>
ورود / ثبت نام
+5 -4
View File
@@ -131,19 +131,20 @@ export function ProductView({ product, variants }: Props) {
</div>
<button
type="button"
disabled={!variant?.id}
onClick={() => {
if (!variant?.id) return;
addToCart({
productId: product.id,
variantId: variant?.id,
id: variant.id,
slug: product.slug,
name: product.nameFa || product.title,
image: images[0] || PLACEHOLDER.product,
price,
qty,
quantity: qty,
});
setAdded(true);
}}
className="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-brand px-5 py-2.5 text-sm text-white hover:bg-[#e51f1f]"
className="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-brand px-5 py-2.5 text-sm text-white hover:bg-[#e51f1f] disabled:opacity-60"
>
<IconCart className="w-5 h-5 text-white" />
{added ? "به سبد اضافه شد" : "افزودن به سبد خرید"}