@hszrdm/create-commerce 1.0.3 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/bin/create-commerce.mjs +9 -2
  2. package/package.json +1 -1
  3. package/src/cli.mjs +5 -2
  4. package/templates/backend/.env.example +66 -7
  5. package/templates/backend/medusa-config.ts +17 -1
  6. package/templates/backend/package.json +2 -1
  7. package/templates/backend/src/scripts/core-init.ts +13 -1
  8. package/templates/storefront/next-env.d.ts +4 -1
  9. package/templates/storefront/src/app/[countryCode]/categories/[handle]/page.tsx +9 -3
  10. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +46 -10
  11. package/templates/storefront/src/app/[countryCode]/products/page.tsx +17 -10
  12. package/templates/storefront/src/app/account/page.tsx +12 -1
  13. package/templates/storefront/src/app/account/wishlist/page.tsx +9 -0
  14. package/templates/storefront/src/app/checkout/page.tsx +12 -3
  15. package/templates/storefront/src/app/checkout/success/page.tsx +58 -18
  16. package/templates/storefront/src/app/core-ux.css +244 -0
  17. package/templates/storefront/src/app/layout.tsx +40 -14
  18. package/templates/storefront/src/app/legal/page.tsx +11 -5
  19. package/templates/storefront/src/app/newsletter/confirm/page.tsx +19 -0
  20. package/templates/storefront/src/app/newsletter/unsubscribe/page.tsx +19 -0
  21. package/templates/storefront/src/app/page.tsx +18 -12
  22. package/templates/storefront/src/app/reset-password/page.tsx +8 -2
  23. package/templates/storefront/src/components/accessibility-preferences.tsx +126 -0
  24. package/templates/storefront/src/components/accessible-dialog.tsx +88 -0
  25. package/templates/storefront/src/components/accessible-dropdown.tsx +98 -0
  26. package/templates/storefront/src/components/account-dashboard.tsx +197 -76
  27. package/templates/storefront/src/components/account-wishlist.tsx +95 -0
  28. package/templates/storefront/src/components/add-to-cart.tsx +127 -18
  29. package/templates/storefront/src/components/back-to-top.tsx +26 -0
  30. package/templates/storefront/src/components/breadcrumbs.tsx +26 -0
  31. package/templates/storefront/src/components/cart-provider.tsx +29 -12
  32. package/templates/storefront/src/components/cart-view.tsx +96 -32
  33. package/templates/storefront/src/components/checkout-analytics.tsx +23 -0
  34. package/templates/storefront/src/components/checkout-flow.tsx +354 -102
  35. package/templates/storefront/src/components/form-ux.tsx +47 -0
  36. package/templates/storefront/src/components/free-shipping-progress.tsx +35 -0
  37. package/templates/storefront/src/components/newsletter-action.tsx +66 -0
  38. package/templates/storefront/src/components/order-detail.tsx +84 -45
  39. package/templates/storefront/src/components/product-card.tsx +16 -8
  40. package/templates/storefront/src/components/product-gallery.tsx +64 -0
  41. package/templates/storefront/src/components/quantity-stepper.tsx +41 -0
  42. package/templates/storefront/src/components/reset-password-form.tsx +19 -13
  43. package/templates/storefront/src/components/share-button.tsx +63 -0
  44. package/templates/storefront/src/components/storefront-header.tsx +88 -20
  45. package/templates/storefront/src/components/stripe-payment.tsx +20 -4
  46. package/templates/storefront/src/components/tier-progress-hint.tsx +32 -0
  47. package/templates/storefront/src/components/toast-provider.tsx +92 -0
  48. package/templates/storefront/src/components/variant-price-display.tsx +31 -0
  49. package/templates/storefront/src/components/wishlist-button.tsx +88 -0
  50. package/templates/storefront/src/lib/core/account.ts +3 -0
  51. package/templates/storefront/src/lib/core/catalog.ts +37 -5
  52. package/templates/storefront/src/lib/core/client.ts +5 -0
  53. package/templates/storefront/src/lib/core/cms-contract.ts +35 -0
  54. package/templates/storefront/src/lib/core/cms.ts +171 -0
  55. package/templates/storefront/src/lib/core/commerce.ts +14 -4
  56. package/templates/storefront/src/lib/core/form-ux.ts +57 -0
  57. package/templates/storefront/src/lib/core/leads.ts +50 -0
  58. package/templates/storefront/src/lib/core/newsletter.ts +53 -0
  59. package/templates/storefront/src/lib/core/pricing.ts +68 -0
  60. package/templates/storefront/src/lib/core/quotes.ts +43 -0
  61. package/templates/storefront/src/lib/core/reviews.ts +40 -0
  62. package/templates/storefront/src/lib/core/seo.ts +44 -6
  63. package/templates/storefront/src/lib/core/share.ts +57 -0
  64. package/templates/storefront/src/lib/core/wishlist.ts +88 -0
  65. package/templates/storefront/src/lib/storefront-copy.ts +435 -0
  66. package/templates/storefront/src/lib/storefront-locale-server.ts +11 -0
  67. package/templates/storefront/src/lib/storefront-routes.ts +94 -0
  68. package/templates/storefront/src/proxy.ts +145 -0
  69. package/templates/storefront/tsconfig.json +23 -5
@@ -1,13 +1,19 @@
1
1
  "use client"
2
2
 
3
3
  import Link from "next/link"
4
- import { useSearchParams } from "next/navigation"
4
+ import { usePathname, useSearchParams } from "next/navigation"
5
5
  import { useMemo, useState } from "react"
6
6
  import { accountApi } from "@/lib/core/account"
7
7
  import type { CoreConfig } from "@/lib/core/types"
8
+ import { storefrontCopy } from "@/lib/storefront-copy"
9
+ import { localeFromPathname, STOREFRONT_ROUTES } from "@/lib/storefront-routes"
8
10
 
9
11
  export function ResetPasswordForm({ config }: { config: CoreConfig }) {
10
12
  const api = useMemo(() => accountApi(config), [config])
13
+ const pathname = usePathname()
14
+ const locale = localeFromPathname(pathname)
15
+ const copy = storefrontCopy(locale)
16
+ const routes = STOREFRONT_ROUTES[locale]
11
17
  const search = useSearchParams()
12
18
  const token = search.get("token") || ""
13
19
  const initialEmail = search.get("email") || ""
@@ -22,29 +28,29 @@ export function ResetPasswordForm({ config }: { config: CoreConfig }) {
22
28
  setError(null)
23
29
  setMessage(null)
24
30
  if (!token) {
25
- setError("Hiányzik a jelszó-visszaállítási token. Kérj új visszaállító e-mailt.")
31
+ setError(locale === "en" ? "The password reset token is missing. Request a new reset email." : "Hiányzik a jelszó-visszaállítási token. Kérj új visszaállító e-mailt.")
26
32
  return
27
33
  }
28
34
  if (!email.trim()) {
29
- setError("Add meg az e-mail címedet.")
35
+ setError(locale === "en" ? "Enter your email address." : "Add meg az e-mail címedet.")
30
36
  return
31
37
  }
32
38
  if (password.length < 8) {
33
- setError("Az új jelszó legalább 8 karakter legyen.")
39
+ setError(locale === "en" ? "The new password must be at least 8 characters long." : "Az új jelszó legalább 8 karakter legyen.")
34
40
  return
35
41
  }
36
42
  if (password !== confirm) {
37
- setError("A két jelszó nem egyezik.")
43
+ setError(locale === "en" ? "The passwords do not match." : "A két jelszó nem egyezik.")
38
44
  return
39
45
  }
40
46
  setBusy(true)
41
47
  try {
42
48
  await api.completePasswordReset(token, email, password)
43
- setMessage("A jelszó sikeresen módosult. Most már bejelentkezhetsz.")
49
+ setMessage(locale === "en" ? "Your password has been changed. You can now sign in." : "A jelszó sikeresen módosult. Most már bejelentkezhetsz.")
44
50
  setPassword("")
45
51
  setConfirm("")
46
52
  } catch (cause) {
47
- setError(cause instanceof Error ? cause.message : "A jelszó-visszaállítás nem sikerült.")
53
+ setError(cause instanceof Error ? cause.message : locale === "en" ? "Password reset failed." : "A jelszó-visszaállítás nem sikerült.")
48
54
  } finally {
49
55
  setBusy(false)
50
56
  }
@@ -52,14 +58,14 @@ export function ResetPasswordForm({ config }: { config: CoreConfig }) {
52
58
 
53
59
  return (
54
60
  <section className="panel stack narrow-card">
55
- <div><p className="eyebrow">Fiók biztonság</p><h1>Új jelszó beállítása</h1></div>
56
- <label>E-mail<input type="email" value={email} onChange={(event) => setEmail(event.target.value)} /></label>
57
- <label>Új jelszó<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} /></label>
58
- <label>Új jelszó újra<input type="password" value={confirm} onChange={(event) => setConfirm(event.target.value)} /></label>
61
+ <div><p className="eyebrow">{copy.resetSecurity}</p><h1>{copy.resetTitle}</h1></div>
62
+ <label>{copy.email}<input type="email" value={email} onChange={(event) => setEmail(event.target.value)} /></label>
63
+ <label>{copy.newPassword}<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} /></label>
64
+ <label>{copy.repeatPassword}<input type="password" value={confirm} onChange={(event) => setConfirm(event.target.value)} /></label>
59
65
  {error ? <p className="error">{error}</p> : null}
60
66
  {message ? <p className="success">{message}</p> : null}
61
- <button className="button button-large" type="button" disabled={busy} onClick={() => void submit()}>{busy ? "Mentés…" : "Jelszó mentése"}</button>
62
- <Link className="text-link" href="/account">Vissza a belépéshez</Link>
67
+ <button className="button button-large" type="button" disabled={busy} onClick={() => void submit()}>{busy ? copy.saving : copy.savePassword}</button>
68
+ <Link className="text-link" href={routes.account}>{copy.backToLogin}</Link>
63
69
  </section>
64
70
  )
65
71
  }
@@ -0,0 +1,63 @@
1
+ "use client"
2
+
3
+ import { usePathname } from "next/navigation"
4
+ import { useMemo, useState } from "react"
5
+ import { copyText, shareContent, shareFallbackLinks } from "@/lib/core/share"
6
+ import { localeFromPathname } from "@/lib/storefront-routes"
7
+ import { useToast } from "./toast-provider"
8
+
9
+ export function ShareButton({
10
+ title,
11
+ text,
12
+ url,
13
+ showFallbackLinks = false,
14
+ }: {
15
+ title?: string
16
+ text?: string
17
+ url?: string
18
+ showFallbackLinks?: boolean
19
+ }) {
20
+ const pathname = usePathname()
21
+ const locale = localeFromPathname(pathname)
22
+ const en = locale === "en"
23
+ const { showToast } = useToast()
24
+ const [expanded, setExpanded] = useState(false)
25
+ const resolvedUrl = useMemo(() => {
26
+ if (url) return url
27
+ if (typeof window === "undefined") return pathname
28
+ return window.location.href
29
+ }, [pathname, url])
30
+ const links = shareFallbackLinks({ title, text, url: resolvedUrl })
31
+
32
+ const share = async () => {
33
+ try {
34
+ const result = await shareContent({ title, text, url: resolvedUrl })
35
+ if (result === "copied") showToast({ message: en ? "Link copied" : "Link másolva", tone: "success" })
36
+ } catch {
37
+ setExpanded(true)
38
+ showToast({ message: en ? "Sharing is not available. You can copy the link instead." : "A megosztás nem érhető el. A linket külön kimásolhatod.", tone: "error" })
39
+ }
40
+ }
41
+
42
+ return (
43
+ <div className="share-control">
44
+ <button type="button" className="button secondary" onClick={() => void share()}>
45
+ {en ? "Share" : "Megosztás"}
46
+ </button>
47
+ <button
48
+ type="button"
49
+ className="text-button"
50
+ onClick={() => void copyText(resolvedUrl).then(() => showToast({ message: en ? "Link copied" : "Link másolva", tone: "success" }))}
51
+ >
52
+ {en ? "Copy link" : "Link másolása"}
53
+ </button>
54
+ {showFallbackLinks || expanded ? (
55
+ <div className="share-links" aria-label={en ? "Share options" : "Megosztási lehetőségek"}>
56
+ <a href={links.facebook} target="_blank" rel="noreferrer">Facebook</a>
57
+ <a href={links.linkedin} target="_blank" rel="noreferrer">LinkedIn</a>
58
+ <a href={links.email}>{en ? "Email" : "E-mail"}</a>
59
+ </div>
60
+ ) : null}
61
+ </div>
62
+ )
63
+ }
@@ -1,42 +1,110 @@
1
1
  "use client"
2
2
 
3
3
  import Link from "next/link"
4
+ import { usePathname } from "next/navigation"
5
+ import { useCallback, useEffect, useState } from "react"
6
+ import { AccessibleDialog } from "./accessible-dialog"
4
7
  import { useCart } from "./cart-provider"
5
8
  import { CartView } from "./cart-view"
6
9
  import type { CoreConfig } from "@/lib/core/types"
10
+ import { storefrontCopy } from "@/lib/storefront-copy"
11
+ import {
12
+ equivalentLocalePath,
13
+ localeFromPathname,
14
+ STOREFRONT_ROUTES,
15
+ } from "@/lib/storefront-routes"
7
16
 
8
17
  export function StorefrontHeader({ config }: { config: CoreConfig }) {
9
18
  const { count, drawerOpen, setDrawerOpen } = useCart()
10
- const country = config.seo.default_country_code
19
+ const [menuOpen, setMenuOpen] = useState(false)
20
+ const pathname = usePathname()
21
+ const locale = localeFromPathname(pathname)
22
+ const routes = STOREFRONT_ROUTES[locale]
23
+ const copy = storefrontCopy(locale)
24
+ const closeDrawer = useCallback(() => setDrawerOpen(false), [setDrawerOpen])
25
+ const closeMenu = useCallback(() => setMenuOpen(false), [])
26
+
27
+ useEffect(() => {
28
+ closeDrawer()
29
+ closeMenu()
30
+ }, [closeDrawer, closeMenu, pathname])
31
+
32
+ const primaryLinks = [
33
+ { href: routes.products, label: copy.products },
34
+ { href: routes.legal, label: copy.legalDocuments },
35
+ ...(config.features.account ? [{ href: routes.account, label: copy.account }] : []),
36
+ ]
11
37
 
12
38
  return (
13
39
  <>
14
40
  <header className="shell header">
15
- <Link className="brand" href="/">{config.store.name}</Link>
16
- <nav className="nav" aria-label="Fő navigáció">
17
- <Link href={`/${country}/products`}>Termékek</Link>
18
- <Link href="/legal">Jogi dokumentumok</Link>
19
- {config.features.account ? <Link href="/account">Fiókom</Link> : null}
20
- <button className="nav-cart" type="button" onClick={() => setDrawerOpen(true)}>
21
- Kosár <span className="cart-count">{count}</span>
41
+ <Link className="brand" href={routes.home} aria-current={pathname === routes.home ? "page" : undefined}>{config.store.name}</Link>
42
+ <nav className="nav" aria-label={locale === "en" ? "Main navigation" : "Fő navigáció"}>
43
+ {primaryLinks.map((item) => (
44
+ <Link key={item.href} href={item.href} aria-current={isActive(pathname, item.href) ? "page" : undefined}>{item.label}</Link>
45
+ ))}
46
+ <span className="locale-switch" aria-label={locale === "en" ? "Language" : "Nyelv"}>
47
+ <Link aria-current={locale === "hu" ? "page" : undefined} href={equivalentLocalePath(pathname, "hu")}>HU</Link>
48
+ <Link aria-current={locale === "en" ? "page" : undefined} href={equivalentLocalePath(pathname, "en")}>EN</Link>
49
+ </span>
50
+ <button
51
+ className="mobile-menu-trigger icon-button"
52
+ type="button"
53
+ aria-label={locale === "en" ? "Open menu" : "Menü megnyitása"}
54
+ aria-haspopup="dialog"
55
+ aria-expanded={menuOpen}
56
+ aria-controls="mobile-navigation"
57
+ onClick={() => setMenuOpen(true)}
58
+ >
59
+ ☰
60
+ </button>
61
+ <button
62
+ className="nav-cart"
63
+ type="button"
64
+ aria-haspopup="dialog"
65
+ aria-expanded={drawerOpen}
66
+ aria-controls="cart-drawer"
67
+ onClick={() => setDrawerOpen(true)}
68
+ >
69
+ {copy.cart} <span className="cart-count" aria-label={`${count} ${copy.productCountSuffix}`}>{count}</span>
22
70
  </button>
23
71
  </nav>
24
72
  </header>
25
73
 
26
- {drawerOpen ? (
27
- <div className="drawer-backdrop" onMouseDown={() => setDrawerOpen(false)}>
28
- <aside className="drawer" onMouseDown={(event) => event.stopPropagation()} aria-label="Kosár">
29
- <div className="drawer-head">
30
- <div>
31
- <p className="eyebrow">Kosár</p>
32
- <h2>{count} termék</h2>
33
- </div>
34
- <button className="icon-button" type="button" aria-label="Bezárás" onClick={() => setDrawerOpen(false)}>×</button>
74
+ <AccessibleDialog open={menuOpen} onClose={closeMenu} labelledBy="mobile-menu-title" className="mobile-menu-drawer">
75
+ <div id="mobile-navigation" className="stack">
76
+ <div className="drawer-head">
77
+ <h2 id="mobile-menu-title">{locale === "en" ? "Menu" : "Menü"}</h2>
78
+ <button className="icon-button" type="button" aria-label={copy.close} onClick={closeMenu}>×</button>
79
+ </div>
80
+ <nav className="mobile-nav-links" aria-label={locale === "en" ? "Mobile navigation" : "Mobil navigáció"}>
81
+ {primaryLinks.map((item) => (
82
+ <Link key={item.href} href={item.href} aria-current={isActive(pathname, item.href) ? "page" : undefined}>{item.label}</Link>
83
+ ))}
84
+ </nav>
85
+ <div className="mobile-locale-switch" aria-label={locale === "en" ? "Language" : "Nyelv"}>
86
+ <Link aria-current={locale === "hu" ? "page" : undefined} href={equivalentLocalePath(pathname, "hu")}>Magyar</Link>
87
+ <Link aria-current={locale === "en" ? "page" : undefined} href={equivalentLocalePath(pathname, "en")}>English</Link>
88
+ </div>
89
+ </div>
90
+ </AccessibleDialog>
91
+
92
+ <AccessibleDialog open={drawerOpen} onClose={closeDrawer} labelledBy="cart-drawer-title">
93
+ <div id="cart-drawer">
94
+ <div className="drawer-head">
95
+ <div>
96
+ <p className="eyebrow">{copy.cart}</p>
97
+ <h2 id="cart-drawer-title">{count} {copy.productCountSuffix}</h2>
35
98
  </div>
36
- <CartView config={config} compact />
37
- </aside>
99
+ <button className="icon-button" type="button" aria-label={copy.close} onClick={closeDrawer}>×</button>
100
+ </div>
101
+ <CartView config={config} compact />
38
102
  </div>
39
- ) : null}
103
+ </AccessibleDialog>
40
104
  </>
41
105
  )
42
106
  }
107
+
108
+ function isActive(pathname: string, href: string) {
109
+ return pathname === href || pathname.startsWith(`${href}/`)
110
+ }
@@ -1,8 +1,10 @@
1
1
  "use client"
2
2
 
3
3
  import { useMemo, useState } from "react"
4
+ import { usePathname } from "next/navigation"
4
5
  import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js"
5
6
  import { loadStripe } from "@stripe/stripe-js/pure"
7
+ import { localeFromPathname, STOREFRONT_ROUTES } from "@/lib/storefront-routes"
6
8
 
7
9
  export function StripePayment({
8
10
  publishableKey,
@@ -45,6 +47,9 @@ function StripePaymentForm({
45
47
  }) {
46
48
  const stripe = useStripe()
47
49
  const elements = useElements()
50
+ const pathname = usePathname()
51
+ const locale = localeFromPathname(pathname)
52
+ const checkoutPath = STOREFRONT_ROUTES[locale].checkout
48
53
  const [busy, setBusy] = useState(false)
49
54
  const [error, setError] = useState<string | null>(null)
50
55
 
@@ -54,7 +59,7 @@ function StripePaymentForm({
54
59
  setError(null)
55
60
  try {
56
61
  if (beforeConfirm) await beforeConfirm()
57
- const returnUrl = new URL("/checkout", window.location.origin)
62
+ const returnUrl = new URL(checkoutPath, window.location.origin)
58
63
  returnUrl.searchParams.set("cart_id", cartId)
59
64
  returnUrl.searchParams.set("stripe_return", "1")
60
65
  const result = await stripe.confirmPayment({
@@ -63,11 +68,20 @@ function StripePaymentForm({
63
68
  confirmParams: { return_url: returnUrl.toString() },
64
69
  })
65
70
  if (result.error) {
66
- throw new Error(result.error.message || "A bankkártyás fizetés nem sikerült.")
71
+ throw new Error(
72
+ result.error.message ||
73
+ (locale === "en" ? "Card payment failed." : "A bankkártyás fizetés nem sikerült."),
74
+ )
67
75
  }
68
76
  await onConfirmed()
69
77
  } catch (cause) {
70
- setError(cause instanceof Error ? cause.message : "A bankkártyás fizetés nem sikerült.")
78
+ setError(
79
+ cause instanceof Error
80
+ ? cause.message
81
+ : locale === "en"
82
+ ? "Card payment failed."
83
+ : "A bankkártyás fizetés nem sikerült.",
84
+ )
71
85
  } finally {
72
86
  setBusy(false)
73
87
  }
@@ -83,7 +97,9 @@ function StripePaymentForm({
83
97
  disabled={!stripe || !elements || disabled || busy}
84
98
  onClick={() => void submit()}
85
99
  >
86
- {busy ? "Fizetés feldolgozása…" : "Fizetés bankkártyával"}
100
+ {busy
101
+ ? locale === "en" ? "Processing payment…" : "Fizetés feldolgozása…"
102
+ : locale === "en" ? "Pay by card" : "Fizetés bankkártyával"}
87
103
  </button>
88
104
  </div>
89
105
  )
@@ -0,0 +1,32 @@
1
+ export type QuantityPriceTier = {
2
+ minQuantity: number
3
+ unitPrice?: number
4
+ }
5
+
6
+ export function unitsUntilNextPriceTier(quantity: number, tiers: QuantityPriceTier[]) {
7
+ const sorted = [...tiers]
8
+ .filter((tier) => Number.isFinite(tier.minQuantity) && tier.minQuantity > 0)
9
+ .sort((a, b) => a.minQuantity - b.minQuantity)
10
+ const next = sorted.find((tier) => tier.minQuantity > quantity)
11
+ return next ? { remaining: next.minQuantity - quantity, tier: next } : null
12
+ }
13
+
14
+ export function TierProgressHint({
15
+ quantity,
16
+ tiers,
17
+ locale = "hu",
18
+ }: {
19
+ quantity: number
20
+ tiers: QuantityPriceTier[]
21
+ locale?: "hu" | "en"
22
+ }) {
23
+ const next = unitsUntilNextPriceTier(quantity, tiers)
24
+ if (!next) return null
25
+ return (
26
+ <p className="tier-progress-hint" role="status" aria-live="polite">
27
+ {locale === "en"
28
+ ? `${next.remaining} more to reach the next price tier.`
29
+ : `Még ${next.remaining} db a következő árszintig.`}
30
+ </p>
31
+ )
32
+ }
@@ -0,0 +1,92 @@
1
+ "use client"
2
+
3
+ import {
4
+ createContext,
5
+ useCallback,
6
+ useContext,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ type ReactNode,
11
+ } from "react"
12
+
13
+ type ToastTone = "success" | "error" | "info"
14
+
15
+ type ToastInput = {
16
+ message: string
17
+ tone?: ToastTone
18
+ actionLabel?: string
19
+ onAction?: () => void | Promise<void>
20
+ durationMs?: number
21
+ }
22
+
23
+ type ToastItem = ToastInput & { id: number }
24
+
25
+ type ToastContextValue = {
26
+ showToast: (input: ToastInput | string) => number
27
+ dismissToast: (id: number) => void
28
+ }
29
+
30
+ const ToastContext = createContext<ToastContextValue | null>(null)
31
+
32
+ export function ToastProvider({ children, locale = "hu" }: { children: ReactNode; locale?: "hu" | "en" }) {
33
+ const [items, setItems] = useState<ToastItem[]>([])
34
+ const sequence = useRef(0)
35
+ const timers = useRef(new Map<number, ReturnType<typeof setTimeout>>())
36
+ const closeLabel = locale === "en" ? "Close notification" : "Értesítés bezárása"
37
+
38
+ const dismissToast = useCallback((id: number) => {
39
+ const timer = timers.current.get(id)
40
+ if (timer) clearTimeout(timer)
41
+ timers.current.delete(id)
42
+ setItems((current) => current.filter((item) => item.id !== id))
43
+ }, [])
44
+
45
+ const showToast = useCallback((input: ToastInput | string) => {
46
+ const normalized: ToastInput = typeof input === "string" ? { message: input } : input
47
+ const id = ++sequence.current
48
+ const item: ToastItem = {
49
+ id,
50
+ tone: normalized.tone || "info",
51
+ durationMs: normalized.durationMs ?? (normalized.actionLabel ? 7000 : 4200),
52
+ ...normalized,
53
+ }
54
+ setItems((current) => [...current.slice(-3), item])
55
+ const timer = setTimeout(() => dismissToast(id), item.durationMs)
56
+ timers.current.set(id, timer)
57
+ return id
58
+ }, [dismissToast])
59
+
60
+ const value = useMemo(() => ({ showToast, dismissToast }), [dismissToast, showToast])
61
+
62
+ return (
63
+ <ToastContext.Provider value={value}>
64
+ {children}
65
+ <div className="toast-region" aria-live="polite" aria-atomic="false">
66
+ {items.map((item) => (
67
+ <div className={`toast toast-${item.tone}`} role={item.tone === "error" ? "alert" : "status"} key={item.id}>
68
+ <span>{item.message}</span>
69
+ {item.actionLabel && item.onAction ? (
70
+ <button
71
+ type="button"
72
+ className="toast-action"
73
+ onClick={() => {
74
+ void Promise.resolve(item.onAction?.()).finally(() => dismissToast(item.id))
75
+ }}
76
+ >
77
+ {item.actionLabel}
78
+ </button>
79
+ ) : null}
80
+ <button type="button" className="toast-close" aria-label={closeLabel} onClick={() => dismissToast(item.id)}>×</button>
81
+ </div>
82
+ ))}
83
+ </div>
84
+ </ToastContext.Provider>
85
+ )
86
+ }
87
+
88
+ export function useToast() {
89
+ const context = useContext(ToastContext)
90
+ if (!context) throw new Error("useToast csak ToastProvider alatt használható.")
91
+ return context
92
+ }
@@ -0,0 +1,31 @@
1
+ "use client"
2
+
3
+ import { useEffect, useState } from "react"
4
+ import { formatMoney } from "@/lib/core/commerce"
5
+
6
+ export function VariantPriceDisplay({
7
+ initialPrice,
8
+ initialCurrency,
9
+ locale,
10
+ }: {
11
+ initialPrice: number
12
+ initialCurrency: string
13
+ locale: string
14
+ }) {
15
+ const [price, setPrice] = useState(initialPrice)
16
+ const [currency, setCurrency] = useState(initialCurrency)
17
+
18
+ useEffect(() => {
19
+ const listener = (event: Event) => {
20
+ const detail = (event as CustomEvent<{ price?: number; currency?: string }>).detail
21
+ const nextPrice = Number(detail?.price)
22
+ if (Number.isFinite(nextPrice)) setPrice(nextPrice)
23
+ if (detail?.currency) setCurrency(detail.currency)
24
+ }
25
+ window.addEventListener("hszrdm:product-variant-change", listener)
26
+ return () => window.removeEventListener("hszrdm:product-variant-change", listener)
27
+ }, [])
28
+
29
+ if (!Number.isFinite(price)) return null
30
+ return <div className="product-price" aria-live="polite">{formatMoney(price, currency, locale)}</div>
31
+ }
@@ -0,0 +1,88 @@
1
+ "use client"
2
+
3
+ import { useEffect, useState } from "react"
4
+ import { usePathname } from "next/navigation"
5
+ import { CoreApiError } from "@/lib/core/client"
6
+ import { humanizeStorefrontError } from "@/lib/core/form-ux"
7
+ import {
8
+ addGuestWishlistProduct,
9
+ addWishlistProduct,
10
+ getGuestWishlistProductIds,
11
+ listWishlist,
12
+ removeGuestWishlistProduct,
13
+ removeWishlistProduct,
14
+ } from "@/lib/core/wishlist"
15
+ import { localeFromPathname } from "@/lib/storefront-routes"
16
+ import { useToast } from "./toast-provider"
17
+
18
+ type WishlistMode = "loading" | "account" | "guest"
19
+
20
+ export function WishlistButton({ productId }: { productId: string }) {
21
+ const pathname = usePathname()
22
+ const locale = localeFromPathname(pathname)
23
+ const en = locale === "en"
24
+ const { showToast } = useToast()
25
+ const [mode, setMode] = useState<WishlistMode>("loading")
26
+ const [saved, setSaved] = useState(false)
27
+ const [busy, setBusy] = useState(false)
28
+
29
+ useEffect(() => {
30
+ let active = true
31
+ void listWishlist()
32
+ .then((response) => {
33
+ if (!active) return
34
+ setMode("account")
35
+ setSaved(response.items.some((item) => item.product_id === productId))
36
+ })
37
+ .catch((error) => {
38
+ if (!active) return
39
+ if (error instanceof CoreApiError && error.status !== 401) {
40
+ setMode("guest")
41
+ } else {
42
+ setMode("guest")
43
+ }
44
+ setSaved(getGuestWishlistProductIds().includes(productId))
45
+ })
46
+ return () => { active = false }
47
+ }, [productId])
48
+
49
+ const toggle = async () => {
50
+ if (busy || mode === "loading") return
51
+ setBusy(true)
52
+ try {
53
+ if (mode === "account") {
54
+ if (saved) await removeWishlistProduct(productId)
55
+ else await addWishlistProduct(productId)
56
+ } else if (saved) {
57
+ removeGuestWishlistProduct(productId)
58
+ } else {
59
+ addGuestWishlistProduct(productId)
60
+ }
61
+ setSaved((current) => !current)
62
+ showToast({
63
+ message: saved
64
+ ? (en ? "Removed from wishlist." : "Eltávolítva a kedvencekből.")
65
+ : (en ? "Added to wishlist." : "Hozzáadva a kedvencekhez."),
66
+ tone: "success",
67
+ })
68
+ } catch (error) {
69
+ showToast({ message: humanizeStorefrontError(error, locale), tone: "error" })
70
+ } finally {
71
+ setBusy(false)
72
+ }
73
+ }
74
+
75
+ return (
76
+ <button
77
+ type="button"
78
+ className={`button secondary wishlist-button${saved ? " is-saved" : ""}`}
79
+ aria-pressed={saved}
80
+ aria-busy={busy || mode === "loading"}
81
+ disabled={busy || mode === "loading"}
82
+ onClick={() => void toggle()}
83
+ >
84
+ <span aria-hidden="true">{saved ? "♥" : "♡"}</span>
85
+ {saved ? (en ? "Saved" : "Kedvenc") : (en ? "Add to wishlist" : "Kedvencekhez")}
86
+ </button>
87
+ )
88
+ }
@@ -1,5 +1,6 @@
1
1
  import { endpoint, medusaFetch } from "./client"
2
2
  import type { CoreConfig } from "./types"
3
+ import { mergeGuestWishlistAfterLogin } from "./wishlist"
3
4
 
4
5
  export function accountApi(config: CoreConfig) {
5
6
  const paths = config.account.endpoints
@@ -52,6 +53,7 @@ export function accountApi(config: CoreConfig) {
52
53
  method: "POST",
53
54
  headers: { Authorization: `Bearer ${login.token}` },
54
55
  })
56
+ await mergeGuestWishlistAfterLogin().catch(() => undefined)
55
57
  return profile()
56
58
  },
57
59
 
@@ -64,6 +66,7 @@ export function accountApi(config: CoreConfig) {
64
66
  method: "POST",
65
67
  headers: { Authorization: `Bearer ${result.token}` },
66
68
  })
69
+ await mergeGuestWishlistAfterLogin().catch(() => undefined)
67
70
  return result
68
71
  },
69
72