@hszrdm/create-commerce 1.1.0 → 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 (38) hide show
  1. package/package.json +1 -1
  2. package/src/cli.mjs +5 -2
  3. package/templates/storefront/src/app/[countryCode]/products/[handle]/page.tsx +41 -9
  4. package/templates/storefront/src/app/account/page.tsx +12 -1
  5. package/templates/storefront/src/app/account/wishlist/page.tsx +9 -0
  6. package/templates/storefront/src/app/core-ux.css +244 -0
  7. package/templates/storefront/src/app/layout.tsx +31 -12
  8. package/templates/storefront/src/app/newsletter/confirm/page.tsx +19 -0
  9. package/templates/storefront/src/app/newsletter/unsubscribe/page.tsx +19 -0
  10. package/templates/storefront/src/components/accessibility-preferences.tsx +126 -0
  11. package/templates/storefront/src/components/accessible-dialog.tsx +88 -0
  12. package/templates/storefront/src/components/accessible-dropdown.tsx +98 -0
  13. package/templates/storefront/src/components/account-wishlist.tsx +95 -0
  14. package/templates/storefront/src/components/add-to-cart.tsx +110 -15
  15. package/templates/storefront/src/components/back-to-top.tsx +26 -0
  16. package/templates/storefront/src/components/breadcrumbs.tsx +26 -0
  17. package/templates/storefront/src/components/cart-view.tsx +72 -16
  18. package/templates/storefront/src/components/form-ux.tsx +47 -0
  19. package/templates/storefront/src/components/free-shipping-progress.tsx +35 -0
  20. package/templates/storefront/src/components/newsletter-action.tsx +66 -0
  21. package/templates/storefront/src/components/product-gallery.tsx +64 -0
  22. package/templates/storefront/src/components/quantity-stepper.tsx +41 -0
  23. package/templates/storefront/src/components/share-button.tsx +63 -0
  24. package/templates/storefront/src/components/storefront-header.tsx +72 -18
  25. package/templates/storefront/src/components/tier-progress-hint.tsx +32 -0
  26. package/templates/storefront/src/components/toast-provider.tsx +92 -0
  27. package/templates/storefront/src/components/variant-price-display.tsx +31 -0
  28. package/templates/storefront/src/components/wishlist-button.tsx +88 -0
  29. package/templates/storefront/src/lib/core/account.ts +3 -0
  30. package/templates/storefront/src/lib/core/cms-contract.ts +35 -0
  31. package/templates/storefront/src/lib/core/cms.ts +66 -7
  32. package/templates/storefront/src/lib/core/form-ux.ts +57 -0
  33. package/templates/storefront/src/lib/core/newsletter.ts +53 -0
  34. package/templates/storefront/src/lib/core/reviews.ts +40 -0
  35. package/templates/storefront/src/lib/core/share.ts +57 -0
  36. package/templates/storefront/src/lib/core/wishlist.ts +88 -0
  37. package/templates/storefront/src/lib/storefront-routes.ts +3 -0
  38. package/templates/storefront/src/proxy.ts +3 -0
@@ -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
 
@@ -0,0 +1,35 @@
1
+ export const CORE_CMS_CONTENT_TYPES = {
2
+ BLOG_POST: "blog_post",
3
+ PAGE: "page",
4
+ KNOWLEDGE_BASE: "knowledge_base",
5
+ } as const
6
+
7
+ export type CoreCmsContentType =
8
+ typeof CORE_CMS_CONTENT_TYPES[keyof typeof CORE_CMS_CONTENT_TYPES]
9
+
10
+ /**
11
+ * Built-in HSZRDM Commerce CMS content types.
12
+ *
13
+ * Projects may still persist and query arbitrary custom content_type strings.
14
+ * This type keeps the built-ins discoverable without restricting extensions.
15
+ */
16
+ export type CmsContentType = CoreCmsContentType | (string & {})
17
+
18
+ export const CORE_CMS_CONTENT_TYPE_OPTIONS = [
19
+ {
20
+ value: CORE_CMS_CONTENT_TYPES.BLOG_POST,
21
+ label: "Blogbejegyzés",
22
+ },
23
+ {
24
+ value: CORE_CMS_CONTENT_TYPES.PAGE,
25
+ label: "Oldal",
26
+ },
27
+ {
28
+ value: CORE_CMS_CONTENT_TYPES.KNOWLEDGE_BASE,
29
+ label: "Tudástár",
30
+ },
31
+ ] as const
32
+
33
+ export function isCoreCmsContentType(value: string): value is CoreCmsContentType {
34
+ return (Object.values(CORE_CMS_CONTENT_TYPES) as string[]).includes(value)
35
+ }
@@ -1,4 +1,16 @@
1
1
  import { medusaFetch } from "./client"
2
+ import {
3
+ CORE_CMS_CONTENT_TYPES,
4
+ type CmsContentType,
5
+ } from "./cms-contract"
6
+
7
+ export {
8
+ CORE_CMS_CONTENT_TYPES,
9
+ CORE_CMS_CONTENT_TYPE_OPTIONS,
10
+ isCoreCmsContentType,
11
+ type CoreCmsContentType,
12
+ type CmsContentType,
13
+ } from "./cms-contract"
2
14
 
3
15
  export type CmsTaxonomyTerm = {
4
16
  id: string
@@ -6,20 +18,20 @@ export type CmsTaxonomyTerm = {
6
18
  name: string
7
19
  slug: string
8
20
  description?: string | null
9
- locale: string
21
+ locale: string | null
10
22
  metadata?: Record<string, unknown> | null
11
23
  }
12
24
 
13
25
  export type CmsEntry = {
14
26
  id: string
15
- content_type: string
27
+ content_type: CmsContentType
16
28
  title: string
17
29
  slug: string
18
30
  excerpt?: string | null
19
31
  body?: string | null
20
32
  body_format: "markdown" | "html" | "blocks"
21
33
  blocks?: unknown
22
- locale: string
34
+ locale: string | null
23
35
  featured_image_url?: string | null
24
36
  featured_image_alt?: string | null
25
37
  author_name?: string | null
@@ -37,7 +49,7 @@ export type CmsEntry = {
37
49
  }
38
50
 
39
51
  export type CmsListOptions = {
40
- contentType?: string
52
+ contentType?: CmsContentType
41
53
  locale?: string
42
54
  category?: string
43
55
  tag?: string
@@ -46,11 +58,16 @@ export type CmsListOptions = {
46
58
  offset?: number
47
59
  }
48
60
 
61
+ export type CmsEntryOptions = {
62
+ contentType?: CmsContentType
63
+ locale?: string
64
+ }
65
+
49
66
  export function cmsConfig() {
50
67
  return medusaFetch<{
51
68
  enabled: true
52
69
  default_locale: string
53
- content_types: Array<{ key: string; label: string }>
70
+ content_types: Array<{ key: CmsContentType; label: string }>
54
71
  body_formats: string[]
55
72
  taxonomies: string[]
56
73
  }>("/store/cms/config", { next: { revalidate: 300 } })
@@ -72,7 +89,7 @@ export function listCmsEntries(options: CmsListOptions = {}) {
72
89
  )
73
90
  }
74
91
 
75
- export function getCmsEntry(slug: string, options: { contentType?: string; locale?: string } = {}) {
92
+ export function getCmsEntry(slug: string, options: CmsEntryOptions = {}) {
76
93
  const params = new URLSearchParams()
77
94
  if (options.contentType) params.set("content_type", options.contentType)
78
95
  if (options.locale) params.set("locale", options.locale)
@@ -83,6 +100,48 @@ export function getCmsEntry(slug: string, options: { contentType?: string; local
83
100
  )
84
101
  }
85
102
 
103
+ export function listBlogPosts(options: Omit<CmsListOptions, "contentType"> = {}) {
104
+ return listCmsEntries({
105
+ ...options,
106
+ contentType: CORE_CMS_CONTENT_TYPES.BLOG_POST,
107
+ })
108
+ }
109
+
110
+ export function getBlogPost(slug: string, options: Omit<CmsEntryOptions, "contentType"> = {}) {
111
+ return getCmsEntry(slug, {
112
+ ...options,
113
+ contentType: CORE_CMS_CONTENT_TYPES.BLOG_POST,
114
+ })
115
+ }
116
+
117
+ export function listCmsPages(options: Omit<CmsListOptions, "contentType"> = {}) {
118
+ return listCmsEntries({
119
+ ...options,
120
+ contentType: CORE_CMS_CONTENT_TYPES.PAGE,
121
+ })
122
+ }
123
+
124
+ export function getCmsPage(slug: string, options: Omit<CmsEntryOptions, "contentType"> = {}) {
125
+ return getCmsEntry(slug, {
126
+ ...options,
127
+ contentType: CORE_CMS_CONTENT_TYPES.PAGE,
128
+ })
129
+ }
130
+
131
+ export function listKnowledgeBaseEntries(options: Omit<CmsListOptions, "contentType"> = {}) {
132
+ return listCmsEntries({
133
+ ...options,
134
+ contentType: CORE_CMS_CONTENT_TYPES.KNOWLEDGE_BASE,
135
+ })
136
+ }
137
+
138
+ export function getKnowledgeBaseEntry(slug: string, options: Omit<CmsEntryOptions, "contentType"> = {}) {
139
+ return getCmsEntry(slug, {
140
+ ...options,
141
+ contentType: CORE_CMS_CONTENT_TYPES.KNOWLEDGE_BASE,
142
+ })
143
+ }
144
+
86
145
  export function listCmsTaxonomy(options: { taxonomy?: "category" | "tag"; locale?: string } = {}) {
87
146
  const params = new URLSearchParams()
88
147
  if (options.taxonomy) params.set("taxonomy", options.taxonomy)
@@ -106,7 +165,7 @@ export function cmsEntrySeo(entry: CmsEntry) {
106
165
  images: entry.og_image_url || entry.featured_image_url
107
166
  ? [entry.og_image_url || entry.featured_image_url]
108
167
  : undefined,
109
- type: entry.content_type === "blog_post" ? "article" : "website",
168
+ type: entry.content_type === CORE_CMS_CONTENT_TYPES.BLOG_POST ? "article" : "website",
110
169
  },
111
170
  }
112
171
  }
@@ -0,0 +1,57 @@
1
+ export function focusFirstInvalidField(root?: ParentNode) {
2
+ if (typeof document === "undefined") return null
3
+ const targetRoot = root || document
4
+ const invalid = targetRoot.querySelector<HTMLElement>(
5
+ "[aria-invalid='true'], input:invalid, select:invalid, textarea:invalid",
6
+ )
7
+ invalid?.focus()
8
+ invalid?.scrollIntoView({ behavior: prefersReducedMotion() ? "auto" : "smooth", block: "center" })
9
+ return invalid || null
10
+ }
11
+
12
+ export function fieldErrorId(fieldName: string) {
13
+ return `field-error-${fieldName.replace(/[^a-zA-Z0-9_-]+/g, "-")}`
14
+ }
15
+
16
+ export function humanizeStorefrontError(error: unknown, locale: "hu" | "en" = "hu") {
17
+ const fallback = locale === "en"
18
+ ? "Something went wrong. Please try again."
19
+ : "Hiba történt. Kérjük, próbáld újra."
20
+ if (!(error instanceof Error)) return fallback
21
+
22
+ const message = error.message.trim()
23
+ if (!message) return fallback
24
+ if (/network|fetch failed|failed to fetch|econn|timeout/i.test(message)) {
25
+ return locale === "en"
26
+ ? "The service is temporarily unavailable. Please try again shortly."
27
+ : "A szolgáltatás átmenetileg nem érhető el. Kérjük, próbáld újra rövidesen."
28
+ }
29
+ if (/unauthorized|401/i.test(message)) {
30
+ return locale === "en" ? "Please sign in to continue." : "A folytatáshoz jelentkezz be."
31
+ }
32
+ if (/forbidden|403/i.test(message)) {
33
+ return locale === "en" ? "You don't have permission for this action." : "Ehhez a művelethez nincs jogosultságod."
34
+ }
35
+ return message.length <= 240 ? message : fallback
36
+ }
37
+
38
+ export function prefersReducedMotion() {
39
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false
40
+ const override = document.documentElement.dataset.motion
41
+ if (override === "reduced") return true
42
+ if (override === "full") return false
43
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches
44
+ }
45
+
46
+ export function accessibilityProps(input: {
47
+ name: string
48
+ error?: string | null
49
+ required?: boolean
50
+ }) {
51
+ const errorId = fieldErrorId(input.name)
52
+ return {
53
+ "aria-invalid": input.error ? true : undefined,
54
+ "aria-describedby": input.error ? errorId : undefined,
55
+ "aria-required": input.required || undefined,
56
+ }
57
+ }
@@ -0,0 +1,53 @@
1
+ import { medusaFetch } from "./client"
2
+
3
+ export type NewsletterConfig = {
4
+ enabled: boolean
5
+ double_opt_in: boolean
6
+ consent_version: string
7
+ consent_url: string | null
8
+ }
9
+
10
+ export type NewsletterSubscriptionState = {
11
+ subscriber: {
12
+ id: string
13
+ status: "pending" | "subscribed" | "unsubscribed"
14
+ double_opt_in?: boolean
15
+ }
16
+ message: string
17
+ }
18
+
19
+ export function newsletterConfig() {
20
+ return medusaFetch<NewsletterConfig>("/store/newsletter/config", {
21
+ next: { revalidate: 300 },
22
+ })
23
+ }
24
+
25
+ export function subscribeNewsletter(input: {
26
+ email: string
27
+ consent: true
28
+ source?: string
29
+ page_url?: string
30
+ utm?: Partial<Record<"utm_source" | "utm_medium" | "utm_campaign" | "utm_term" | "utm_content", string>>
31
+ }) {
32
+ return medusaFetch<NewsletterSubscriptionState>("/store/newsletter", {
33
+ method: "POST",
34
+ body: JSON.stringify(input),
35
+ cache: "no-store",
36
+ })
37
+ }
38
+
39
+ export function confirmNewsletter(token: string) {
40
+ return medusaFetch<NewsletterSubscriptionState>("/store/newsletter/confirm", {
41
+ method: "POST",
42
+ body: JSON.stringify({ token }),
43
+ cache: "no-store",
44
+ })
45
+ }
46
+
47
+ export function unsubscribeNewsletter(token: string) {
48
+ return medusaFetch<NewsletterSubscriptionState>("/store/newsletter/unsubscribe", {
49
+ method: "POST",
50
+ body: JSON.stringify({ token }),
51
+ cache: "no-store",
52
+ })
53
+ }
@@ -0,0 +1,40 @@
1
+ import { medusaFetch } from "./client"
2
+
3
+ export type ProductReview = {
4
+ id: string
5
+ product_id: string
6
+ customer_name: string
7
+ rating: number
8
+ body: string
9
+ verified_purchase: boolean
10
+ status?: "pending" | "approved" | "rejected"
11
+ created_at?: string
12
+ updated_at?: string
13
+ }
14
+
15
+ export type ProductReviewSummary = {
16
+ average: number
17
+ count: number
18
+ }
19
+
20
+ export function listProductReviews(productId: string, options: { limit?: number; offset?: number } = {}) {
21
+ const params = new URLSearchParams()
22
+ if (options.limit != null) params.set("limit", String(options.limit))
23
+ if (options.offset != null) params.set("offset", String(options.offset))
24
+ const query = params.toString()
25
+ return medusaFetch<{
26
+ reviews: ProductReview[]
27
+ summary: ProductReviewSummary
28
+ limit: number
29
+ offset: number
30
+ }>(`/store/products/${encodeURIComponent(productId)}/reviews${query ? `?${query}` : ""}`, {
31
+ cache: "no-store",
32
+ })
33
+ }
34
+
35
+ export function submitProductReview(productId: string, input: { rating: number; body: string }) {
36
+ return medusaFetch<{ review: ProductReview }>(`/store/products/${encodeURIComponent(productId)}/reviews`, {
37
+ method: "POST",
38
+ body: JSON.stringify(input),
39
+ })
40
+ }
@@ -0,0 +1,57 @@
1
+ export type SharePayload = {
2
+ title?: string
3
+ text?: string
4
+ url: string
5
+ }
6
+
7
+ export type ShareResult = "shared" | "copied" | "cancelled"
8
+
9
+ export async function shareContent(payload: SharePayload): Promise<ShareResult> {
10
+ if (typeof window === "undefined") return "cancelled"
11
+
12
+ if (typeof navigator.share === "function") {
13
+ try {
14
+ await navigator.share({
15
+ title: payload.title,
16
+ text: payload.text,
17
+ url: payload.url,
18
+ })
19
+ return "shared"
20
+ } catch (error) {
21
+ if (error instanceof DOMException && error.name === "AbortError") return "cancelled"
22
+ }
23
+ }
24
+
25
+ await copyText(payload.url)
26
+ return "copied"
27
+ }
28
+
29
+ export async function copyText(value: string) {
30
+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
31
+ await navigator.clipboard.writeText(value)
32
+ return
33
+ }
34
+
35
+ if (typeof document === "undefined") throw new Error("Clipboard is not available.")
36
+ const input = document.createElement("textarea")
37
+ input.value = value
38
+ input.setAttribute("readonly", "")
39
+ input.style.position = "fixed"
40
+ input.style.opacity = "0"
41
+ document.body.appendChild(input)
42
+ input.select()
43
+ const copied = document.execCommand("copy")
44
+ input.remove()
45
+ if (!copied) throw new Error("Could not copy to clipboard.")
46
+ }
47
+
48
+ export function shareFallbackLinks(payload: SharePayload) {
49
+ const url = encodeURIComponent(payload.url)
50
+ const title = encodeURIComponent(payload.title || "")
51
+ const text = encodeURIComponent(payload.text || payload.title || "")
52
+ return {
53
+ facebook: `https://www.facebook.com/sharer/sharer.php?u=${url}`,
54
+ linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${url}`,
55
+ email: `mailto:?subject=${title}&body=${text}%0A%0A${url}`,
56
+ }
57
+ }