Template
Vite + Hono + TanStack port of the Shopify storefront
Ports nextjs-templates/shopify-storefront to Vite, TanStack Router/Query, Tailwind v4 and Hono, without the AI store assistant. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
# Shopify Storefront
|
||||
VITE_SHOPIFY_DOMAIN=mock.shop
|
||||
# VITE_SHOPIFY_PUBLIC_ACCESS_TOKEN=
|
||||
# VITE_SHOPIFY_API_VERSION=2026-07
|
||||
|
||||
# Absolute origin used for canonical / Open Graph URLs
|
||||
# VITE_SITE_URL=http://localhost:5173
|
||||
|
||||
# Port for `yarn start`
|
||||
# PORT=3000
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
.DS_Store
|
||||
node_modules/*
|
||||
dist
|
||||
.yarn/install-state.gz
|
||||
.env*.local
|
||||
src/routeTree.gen.ts
|
||||
*.tsbuildinfo
|
||||
|
||||
# Temp tsconfig written by `hydrogen gql check`; normally cleaned up on exit
|
||||
.hydrogen-gql-*.json
|
||||
.tanstack
|
||||
@@ -0,0 +1 @@
|
||||
nodeLinker: node-modules
|
||||
@@ -0,0 +1,52 @@
|
||||
# Vite Shopify Storefront
|
||||
|
||||
A Shopify storefront built with Vite, React 19, TanStack Router, TanStack Query,
|
||||
Tailwind CSS v4, Hono and `@shopify/hydrogen`. It's a port of
|
||||
`nextjs-templates/shopify-storefront` without the AI store assistant.
|
||||
|
||||
## Getting started
|
||||
|
||||
```sh
|
||||
cp .env.example .env.local # defaults to the tokenless mock.shop
|
||||
yarn install
|
||||
yarn dev # http://localhost:5173
|
||||
```
|
||||
|
||||
| Script | What it does |
|
||||
| ---------------- | --------------------------------------------------------- |
|
||||
| `yarn dev` | Vite dev server with the Hono API mounted at `/api` |
|
||||
| `yarn build` | Client build to `dist/client`, server build to `dist/server` |
|
||||
| `yarn start` | Production Node server (API + static client), `PORT` or 3000 |
|
||||
| `yarn typecheck` | `tsc` plus `hydrogen gql check` for the GraphQL documents |
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
server/ Hono API — classic customer accounts behind an httpOnly cookie
|
||||
app.ts /api routes (mounted by @hono/vite-dev-server in dev)
|
||||
account.ts login, logout, register, recover, reset, activate, me, customer
|
||||
node.ts production entry: API + dist/client + SPA fallback
|
||||
src/
|
||||
routes/ TanStack file routes (route tree is generated)
|
||||
hooks/ TanStack Query options + hooks over the Storefront API
|
||||
services/shopify Storefront client, catalogue and customer functions
|
||||
graphql/ Typed `gql()` documents
|
||||
components/ Storefront UI (header, cart drawer, product detail, ...)
|
||||
```
|
||||
|
||||
## How the Next.js pieces map
|
||||
|
||||
| Next.js | Here |
|
||||
| -------------------------------- | ----------------------------------------------------- |
|
||||
| `app/**/page.tsx` | `src/routes/**` (TanStack file routes) |
|
||||
| `generateMetadata` / `metadata` | route `head()` via `src/lib/seo.ts` + `<HeadContent />` |
|
||||
| Server-side data fetching | route `loader`s seeding the TanStack Query cache |
|
||||
| `app/api/account/*` route handlers | `server/account.ts` (Hono) |
|
||||
| `next/headers` cookies | `hono/cookie` |
|
||||
| `next/image` | `src/components/ui/image.tsx` (Shopify CDN `srcset`) |
|
||||
| `useSearchParams` | `validateSearch` + `Route.useSearch()` |
|
||||
| `NEXT_PUBLIC_*` env | `VITE_*` env |
|
||||
|
||||
Catalogue and cart requests go straight from the browser to the Storefront API
|
||||
with the public token. Account requests go through Hono so the customer access
|
||||
token never reaches client JavaScript.
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Shop</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "vite-shopify-storefront",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build && vite build --ssr server/node.ts --outDir dist/server",
|
||||
"start": "NODE_ENV=production node dist/server/node.js",
|
||||
"typecheck": "tsc --noEmit && hydrogen gql check"
|
||||
},
|
||||
"packageManager": "yarn@4.18.0+sha512.fcb8716fe7cd0eece141ffc18b92193a9df9204c1ba83189c288835223fc0bbe64af473bab0d5e9927a7daeb5caf2bb07eb2787cc9338ca040ea125f2a1f2f7e",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@fontsource-variable/geist-mono": "^5.3.0",
|
||||
"@hono/node-server": "^2.1.3",
|
||||
"@remixicon/react": "^4.9.0",
|
||||
"@shopify/hydrogen": "0.0.0-preview-116d5d7-20260730141607",
|
||||
"@tanstack/react-query": "^5.104.1",
|
||||
"@tanstack/react-router": "^1.170.41",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"framer-motion": "^12.42.2",
|
||||
"hono": "^4.13.12",
|
||||
"lucide-react": "^0.562.0",
|
||||
"radix-ui": "^1.6.7",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/vite-dev-server": "^0.26.1",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/router-plugin": "^1.168.42",
|
||||
"@types/node": "^26.6.4",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^8.3.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Classic Storefront customer accounts. The access token only ever lives in
|
||||
// the httpOnly session cookie; none of these routes return it.
|
||||
import { Hono } from 'hono';
|
||||
import {
|
||||
activateAccount,
|
||||
createCustomer,
|
||||
customerErrorMessage,
|
||||
getCustomer,
|
||||
login,
|
||||
logout,
|
||||
recoverPassword,
|
||||
resetPassword,
|
||||
toCustomerGid,
|
||||
} from '@/services/shopify/customer';
|
||||
import {
|
||||
clearSessionToken,
|
||||
getSessionToken,
|
||||
setSessionToken,
|
||||
} from './session';
|
||||
|
||||
type Body = Record<string, string | undefined>;
|
||||
|
||||
// A malformed body reads as empty, so each route's own validation answers it.
|
||||
const readBody = (req: Request): Promise<Body> =>
|
||||
req.json().catch(() => ({}));
|
||||
|
||||
export const account = new Hono();
|
||||
|
||||
// Minimal session probe for the header menu.
|
||||
account.get('/me', async (c) => {
|
||||
const token = getSessionToken(c);
|
||||
if (!token) return c.json({ customer: null });
|
||||
|
||||
const customer = await getCustomer(token, 0);
|
||||
if (!customer) return c.json({ customer: null });
|
||||
|
||||
return c.json({
|
||||
customer: {
|
||||
displayName: customer.displayName,
|
||||
email: customer.email,
|
||||
firstName: customer.firstName,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Full profile with recent orders, for the order history page.
|
||||
account.get('/customer', async (c) => {
|
||||
const token = getSessionToken(c);
|
||||
if (!token) return c.json({ customer: null });
|
||||
|
||||
const customer = await getCustomer(token, 20);
|
||||
return c.json({ customer });
|
||||
});
|
||||
|
||||
account.post('/login', async (c) => {
|
||||
const { email, password } = await readBody(c.req.raw);
|
||||
|
||||
if (!email || !password) {
|
||||
return c.json({ error: 'Enter your email and password.' }, 400);
|
||||
}
|
||||
|
||||
const { token, errors } = await login(email, password);
|
||||
|
||||
if (!token) {
|
||||
// Shopify distinguishes wrong-password from unknown-email; collapse both so
|
||||
// the form can't be used to enumerate accounts.
|
||||
return c.json(
|
||||
{
|
||||
error: errors.length
|
||||
? 'Incorrect email or password.'
|
||||
: customerErrorMessage(errors),
|
||||
},
|
||||
401
|
||||
);
|
||||
}
|
||||
|
||||
setSessionToken(c, token.accessToken, token.expiresAt);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
account.post('/logout', async (c) => {
|
||||
const token = getSessionToken(c);
|
||||
if (token) await logout(token);
|
||||
|
||||
clearSessionToken(c);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
account.post('/register', async (c) => {
|
||||
const { email, password, firstName, lastName } = await readBody(c.req.raw);
|
||||
|
||||
if (!email || !password) {
|
||||
return c.json({ error: 'Enter your email and password.' }, 400);
|
||||
}
|
||||
|
||||
const { errors } = await createCustomer({
|
||||
email,
|
||||
password,
|
||||
firstName,
|
||||
lastName,
|
||||
});
|
||||
|
||||
if (errors.length) {
|
||||
return c.json({ error: customerErrorMessage(errors) }, 400);
|
||||
}
|
||||
|
||||
// Sign the new customer straight in. Accounts needing email confirmation
|
||||
// won't return a token yet, which is not an error.
|
||||
const { token } = await login(email, password);
|
||||
|
||||
if (token) {
|
||||
setSessionToken(c, token.accessToken, token.expiresAt);
|
||||
return c.json({ ok: true, signedIn: true });
|
||||
}
|
||||
|
||||
return c.json({ ok: true, signedIn: false });
|
||||
});
|
||||
|
||||
account.post('/recover', async (c) => {
|
||||
const { email } = await readBody(c.req.raw);
|
||||
|
||||
if (email) await recoverPassword(email);
|
||||
|
||||
// Always the same response, so the form can't reveal who has an account.
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
account.post('/reset', async (c) => {
|
||||
const { id, resetToken, password } = await readBody(c.req.raw);
|
||||
|
||||
if (!id || !resetToken || !password) {
|
||||
return c.json({ error: 'This reset link is incomplete.' }, 400);
|
||||
}
|
||||
|
||||
const { token, errors } = await resetPassword(
|
||||
toCustomerGid(id),
|
||||
resetToken,
|
||||
password
|
||||
);
|
||||
|
||||
if (!token) {
|
||||
return c.json({ error: customerErrorMessage(errors) }, 400);
|
||||
}
|
||||
|
||||
setSessionToken(c, token.accessToken, token.expiresAt);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
account.post('/activate', async (c) => {
|
||||
const { id, activationToken, password } = await readBody(c.req.raw);
|
||||
|
||||
if (!id || !activationToken || !password) {
|
||||
return c.json({ error: 'This activation link is incomplete.' }, 400);
|
||||
}
|
||||
|
||||
const { token, errors } = await activateAccount(
|
||||
toCustomerGid(id),
|
||||
activationToken,
|
||||
password
|
||||
);
|
||||
|
||||
if (!token) {
|
||||
return c.json({ error: customerErrorMessage(errors) }, 400);
|
||||
}
|
||||
|
||||
setSessionToken(c, token.accessToken, token.expiresAt);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
// The API surface. In dev, @hono/vite-dev-server mounts this inside Vite; in
|
||||
// production, server/node.ts serves it alongside the built client.
|
||||
import { Hono } from 'hono';
|
||||
import { account } from './account';
|
||||
|
||||
const app = new Hono().basePath('/api');
|
||||
|
||||
app.route('/account', account);
|
||||
|
||||
app.notFound((c) => c.json({ error: 'Not found' }, 404));
|
||||
|
||||
app.onError((err, c) => {
|
||||
console.error(err);
|
||||
return c.json({ error: 'Something went wrong. Please try again.' }, 500);
|
||||
});
|
||||
|
||||
export default app;
|
||||
@@ -0,0 +1,30 @@
|
||||
// Production entry: the API plus the static client build, with an SPA fallback
|
||||
// so deep links like /products/:handle load index.html.
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { Hono } from 'hono';
|
||||
import { serve } from '@hono/node-server';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import api from './app';
|
||||
|
||||
const CLIENT_DIR = './dist/client';
|
||||
const indexHtml = await readFile(`${CLIENT_DIR}/index.html`, 'utf8');
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
app.route('/', api);
|
||||
// Unknown API paths stay JSON 404s rather than falling through to the SPA.
|
||||
app.all('/api/*', (c) => c.json({ error: 'Not found' }, 404));
|
||||
|
||||
// Hashed build assets never change, so let browsers keep them.
|
||||
app.use('/assets/*', async (c, next) => {
|
||||
await next();
|
||||
c.header('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
});
|
||||
app.use('*', serveStatic({ root: CLIENT_DIR }));
|
||||
app.get('*', (c) => c.html(indexHtml));
|
||||
|
||||
const port = Number(process.env.PORT) || 3000;
|
||||
|
||||
serve({ fetch: app.fetch, port }, (info) => {
|
||||
console.log(`Storefront listening on http://localhost:${info.port}`);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// Customer session, stored in an httpOnly cookie. Server-only: the access token
|
||||
// must never reach the browser's JavaScript.
|
||||
import type { Context } from 'hono';
|
||||
import { getCookie, setCookie, deleteCookie } from 'hono/cookie';
|
||||
import { CUSTOMER_TOKEN_COOKIE } from '@/services/shopify/customer';
|
||||
|
||||
export function getSessionToken(c: Context): string | null {
|
||||
return getCookie(c, CUSTOMER_TOKEN_COOKIE) ?? null;
|
||||
}
|
||||
|
||||
export function setSessionToken(
|
||||
c: Context,
|
||||
accessToken: string,
|
||||
expiresAt: string
|
||||
): void {
|
||||
const expires = new Date(expiresAt);
|
||||
|
||||
setCookie(c, CUSTOMER_TOKEN_COOKIE, accessToken, {
|
||||
httpOnly: true,
|
||||
secure: import.meta.env.PROD,
|
||||
sameSite: 'Lax',
|
||||
path: '/',
|
||||
expires: Number.isNaN(expires.getTime()) ? undefined : expires,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearSessionToken(c: Context): void {
|
||||
deleteCookie(c, CUSTOMER_TOKEN_COOKIE, { path: '/' });
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from 'react';
|
||||
import { Link, type LinkProps } from '@tanstack/react-router';
|
||||
|
||||
interface LogoProps {
|
||||
/** Logo image URL. Falls back to the store name as a wordmark when absent. */
|
||||
src?: string | null;
|
||||
/** Wordmark text, and the image's alt text. */
|
||||
storeName?: string;
|
||||
/** Where the logo links to. Pass null to render it unwrapped. */
|
||||
href?: LinkProps['to'] | null;
|
||||
/** Sizing for the image — height only, so the aspect ratio is preserved. */
|
||||
imageClassName?: string;
|
||||
/** Sizing and weight for the wordmark fallback. */
|
||||
textClassName?: string;
|
||||
}
|
||||
|
||||
const Logo: React.FC<LogoProps> = ({
|
||||
src,
|
||||
storeName = 'Shop',
|
||||
href = '/',
|
||||
imageClassName = 'h-6',
|
||||
textClassName = 'text-xl',
|
||||
}) => {
|
||||
const mark = src ? (
|
||||
<img
|
||||
src={src}
|
||||
alt={storeName}
|
||||
className={`w-auto object-contain ${imageClassName}`}
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
className={`font-medium tracking-tight text-foreground ${textClassName}`}
|
||||
>
|
||||
{storeName}
|
||||
</span>
|
||||
);
|
||||
|
||||
if (href === null) {
|
||||
return <span className="flex items-center">{mark}</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Link to={href} className="flex items-center">
|
||||
{mark}
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
export default Logo;
|
||||
@@ -0,0 +1,40 @@
|
||||
import React from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
|
||||
// Ported from app/not-found.tsx and app/error.tsx. Both render inside the root
|
||||
// layout, so the header and footer stay put.
|
||||
|
||||
export function NotFound() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="text-lg font-medium text-black font-sans whitespace-nowrap">
|
||||
404
|
||||
</div>
|
||||
<div className="border-l border-gray-300 h-6"></div>
|
||||
<div className="text-sm text-gray-700 font-sans max-w-lg">
|
||||
This page could not be found.{' '}
|
||||
<Link to="/" className="underline underline-offset-2">
|
||||
Go home
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorMessage({ error }: { error: unknown }) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="text-lg font-medium text-black font-sans whitespace-nowrap">
|
||||
Something went wrong
|
||||
</div>
|
||||
<div className="border-l border-gray-300 h-6"></div>
|
||||
<div className="text-sm text-gray-700 font-sans max-w-lg">
|
||||
{error instanceof Error ? error.message : String(error)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link, useNavigate, type LinkProps } from '@tanstack/react-router';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ACCOUNT_QUERY_KEY } from '@/hooks/use-account';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
|
||||
export interface AccountFormField {
|
||||
name: string;
|
||||
label: string;
|
||||
type?: 'text' | 'email' | 'password';
|
||||
autoComplete?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
interface AccountFormProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
fields: AccountFormField[];
|
||||
submitLabel: string;
|
||||
endpoint: string;
|
||||
/** Merged into the request body alongside the field values. */
|
||||
extraPayload?: Record<string, string>;
|
||||
/** Where to go on success; omit to show `successMessage` instead. */
|
||||
redirectTo?: LinkProps['to'];
|
||||
successMessage?: string;
|
||||
footer?: React.ReactNode;
|
||||
}
|
||||
|
||||
const AccountForm: React.FC<AccountFormProps> = ({
|
||||
title,
|
||||
description,
|
||||
fields,
|
||||
submitLabel,
|
||||
endpoint,
|
||||
extraPayload,
|
||||
redirectTo,
|
||||
successMessage,
|
||||
footer,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const [values, setValues] = useState<Record<string, string>>({});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (submitting) return;
|
||||
|
||||
try {
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...values, ...extraPayload }),
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
setError(data.error ?? 'Something went wrong. Please try again.');
|
||||
return;
|
||||
}
|
||||
|
||||
// The session cookie may have changed, so drop any cached account state
|
||||
// (header menu, order history) before moving on.
|
||||
await queryClient.invalidateQueries({ queryKey: ACCOUNT_QUERY_KEY });
|
||||
|
||||
if (redirectTo) {
|
||||
await navigate({ to: redirectTo });
|
||||
} else {
|
||||
setDone(true);
|
||||
}
|
||||
} catch {
|
||||
setError('Could not reach the server. Please try again.');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-sm">
|
||||
<h1 className="text-2xl font-normal text-foreground">{title}</h1>
|
||||
{description && (
|
||||
<p className="mt-2 text-sm text-muted-foreground">{description}</p>
|
||||
)}
|
||||
|
||||
{done && successMessage ? (
|
||||
<p className="mt-6 text-sm text-foreground">{successMessage}</p>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
|
||||
{fields.map((field) => (
|
||||
<label key={field.name} className="flex flex-col gap-1.5">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{field.label}
|
||||
</span>
|
||||
<input
|
||||
type={field.type ?? 'text'}
|
||||
name={field.name}
|
||||
required={field.required ?? true}
|
||||
autoComplete={field.autoComplete}
|
||||
value={values[field.name] ?? ''}
|
||||
onChange={(event) =>
|
||||
setValues((prev) => ({
|
||||
...prev,
|
||||
[field.name]: event.target.value,
|
||||
}))
|
||||
}
|
||||
className="h-11 rounded-md border border-border px-3 text-sm outline-none transition-colors focus:border-foreground"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
|
||||
<Button type="submit" disabled={submitting} className="h-11">
|
||||
{submitting && <Loader size={16} />}
|
||||
{submitLabel}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{footer && (
|
||||
<div className="mt-6 flex flex-col gap-2 text-sm text-muted-foreground">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const AccountFormLink: React.FC<{
|
||||
to: LinkProps['to'];
|
||||
children: React.ReactNode;
|
||||
}> = ({
|
||||
to,
|
||||
children,
|
||||
}) => (
|
||||
<Link to={to} className="underline underline-offset-2 hover:text-foreground">
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
|
||||
export default AccountForm;
|
||||
@@ -0,0 +1,93 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link, useNavigate } from '@tanstack/react-router';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
ACCOUNT_QUERY_KEY,
|
||||
sessionQueryOptions,
|
||||
} from '@/hooks/use-account';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { RiUserLine } from '@remixicon/react';
|
||||
|
||||
const AccountMenu: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// The token lives in an httpOnly cookie, so the signed-in state has to come
|
||||
// from the server rather than being read directly.
|
||||
const { data: customer } = useQuery(sessionQueryOptions());
|
||||
|
||||
const handleSignOut = async () => {
|
||||
setOpen(false);
|
||||
await fetch('/api/account/logout', { method: 'POST' });
|
||||
queryClient.removeQueries({ queryKey: ACCOUNT_QUERY_KEY });
|
||||
queryClient.setQueryData(sessionQueryOptions().queryKey, null);
|
||||
await navigate({ to: '/' });
|
||||
};
|
||||
|
||||
// Signed out: straight to the sign-in page, no menu.
|
||||
if (!customer) {
|
||||
return (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Sign in"
|
||||
className="rounded-full"
|
||||
>
|
||||
<Link to="/account/login">
|
||||
<RiUserLine className="size-5" />
|
||||
</Link>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<Button
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Account menu"
|
||||
aria-expanded={open}
|
||||
className="rounded-full"
|
||||
>
|
||||
<RiUserLine className="size-5" />
|
||||
</Button>
|
||||
|
||||
{open && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
<div className="absolute right-0 top-full z-50 mt-1 w-60 rounded-md border border-border bg-background py-1 shadow-md">
|
||||
<div className="px-4 py-2">
|
||||
<p className="truncate text-sm font-medium text-foreground">
|
||||
{customer.firstName || customer.displayName}
|
||||
</p>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{customer.email}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="my-1 h-px bg-border" />
|
||||
|
||||
<Link
|
||||
to="/account"
|
||||
onClick={() => setOpen(false)}
|
||||
className="block px-4 py-2 text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
Order history
|
||||
</Link>
|
||||
<button
|
||||
onClick={handleSignOut}
|
||||
className="block w-full px-4 py-2 text-left text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AccountMenu;
|
||||
@@ -0,0 +1,349 @@
|
||||
import React, { useState } from 'react';
|
||||
import Image from '@/components/ui/image';
|
||||
import { useCartStore, redirectToCheckout } from '@/hooks/use-shopify-cart';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetBody,
|
||||
AnimatePresence,
|
||||
} from '@/components/ui/sheet';
|
||||
import {
|
||||
RiCloseLine,
|
||||
RiImageLine,
|
||||
RiSubtractLine,
|
||||
RiAddLine,
|
||||
} from '@remixicon/react';
|
||||
import {
|
||||
Empty,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
EmptyDescription,
|
||||
EmptyContent,
|
||||
} from '@/components/ui/empty';
|
||||
import { isDefaultTitleSelection } from '@/services/shopify/catalog';
|
||||
|
||||
const CartDrawer: React.FC = () => {
|
||||
const isOpen = useCartStore((s) => s.isOpen);
|
||||
const closeCart = useCartStore((s) => s.closeCart);
|
||||
const loading = useCartStore((s) => s.loading);
|
||||
const cart = useCartStore((s) => s.cart);
|
||||
const removeItem = useCartStore((s) => s.removeItem);
|
||||
const updateItemQuantity = useCartStore((s) => s.updateItemQuantity);
|
||||
const applyDiscountCode = useCartStore((s) => s.applyDiscountCode);
|
||||
|
||||
const [discountCode, setDiscountCode] = useState('');
|
||||
const [discountError, setDiscountError] = useState<string | null>(null);
|
||||
const [applyingDiscount, setApplyingDiscount] = useState(false);
|
||||
// The store's `loading` flag is global, so track the specific line being
|
||||
// changed to keep the other rows interactive.
|
||||
const [pendingLineId, setPendingLineId] = useState<string | null>(null);
|
||||
|
||||
const runLineAction = async (lineId: string, action: () => Promise<unknown>) => {
|
||||
if (pendingLineId) return;
|
||||
|
||||
try {
|
||||
setPendingLineId(lineId);
|
||||
await action();
|
||||
} catch (err) {
|
||||
console.error('Cart line update failed:', err);
|
||||
} finally {
|
||||
setPendingLineId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const items = cart?.lines?.edges?.map((edge) => edge.node) ?? [];
|
||||
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
|
||||
const totalAmount = parseFloat(cart?.cost?.totalAmount?.amount ?? '0');
|
||||
const checkoutUrl = cart?.checkoutUrl ?? null;
|
||||
const appliedDiscounts =
|
||||
cart?.discountCodes?.filter((discount) => discount.applicable) ?? [];
|
||||
|
||||
const handleCheckout = () => {
|
||||
if (checkoutUrl) {
|
||||
redirectToCheckout(checkoutUrl);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApplyDiscount = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
const code = discountCode.trim();
|
||||
if (!code || applyingDiscount) return;
|
||||
|
||||
try {
|
||||
setApplyingDiscount(true);
|
||||
setDiscountError(null);
|
||||
const updatedCart = await applyDiscountCode(code);
|
||||
|
||||
// Shopify accepts unknown codes silently, flagging them as inapplicable.
|
||||
const accepted = updatedCart.discountCodes?.some(
|
||||
(discount) =>
|
||||
discount.applicable &&
|
||||
discount.code.toLowerCase() === code.toLowerCase()
|
||||
);
|
||||
|
||||
if (accepted) {
|
||||
setDiscountCode('');
|
||||
} else {
|
||||
setDiscountError('That code is not valid for this cart.');
|
||||
}
|
||||
} catch {
|
||||
setDiscountError('Could not apply that code. Please try again.');
|
||||
} finally {
|
||||
setApplyingDiscount(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getItemImage = (item: (typeof items)[0]) => {
|
||||
return item.merchandise.image?.url;
|
||||
};
|
||||
|
||||
const getSelectedOptions = (item: (typeof items)[0]) => {
|
||||
// Single-SKU items carry a synthetic `Title: Default Title` — not worth a line.
|
||||
return (item.merchandise.selectedOptions ?? []).filter(
|
||||
(option) => !isDefaultTitleSelection(option)
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => !open && closeCart()}
|
||||
side="right"
|
||||
>
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<SheetContent className="w-full max-w-md" showCloseButton={false}>
|
||||
{/* Header */}
|
||||
<SheetHeader className="min-h-0 px-5 py-4 border-b-0">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<SheetTitle className="text-base font-medium flex items-center gap-x-2">
|
||||
Cart
|
||||
<span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-foreground px-1.5 text-[11px] font-medium text-background">
|
||||
{itemCount}
|
||||
</span>
|
||||
</SheetTitle>
|
||||
<Button
|
||||
onClick={closeCart}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Close cart"
|
||||
className="rounded-full"
|
||||
>
|
||||
<RiCloseLine className="size-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
{/* Cart Items */}
|
||||
<SheetBody className="px-5">
|
||||
{loading && items.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader size={20} />
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>Your cart is empty</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Add some products to get started!
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<Button onClick={closeCart} className="w-full">
|
||||
Continue Shopping
|
||||
</Button>
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
{items.map((item) => {
|
||||
const image = getItemImage(item);
|
||||
const selectedOptions = getSelectedOptions(item);
|
||||
const isPending = pendingLineId === item.id;
|
||||
|
||||
return (
|
||||
<div key={item.id} className="flex items-start gap-x-3">
|
||||
{/* Product Image */}
|
||||
<div className="w-16 h-16 bg-zinc-100 overflow-hidden shrink-0">
|
||||
{image ? (
|
||||
<Image
|
||||
src={image}
|
||||
alt={item.merchandise.product.title}
|
||||
width={64}
|
||||
height={64}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-zinc-400">
|
||||
<RiImageLine size={20} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Product Details */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-start justify-between gap-x-3">
|
||||
<h4 className="text-sm font-medium text-foreground line-clamp-2">
|
||||
{item.merchandise.product.title}
|
||||
</h4>
|
||||
<span className="shrink-0 font-mono tabular-nums tracking-tight text-sm text-foreground">
|
||||
$
|
||||
{parseFloat(
|
||||
item.cost?.totalAmount?.amount ??
|
||||
item.merchandise.price.amount
|
||||
).toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{selectedOptions.length > 0 && (
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{selectedOptions
|
||||
.map((option) => option.value)
|
||||
.join(' / ')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quantity Controls */}
|
||||
<div className="flex items-center gap-x-2 mt-2">
|
||||
<div className="inline-flex items-center rounded-full bg-secondary">
|
||||
<Button
|
||||
onClick={() =>
|
||||
runLineAction(item.id, () =>
|
||||
updateItemQuantity(
|
||||
item.id,
|
||||
item.quantity - 1
|
||||
)
|
||||
)
|
||||
}
|
||||
disabled={item.quantity <= 1 || isPending}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Decrease quantity"
|
||||
className="size-7 rounded-full"
|
||||
>
|
||||
<RiSubtractLine size={14} />
|
||||
</Button>
|
||||
<span className="min-w-8 px-1 text-sm tabular-nums text-center">
|
||||
{isPending ? (
|
||||
<Loader size={12} className="mx-auto" />
|
||||
) : (
|
||||
item.quantity
|
||||
)}
|
||||
</span>
|
||||
<Button
|
||||
onClick={() =>
|
||||
runLineAction(item.id, () =>
|
||||
updateItemQuantity(
|
||||
item.id,
|
||||
item.quantity + 1
|
||||
)
|
||||
)
|
||||
}
|
||||
disabled={isPending}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Increase quantity"
|
||||
className="size-7 rounded-full"
|
||||
>
|
||||
<RiAddLine size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() =>
|
||||
runLineAction(item.id, () => removeItem(item.id))
|
||||
}
|
||||
disabled={isPending}
|
||||
variant="link"
|
||||
aria-label={`Remove ${item.merchandise.product.title}`}
|
||||
className="ml-auto h-7 self-center px-0 text-xs font-normal leading-none text-muted-foreground underline decoration-dashed underline-offset-2 hover:text-foreground hover:no-underline"
|
||||
>
|
||||
remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</SheetBody>
|
||||
|
||||
{/* Footer — discount, total, checkout */}
|
||||
{items.length > 0 && (
|
||||
<div className="px-5 py-5 space-y-4">
|
||||
{/* Discount Code */}
|
||||
<form onSubmit={handleApplyDiscount} className="flex gap-x-2">
|
||||
<input
|
||||
type="text"
|
||||
value={discountCode}
|
||||
onChange={(event) => {
|
||||
setDiscountCode(event.target.value);
|
||||
setDiscountError(null);
|
||||
}}
|
||||
placeholder="Discount code"
|
||||
aria-label="Discount code"
|
||||
className="flex-1 h-10 rounded-md border border-border px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:border-foreground transition-colors"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!discountCode.trim() || applyingDiscount}
|
||||
className="h-10 bg-muted-foreground px-5 hover:bg-foreground"
|
||||
>
|
||||
{applyingDiscount ? <Loader size={16} /> : 'Apply'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{discountError && (
|
||||
<p className="text-xs text-destructive">{discountError}</p>
|
||||
)}
|
||||
|
||||
{appliedDiscounts.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Applied: {appliedDiscounts.map((d) => d.code).join(', ')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Estimated total */}
|
||||
<div>
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="text-base text-foreground">
|
||||
Estimated total
|
||||
</span>
|
||||
<span className="font-mono tabular-nums tracking-tight text-lg text-foreground">
|
||||
${totalAmount.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Taxes and shipping calculated at checkout.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleCheckout}
|
||||
disabled={!checkoutUrl || pendingLineId !== null}
|
||||
className="h-12 w-full"
|
||||
>
|
||||
Go to Checkout
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={closeCart}
|
||||
variant="ghost"
|
||||
className="w-full font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Continue Shopping
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
|
||||
export default CartDrawer;
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import Image from '@/components/ui/image';
|
||||
|
||||
interface CollectionImage {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
}
|
||||
|
||||
interface Collection {
|
||||
id: string;
|
||||
title: string;
|
||||
handle: string;
|
||||
description?: string;
|
||||
image?: CollectionImage | null;
|
||||
}
|
||||
|
||||
interface CollectionCardProps {
|
||||
collection: Collection;
|
||||
}
|
||||
|
||||
const CollectionCard: React.FC<CollectionCardProps> = ({ collection }) => {
|
||||
return (
|
||||
<Link
|
||||
to="/collections/$handle"
|
||||
params={{ handle: collection.handle }}
|
||||
className="group block h-full"
|
||||
>
|
||||
{/* Collection Image */}
|
||||
<div className="relative aspect-square overflow-hidden">
|
||||
{collection.image ? (
|
||||
<Image
|
||||
src={collection.image.url}
|
||||
alt={collection.image.altText || collection.title}
|
||||
fill
|
||||
sizes="(min-width: 1024px) 25vw, 50vw"
|
||||
className="object-cover transition-transform duration-500 group-hover:scale-[1.04]"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-zinc-300">
|
||||
<i className="ri-folder-line text-8xl"></i>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Collection Info */}
|
||||
<div className="flex flex-col flex-1 py-2.5">
|
||||
<h3 className="text-sm font-medium text-foreground line-clamp-1">
|
||||
{collection.title}
|
||||
</h3>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
export default CollectionCard;
|
||||
@@ -0,0 +1,180 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useParams } from '@tanstack/react-router';
|
||||
import ProductCard from './product-card';
|
||||
import ProductFilters, { type ProductFilterFacet } from './product-filters';
|
||||
import ProductToolbar from './product-toolbar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
import {
|
||||
collectionProductsInfiniteQueryOptions,
|
||||
type CollectionSortKey,
|
||||
} from '@/hooks/use-shopify-collections';
|
||||
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
const GRID_CLASSES =
|
||||
'grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 gap-x-8 gap-y-12';
|
||||
|
||||
interface SortOption {
|
||||
label: string;
|
||||
sortKey: CollectionSortKey;
|
||||
reverse: boolean;
|
||||
}
|
||||
|
||||
const SORT_OPTIONS: SortOption[] = [
|
||||
{ label: 'Featured', sortKey: 'COLLECTION_DEFAULT', reverse: false },
|
||||
{ label: 'Best Selling', sortKey: 'BEST_SELLING', reverse: false },
|
||||
{ label: 'Price: Low to High', sortKey: 'PRICE', reverse: false },
|
||||
{ label: 'Price: High to Low', sortKey: 'PRICE', reverse: true },
|
||||
{ label: 'Newest', sortKey: 'CREATED', reverse: true },
|
||||
];
|
||||
|
||||
interface CollectionDetailProps {
|
||||
handle: string;
|
||||
}
|
||||
|
||||
const CollectionDetail: React.FC<CollectionDetailProps> = ({ handle }) => {
|
||||
const [filters, setFilters] = useState<ProductFilterFacet[]>([]);
|
||||
const [sortIndex, setSortIndex] = useState(0);
|
||||
const [filtersOpen, setFiltersOpen] = useState(false);
|
||||
const [activeFilters, setActiveFilters] = useState<string[]>([]);
|
||||
|
||||
const sort = SORT_OPTIONS[sortIndex];
|
||||
|
||||
// Fall back to the handle until the collection's real title arrives.
|
||||
const formattedTitle = handle
|
||||
? handle.replace(/-/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())
|
||||
: 'Collection';
|
||||
|
||||
// Sort and filters are part of the query key, so changing either starts a
|
||||
// fresh first page.
|
||||
const {
|
||||
data,
|
||||
isPending: loading,
|
||||
error: queryError,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage: loadingMore,
|
||||
} = useInfiniteQuery(
|
||||
collectionProductsInfiniteQueryOptions(handle, {
|
||||
first: PAGE_SIZE,
|
||||
sortKey: sort.sortKey,
|
||||
reverse: sort.reverse,
|
||||
filterInputs: activeFilters,
|
||||
})
|
||||
);
|
||||
|
||||
const firstPage = data?.pages[0];
|
||||
const title = firstPage?.collection?.title ?? null;
|
||||
const error = queryError
|
||||
? queryError.message || 'Failed to load collection'
|
||||
: firstPage && !firstPage.collection
|
||||
? 'Collection not found'
|
||||
: null;
|
||||
|
||||
const products = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
return (data?.pages ?? [])
|
||||
.flatMap((page) => page.products)
|
||||
.filter((product) => !seen.has(product.id) && seen.add(product.id));
|
||||
}, [data]);
|
||||
|
||||
// Keep the facet list stable while a selection is active, so options don't
|
||||
// disappear out from under the panel.
|
||||
useEffect(() => {
|
||||
if (firstPage && activeFilters.length === 0) setFilters(firstPage.filters);
|
||||
}, [firstPage, activeFilters.length]);
|
||||
|
||||
const handleLoadMore = () => {
|
||||
if (!loadingMore && hasNextPage) fetchNextPage();
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="bg-background py-10">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<h1 className="text-3xl md:text-4xl font-normal text-foreground">
|
||||
{title || formattedTitle}
|
||||
</h1>
|
||||
|
||||
<div className="mt-6">
|
||||
<ProductToolbar
|
||||
totalCount={products.length > 0 ? products.length : null}
|
||||
onOpenFilters={() => setFiltersOpen(true)}
|
||||
sortOptions={SORT_OPTIONS}
|
||||
sortIndex={sortIndex}
|
||||
onSortChange={setSortIndex}
|
||||
activeFilterCount={activeFilters.length}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-8">
|
||||
{loading ? (
|
||||
<div className={GRID_CLASSES}>
|
||||
{Array.from({ length: 10 }).map((_, index) => (
|
||||
<div key={index} className="animate-pulse">
|
||||
<div className="aspect-square bg-zinc-100"></div>
|
||||
<div className="pt-4 space-y-2">
|
||||
<div className="h-4 w-4/5 bg-zinc-200"></div>
|
||||
<div className="h-4 w-1/4 bg-zinc-200"></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : error ? (
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
) : products.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{activeFilters.length > 0
|
||||
? 'No products matched your filters.'
|
||||
: "This collection doesn't have any products yet."}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className={GRID_CLASSES}>
|
||||
{products.map((product) => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{hasNextPage && (
|
||||
<div className="mt-16 flex justify-center">
|
||||
<Button
|
||||
onClick={handleLoadMore}
|
||||
disabled={loadingMore}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{loadingMore && <Loader size={16} />}
|
||||
{loadingMore ? 'Loading' : 'Load more'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProductFilters
|
||||
open={filtersOpen}
|
||||
onOpenChange={setFiltersOpen}
|
||||
filters={filters}
|
||||
activeFilters={activeFilters}
|
||||
onActiveFiltersChange={setActiveFilters}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default CollectionDetail;
|
||||
|
||||
/**
|
||||
* Route body for /collections/$handle — used as both the route component and
|
||||
* its pending component, since the page skeleton comes from the same query.
|
||||
*/
|
||||
export function CollectionPage() {
|
||||
const { handle } = useParams({ from: '/collections/$handle' });
|
||||
// Keyed so sort and filter state reset when moving between collections.
|
||||
return <CollectionDetail key={handle} handle={handle} />;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import React from 'react';
|
||||
import { useCollections } from '@/hooks/use-shopify-collections';
|
||||
import CollectionCard from './collection-card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface CollectionsProps {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
}
|
||||
|
||||
const SectionHeader: React.FC<{ title: string; subtitle?: string }> = ({
|
||||
title,
|
||||
subtitle,
|
||||
}) => (
|
||||
<>
|
||||
<h2 className="text-center text-2xl md:text-3xl font-normal max-w-3xl mx-auto text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
{subtitle && (
|
||||
<p className="text-center text-sm font-normal max-w-xl mx-auto text-muted-foreground mt-2.5 mb-16">
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const GRID_CLASSES = 'grid grid-cols-2 lg:grid-cols-4 gap-x-8 gap-y-12';
|
||||
|
||||
const Collections: React.FC<CollectionsProps> = ({
|
||||
title = 'Our Collections',
|
||||
subtitle = 'Discover our carefully crafted worlds',
|
||||
}) => {
|
||||
const { collections, loading, error, refetch } = useCollections(12);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="py-20 bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<SectionHeader title={title} subtitle={subtitle} />
|
||||
|
||||
<div className={GRID_CLASSES}>
|
||||
{Array.from({ length: 8 }).map((_, index) => (
|
||||
<div key={index} className="animate-pulse">
|
||||
<div className="aspect-square bg-zinc-100"></div>
|
||||
<div className="pt-4">
|
||||
<div className="h-4 bg-zinc-200 w-3/5"></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="py-20 bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8 text-center">
|
||||
<SectionHeader title={title} subtitle={subtitle} />
|
||||
<p className="text-sm text-muted-foreground mb-6">{error}</p>
|
||||
<Button onClick={() => refetch()} variant="outline">
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (collections.length === 0) {
|
||||
return (
|
||||
<div className="py-20 bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8 text-center">
|
||||
<SectionHeader title={title} subtitle={subtitle} />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Collections will appear here once added to your Shopify store.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="py-20 bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<SectionHeader title={title} subtitle={subtitle} />
|
||||
|
||||
<div className={GRID_CLASSES}>
|
||||
{collections.map((collection) => (
|
||||
<CollectionCard key={collection.id} collection={collection} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Collections;
|
||||
@@ -0,0 +1,101 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
RiInstagramLine,
|
||||
RiTiktokLine,
|
||||
RiFacebookFill,
|
||||
} from '@remixicon/react';
|
||||
import { Link, linkOptions, type LinkOptions } from '@tanstack/react-router';
|
||||
import Logo from '@/components/logo';
|
||||
|
||||
export interface FooterLink {
|
||||
label: string;
|
||||
/** Built with `linkOptions()`, so dynamic routes carry typed params. */
|
||||
link: LinkOptions;
|
||||
}
|
||||
|
||||
const policyLink = (label: string, handle: string): FooterLink => ({
|
||||
label,
|
||||
link: linkOptions({ to: '/policies/$handle', params: { handle } }),
|
||||
});
|
||||
|
||||
interface FooterProps {
|
||||
storeName?: string;
|
||||
logoUrl?: string;
|
||||
copyright?: string;
|
||||
links?: FooterLink[];
|
||||
instagramUrl?: string;
|
||||
tiktokUrl?: string;
|
||||
facebookUrl?: string;
|
||||
}
|
||||
|
||||
const Footer: React.FC<FooterProps> = ({
|
||||
storeName = 'Shop',
|
||||
logoUrl,
|
||||
copyright,
|
||||
links = [
|
||||
policyLink('Terms of Service', 'terms-of-service'),
|
||||
policyLink('Privacy Policy', 'privacy-policy'),
|
||||
policyLink('Refund Policy', 'refund-policy'),
|
||||
policyLink('Shipping Policy', 'shipping-policy'),
|
||||
policyLink('Subscription Policy', 'subscription-policy'),
|
||||
],
|
||||
instagramUrl = '#',
|
||||
tiktokUrl = '#',
|
||||
facebookUrl = '#',
|
||||
}) => {
|
||||
const socials = [
|
||||
{ label: 'Instagram', url: instagramUrl, Icon: RiInstagramLine },
|
||||
{ label: 'TikTok', url: tiktokUrl, Icon: RiTiktokLine },
|
||||
{ label: 'Facebook', url: facebookUrl, Icon: RiFacebookFill },
|
||||
];
|
||||
|
||||
return (
|
||||
<footer className="bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8 py-10">
|
||||
{/* Links and socials sit on separate rows so the icons aren't
|
||||
crammed onto the end of the link list. */}
|
||||
<div className="flex flex-col items-center gap-y-5 sm:items-start">
|
||||
<Logo
|
||||
src={logoUrl}
|
||||
storeName={storeName}
|
||||
imageClassName="h-5"
|
||||
textClassName="text-base"
|
||||
/>
|
||||
|
||||
<nav className="flex flex-wrap items-center justify-center gap-x-5 gap-y-2 sm:justify-start">
|
||||
{links.map((link) => (
|
||||
<Link
|
||||
key={link.label}
|
||||
{...link.link}
|
||||
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="flex flex-col-reverse items-center gap-3 sm:flex-row sm:gap-x-5">
|
||||
<span className="flex items-center gap-x-4">
|
||||
{socials.map(({ label, url, Icon }) => (
|
||||
<a
|
||||
key={label}
|
||||
href={url}
|
||||
aria-label={label}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Icon size={18} />
|
||||
</a>
|
||||
))}
|
||||
</span>
|
||||
|
||||
<p className="text-sm text-muted-foreground leading-5">
|
||||
{copyright || `© ${storeName}. All rights reserved.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Footer;
|
||||
@@ -0,0 +1,151 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link, type LinkProps } from '@tanstack/react-router';
|
||||
import { useCartStore } from '@/hooks/use-shopify-cart';
|
||||
import CartDrawer from '@/components/shopify/cart-drawer';
|
||||
import SearchDialog from '@/components/shopify/search-dialog';
|
||||
import AccountMenu from '@/components/shopify/account-menu';
|
||||
import ShopMenu from '@/components/shopify/shop-menu';
|
||||
import { RiShoppingBagLine, RiCloseLine, RiMenu3Line } from '@remixicon/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Logo from '@/components/logo';
|
||||
|
||||
const CartIcon: React.FC = () => {
|
||||
const toggleCart = useCartStore((s) => s.toggleCart);
|
||||
const cart = useCartStore((s) => s.cart);
|
||||
const itemCount =
|
||||
cart?.lines?.edges?.reduce((sum, { node }) => sum + node.quantity, 0) ?? 0;
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={toggleCart}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Open bag (${itemCount})`}
|
||||
className="relative rounded-full"
|
||||
>
|
||||
<RiShoppingBagLine className="size-5" />
|
||||
{itemCount > 0 && (
|
||||
<span className="absolute top-0 right-0 bg-primary text-primary-foreground text-[10px] font-mono rounded-full w-4 h-4 flex items-center justify-center">
|
||||
{itemCount > 99 ? '99+' : itemCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export interface NavLink {
|
||||
label: string;
|
||||
url: LinkProps['to'];
|
||||
}
|
||||
|
||||
interface HeaderProps {
|
||||
storeName?: string;
|
||||
logoUrl?: string;
|
||||
links?: readonly NavLink[];
|
||||
/** Thin bar above the nav. Pass null to hide it. */
|
||||
announcement?: string | null;
|
||||
announcementUrl?: LinkProps['to'];
|
||||
}
|
||||
|
||||
const Header: React.FC<HeaderProps> = ({
|
||||
storeName = 'Logo',
|
||||
logoUrl,
|
||||
links = [
|
||||
{ label: 'Shop', url: '/' },
|
||||
{ label: 'Collections', url: '/collections' },
|
||||
],
|
||||
announcement = 'Free shipping on orders over $100',
|
||||
announcementUrl,
|
||||
}) => {
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Sits above the sticky nav, so it scrolls away on its own. */}
|
||||
{announcement && (
|
||||
<div className="bg-muted text-foreground">
|
||||
<div className="max-w-screen-2xl mx-auto flex h-9 items-center justify-center px-8 text-center text-xs">
|
||||
{announcementUrl ? (
|
||||
<Link
|
||||
to={announcementUrl}
|
||||
className="underline-offset-2 hover:underline"
|
||||
>
|
||||
{announcement}
|
||||
</Link>
|
||||
) : (
|
||||
<span>{announcement}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<nav className="bg-background/95 backdrop-blur-md sticky top-0 z-50">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<div className="flex justify-between items-center h-14">
|
||||
{/* Logo */}
|
||||
<Logo src={logoUrl} storeName={storeName} />
|
||||
|
||||
{/* Desktop Navigation */}
|
||||
<div className="hidden md:flex items-center gap-x-8 text-sm">
|
||||
<ShopMenu />
|
||||
{links.map((link, index) => (
|
||||
<Link
|
||||
key={index}
|
||||
to={link.url}
|
||||
className="text-foreground hover:text-muted-foreground transition-colors"
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center">
|
||||
<SearchDialog />
|
||||
<AccountMenu />
|
||||
<CartIcon />
|
||||
|
||||
{/* Mobile hamburger */}
|
||||
<Button
|
||||
onClick={() => setMenuOpen(!menuOpen)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="md:hidden"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
{menuOpen ? (
|
||||
<RiCloseLine className="size-5" />
|
||||
) : (
|
||||
<RiMenu3Line className="size-5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mobile Menu */}
|
||||
{menuOpen && (
|
||||
<div className="md:hidden bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8 pb-6 flex flex-col gap-y-4 text-sm">
|
||||
<ShopMenu mobile onNavigate={() => setMenuOpen(false)} />
|
||||
{links.map((link, index) => (
|
||||
<Link
|
||||
key={index}
|
||||
to={link.url}
|
||||
onClick={() => setMenuOpen(false)}
|
||||
className="text-foreground hover:text-muted-foreground transition-colors"
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CartDrawer />
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Header;
|
||||
@@ -0,0 +1,167 @@
|
||||
import React, { useState } from 'react';
|
||||
import Image from '@/components/ui/image';
|
||||
import { RiImageLine } from '@remixicon/react';
|
||||
import type { Customer, CustomerOrder } from '@/services/shopify/customer';
|
||||
|
||||
interface OrderHistoryProps {
|
||||
customer: Customer;
|
||||
}
|
||||
|
||||
const formatMoney = (amount: string, currencyCode: string) => {
|
||||
const value = parseFloat(amount);
|
||||
try {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currencyCode,
|
||||
}).format(value);
|
||||
} catch {
|
||||
return `$${value.toFixed(2)}`;
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (iso: string) =>
|
||||
new Date(iso).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
});
|
||||
|
||||
const StatusPill: React.FC<{ label?: string | null }> = ({ label }) => {
|
||||
if (!label) return null;
|
||||
return (
|
||||
<span className="rounded-full bg-secondary px-2 py-0.5 text-[11px] uppercase tracking-wide text-muted-foreground">
|
||||
{label.replace(/_/g, ' ').toLowerCase()}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const OrderHistory: React.FC<OrderHistoryProps> = ({ customer }) => {
|
||||
const orders: CustomerOrder[] =
|
||||
customer.orders?.edges.map((edge) => edge.node) ?? [];
|
||||
|
||||
// The Storefront API has no standalone order-by-id query for customers, so
|
||||
// the detail is rendered from the order already loaded in this list.
|
||||
const [selectedId, setSelectedId] = useState<string | null>(
|
||||
orders[0]?.id ?? null
|
||||
);
|
||||
const selected = orders.find((order) => order.id === selectedId) ?? null;
|
||||
|
||||
if (orders.length === 0) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You haven't placed any orders yet.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-8 lg:grid-cols-5">
|
||||
{/* List */}
|
||||
<div className="lg:col-span-2">
|
||||
<h2 className="mb-3 text-sm text-muted-foreground">Orders</h2>
|
||||
<ul className="flex flex-col">
|
||||
{orders.map((order) => {
|
||||
const isSelected = order.id === selectedId;
|
||||
|
||||
return (
|
||||
<li key={order.id}>
|
||||
<button
|
||||
onClick={() => setSelectedId(order.id)}
|
||||
aria-current={isSelected}
|
||||
className={`flex w-full items-baseline justify-between gap-x-4 rounded-md px-3 py-3 text-left transition-colors ${
|
||||
isSelected ? 'bg-secondary' : 'hover:bg-secondary/60'
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-sm font-medium text-foreground">
|
||||
Order #{order.orderNumber}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{formatDate(order.processedAt)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="shrink-0 font-mono text-sm tabular-nums tracking-tight text-foreground">
|
||||
{formatMoney(
|
||||
order.currentTotalPrice.amount,
|
||||
order.currentTotalPrice.currencyCode
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Detail — same screen, no navigation */}
|
||||
<div className="lg:col-span-3">
|
||||
{selected && (
|
||||
<>
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-2">
|
||||
<h2 className="text-lg text-foreground">
|
||||
Order #{selected.orderNumber}
|
||||
</h2>
|
||||
<span className="font-mono text-base tabular-nums tracking-tight text-foreground">
|
||||
{formatMoney(
|
||||
selected.currentTotalPrice.amount,
|
||||
selected.currentTotalPrice.currencyCode
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Placed {formatDate(selected.processedAt)}
|
||||
</span>
|
||||
<StatusPill label={selected.financialStatus} />
|
||||
<StatusPill label={selected.fulfillmentStatus} />
|
||||
</div>
|
||||
|
||||
<ul className="mt-6 flex flex-col gap-4">
|
||||
{selected.lineItems.edges.map(({ node }, index) => (
|
||||
<li key={index} className="flex items-start gap-x-3">
|
||||
<div className="h-16 w-16 shrink-0 overflow-hidden bg-zinc-100">
|
||||
{node.variant?.image ? (
|
||||
<Image
|
||||
src={node.variant.image.url}
|
||||
alt={node.variant.image.altText || node.title}
|
||||
width={64}
|
||||
height={64}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-zinc-400">
|
||||
<RiImageLine className="size-5" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{node.title}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Qty {node.quantity}
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{selected.statusUrl && (
|
||||
<a
|
||||
href={selected.statusUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="mt-6 inline-block text-sm text-muted-foreground underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
View order status
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrderHistory;
|
||||
@@ -0,0 +1,120 @@
|
||||
import React from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import Image from '@/components/ui/image';
|
||||
import { truncate } from '@/lib/utils';
|
||||
|
||||
interface ProductImage {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
}
|
||||
|
||||
interface ProductPrice {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
interface ProductVariant {
|
||||
id: string;
|
||||
title: string;
|
||||
price: ProductPrice;
|
||||
availableForSale: boolean;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
handle: string;
|
||||
images: {
|
||||
edges: Array<{
|
||||
node: ProductImage;
|
||||
}>;
|
||||
};
|
||||
priceRange: {
|
||||
minVariantPrice: ProductPrice;
|
||||
};
|
||||
compareAtPriceRange?: {
|
||||
minVariantPrice: ProductPrice;
|
||||
};
|
||||
variants: {
|
||||
edges: Array<{
|
||||
node: ProductVariant;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
interface ProductCardProps {
|
||||
product: Product;
|
||||
}
|
||||
|
||||
const ProductCard: React.FC<ProductCardProps> = ({ product }) => {
|
||||
const firstImage = product.images.edges[0]?.node;
|
||||
const price = product.priceRange.minVariantPrice;
|
||||
const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
|
||||
const hasDiscount =
|
||||
compareAtPrice &&
|
||||
parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
|
||||
const firstVariant = product.variants.edges[0]?.node;
|
||||
const isAvailable = firstVariant?.availableForSale || false;
|
||||
|
||||
const formatPrice = (amount: string) => {
|
||||
return `$${parseFloat(amount).toFixed(2)}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Link
|
||||
to="/products/$handle"
|
||||
params={{ handle: product.handle }}
|
||||
className="group block h-full"
|
||||
>
|
||||
{/* Product Image */}
|
||||
<div className="relative aspect-square overflow-hidden">
|
||||
{firstImage ? (
|
||||
<Image
|
||||
src={firstImage.url}
|
||||
alt={firstImage.altText || product.title}
|
||||
fill
|
||||
sizes="(min-width: 1280px) 20vw, (min-width: 1024px) 25vw, (min-width: 640px) 33vw, 50vw"
|
||||
className="object-contain transition-transform duration-500 group-hover:scale-[1.04]"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-zinc-300">
|
||||
<i className="ri-image-line text-8xl"></i>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasDiscount && compareAtPrice && (
|
||||
<span className="absolute top-3 left-3 text-[11px] font-mono tracking-widest text-rose-600">
|
||||
SALE
|
||||
</span>
|
||||
)}
|
||||
|
||||
{!isAvailable && (
|
||||
<span className="absolute top-3 right-3 text-[11px] font-mono tracking-widest text-muted-foreground">
|
||||
SOLD OUT
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Product Info */}
|
||||
<div className="flex flex-col flex-1 py-2.5">
|
||||
<h3 className="text-sm font-medium text-foreground line-clamp-1">
|
||||
{truncate(product.title, 65)}
|
||||
</h3>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="font-mono tabular-nums tracking-tight text-sm text-foreground">
|
||||
{formatPrice(price.amount)}
|
||||
</span>
|
||||
{hasDiscount && compareAtPrice && (
|
||||
<span className="font-mono tabular-nums tracking-tight text-sm line-through text-muted-foreground">
|
||||
{formatPrice(compareAtPrice.amount)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductCard;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useParams } from '@tanstack/react-router';
|
||||
import ProductDetail from './product-detail/index';
|
||||
import ProductRecommendations from './product-recommendations';
|
||||
|
||||
export default ProductDetail;
|
||||
|
||||
/**
|
||||
* Route body for /products/$handle — used as both the route component and its
|
||||
* pending component, since the skeleton comes from the same in-flight query.
|
||||
*/
|
||||
export function ProductPage() {
|
||||
const { handle } = useParams({ from: '/products/$handle' });
|
||||
|
||||
return (
|
||||
<>
|
||||
<ProductDetail handle={handle} addToCartLabel="Add to Cart" />
|
||||
<ProductRecommendations title="You May Also Like" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useParams } from '@tanstack/react-router';
|
||||
import { useProduct, type Product } from '@/hooks/use-shopify-products';
|
||||
import { useShopifyCart, redirectToCheckout } from '@/hooks/use-shopify-cart';
|
||||
import ProductDetailGallery from './product-detail-gallery';
|
||||
import ProductDetailInfo from './product-detail-info';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Empty,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
EmptyDescription,
|
||||
EmptyContent,
|
||||
} from '@/components/ui/empty';
|
||||
|
||||
interface ProductVariant {
|
||||
id: string;
|
||||
title: string;
|
||||
price: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
};
|
||||
availableForSale: boolean;
|
||||
selectedOptions: Array<{
|
||||
name: string;
|
||||
value: string;
|
||||
}>;
|
||||
image?: {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export type { Product };
|
||||
|
||||
interface ProductDetailProps {
|
||||
handle?: string;
|
||||
addToCartLabel?: string;
|
||||
}
|
||||
|
||||
const ProductDetail: React.FC<ProductDetailProps> = ({
|
||||
handle: handleProp,
|
||||
addToCartLabel = 'Add to Cart',
|
||||
}) => {
|
||||
const params = useParams({ strict: false });
|
||||
const handle = handleProp || params.handle || '';
|
||||
const { addItem, openCart, checkoutUrl } = useShopifyCart();
|
||||
|
||||
const { product, loading, error } = useProduct(handle);
|
||||
|
||||
const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(
|
||||
null
|
||||
);
|
||||
const [selectedOptions, setSelectedOptions] = useState<
|
||||
Record<string, string>
|
||||
>({});
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [addingToCart, setAddingToCart] = useState(false);
|
||||
const [buyingNow, setBuyingNow] = useState(false);
|
||||
|
||||
// Initialize variant when product loads
|
||||
useEffect(() => {
|
||||
if (product) {
|
||||
const firstVariant = product.variants.edges[0]?.node;
|
||||
if (firstVariant) {
|
||||
setSelectedVariant(firstVariant);
|
||||
|
||||
const initialOptions: Record<string, string> = {};
|
||||
firstVariant.selectedOptions.forEach(
|
||||
(option: { name: string; value: string }) => {
|
||||
initialOptions[option.name] = option.value;
|
||||
}
|
||||
);
|
||||
setSelectedOptions(initialOptions);
|
||||
}
|
||||
}
|
||||
}, [product]);
|
||||
|
||||
// A value is available if some in-stock variant carries it alongside the
|
||||
// other currently-selected options. Options the shopper hasn't chosen yet
|
||||
// act as wildcards, so nothing is struck through before a full selection.
|
||||
const isOptionValueAvailable = (optionName: string, value: string) => {
|
||||
const variants = product?.variants.edges ?? [];
|
||||
if (variants.length === 0) return true;
|
||||
|
||||
return variants.some(({ node }) => {
|
||||
if (!node.availableForSale) return false;
|
||||
|
||||
return node.selectedOptions.every((option) => {
|
||||
if (option.name === optionName) return option.value === value;
|
||||
const selected = selectedOptions[option.name];
|
||||
return selected === undefined || selected === option.value;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const handleOptionChange = (optionName: string, value: string) => {
|
||||
const newOptions = { ...selectedOptions, [optionName]: value };
|
||||
setSelectedOptions(newOptions);
|
||||
|
||||
// Find matching variant
|
||||
const matchingVariant = product?.variants.edges.find(({ node }) => {
|
||||
return node.selectedOptions.every(
|
||||
(option) => newOptions[option.name] === option.value
|
||||
);
|
||||
});
|
||||
|
||||
if (matchingVariant) {
|
||||
setSelectedVariant(matchingVariant.node);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddToCart = async () => {
|
||||
if (!selectedVariant || !product) return;
|
||||
|
||||
try {
|
||||
setAddingToCart(true);
|
||||
await addItem(selectedVariant.id, quantity);
|
||||
openCart();
|
||||
} catch (err) {
|
||||
console.error('Failed to add item to cart:', err);
|
||||
} finally {
|
||||
setAddingToCart(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Adds the item, then sends the shopper straight to the Shopify checkout
|
||||
// (where Shop Pay is offered) rather than opening the cart drawer.
|
||||
const handleBuyNow = async () => {
|
||||
if (!selectedVariant || !product) return;
|
||||
|
||||
try {
|
||||
setBuyingNow(true);
|
||||
const updatedCart = await addItem(selectedVariant.id, quantity);
|
||||
const url = updatedCart?.checkoutUrl ?? checkoutUrl;
|
||||
|
||||
if (url) {
|
||||
redirectToCheckout(url);
|
||||
} else {
|
||||
openCart();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to start checkout:', err);
|
||||
} finally {
|
||||
setBuyingNow(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="max-w-screen-2xl mx-auto px-8 py-8">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-5 gap-8 lg:gap-10">
|
||||
{/* Image Gallery Skeleton */}
|
||||
<div className="lg:col-span-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="aspect-square bg-zinc-100 animate-pulse"
|
||||
></div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Product Info Skeleton */}
|
||||
<div className="lg:col-span-2 animate-pulse">
|
||||
<div className="h-8 bg-zinc-100 w-2/3"></div>
|
||||
<div className="h-5 bg-zinc-100 w-24 mt-2"></div>
|
||||
<div className="h-8 bg-zinc-100 w-32 mt-8"></div>
|
||||
<div className="h-10 bg-zinc-100 mt-8"></div>
|
||||
<div className="h-12 bg-zinc-100 mt-8"></div>
|
||||
<div className="h-12 bg-zinc-100 mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !product) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<Empty className="min-h-[400px]">
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>Product Not Found</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{error || 'The requested product could not be found.'}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<Button onClick={() => window.history.back()} variant="outline">
|
||||
Go Back
|
||||
</Button>
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8 py-8">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-5 gap-8 lg:gap-10 items-start">
|
||||
<div className="lg:col-span-3">
|
||||
<ProductDetailGallery
|
||||
images={product.images.edges.map((edge) => edge.node)}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:col-span-2 lg:sticky lg:top-20">
|
||||
<ProductDetailInfo
|
||||
product={product}
|
||||
selectedVariant={selectedVariant}
|
||||
selectedOptions={selectedOptions}
|
||||
quantity={quantity}
|
||||
setQuantity={setQuantity}
|
||||
handleAddToCart={handleAddToCart}
|
||||
handleBuyNow={handleBuyNow}
|
||||
onOptionChange={handleOptionChange}
|
||||
isOptionValueAvailable={isOptionValueAvailable}
|
||||
loading={addingToCart}
|
||||
buyingNow={buyingNow}
|
||||
addToCartLabel={addToCartLabel}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductDetail;
|
||||
@@ -0,0 +1,210 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import Image from '@/components/ui/image';
|
||||
import { RiCloseLine } from '@remixicon/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ProductImage {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
}
|
||||
|
||||
interface ProductDetailGalleryProps {
|
||||
images: ProductImage[];
|
||||
}
|
||||
|
||||
const ProductDetailGallery: React.FC<ProductDetailGalleryProps> = ({
|
||||
images,
|
||||
}) => {
|
||||
const [zoomedIndex, setZoomedIndex] = useState<number | null>(null);
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const scrollerRef = useRef<HTMLDivElement>(null);
|
||||
const isZoomed = zoomedIndex !== null;
|
||||
|
||||
const close = useCallback(() => setZoomedIndex(null), []);
|
||||
|
||||
// The slide whose left edge sits closest to the scroller's left edge is the
|
||||
// one in view. Measuring rects keeps this correct whatever the gap or width.
|
||||
const handleScroll = useCallback(() => {
|
||||
const scroller = scrollerRef.current;
|
||||
if (!scroller) return;
|
||||
|
||||
const scrollerLeft = scroller.getBoundingClientRect().left;
|
||||
let nearest = 0;
|
||||
let smallestOffset = Infinity;
|
||||
|
||||
Array.from(scroller.children).forEach((child, index) => {
|
||||
const offset = Math.abs(child.getBoundingClientRect().left - scrollerLeft);
|
||||
if (offset < smallestOffset) {
|
||||
smallestOffset = offset;
|
||||
nearest = index;
|
||||
}
|
||||
});
|
||||
|
||||
setActiveIndex(nearest);
|
||||
}, []);
|
||||
|
||||
// Touch already scrolls natively; this adds click-and-drag for pointers that
|
||||
// don't (mouse at mobile widths), suspending snap so the drag stays smooth.
|
||||
const drag = useRef<{ startX: number; startScroll: number } | null>(null);
|
||||
|
||||
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.pointerType === 'touch') return;
|
||||
const scroller = scrollerRef.current;
|
||||
if (!scroller) return;
|
||||
|
||||
drag.current = { startX: event.clientX, startScroll: scroller.scrollLeft };
|
||||
scroller.style.scrollSnapType = 'none';
|
||||
};
|
||||
|
||||
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const scroller = scrollerRef.current;
|
||||
if (!drag.current || !scroller) return;
|
||||
|
||||
event.preventDefault();
|
||||
scroller.scrollLeft =
|
||||
drag.current.startScroll - (event.clientX - drag.current.startX);
|
||||
};
|
||||
|
||||
const endDrag = () => {
|
||||
const scroller = scrollerRef.current;
|
||||
if (!drag.current || !scroller) return;
|
||||
|
||||
drag.current = null;
|
||||
// Restoring snap lets the browser settle on the nearest slide.
|
||||
scroller.style.scrollSnapType = '';
|
||||
};
|
||||
|
||||
const scrollToIndex = (index: number) => {
|
||||
const scroller = scrollerRef.current;
|
||||
const slide = scroller?.children[index];
|
||||
if (!scroller || !slide) return;
|
||||
|
||||
const offset =
|
||||
slide.getBoundingClientRect().left - scroller.getBoundingClientRect().left;
|
||||
scroller.scrollTo({ left: scroller.scrollLeft + offset, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
// Close on Escape, and keep the page behind the overlay from scrolling.
|
||||
useEffect(() => {
|
||||
if (!isZoomed) return;
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') close();
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
const previousOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', onKeyDown);
|
||||
document.body.style.overflow = previousOverflow;
|
||||
};
|
||||
}, [isZoomed, close]);
|
||||
|
||||
if (images.length === 0) {
|
||||
return (
|
||||
<div className="aspect-square bg-zinc-50 flex items-center justify-center text-zinc-300">
|
||||
<i className="ri-image-line text-[120px]"></i>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isSingle = images.length === 1;
|
||||
const zoomedImage = zoomedIndex !== null ? images[zoomedIndex] : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Swipeable carousel on mobile, grid from sm up */}
|
||||
<div
|
||||
ref={scrollerRef}
|
||||
onScroll={handleScroll}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={endDrag}
|
||||
onPointerLeave={endDrag}
|
||||
onPointerCancel={endDrag}
|
||||
className="flex snap-x snap-mandatory gap-3 overflow-x-auto no-scrollbar touch-pan-x sm:grid sm:grid-cols-2 sm:touch-auto sm:overflow-visible"
|
||||
>
|
||||
{images.map((image, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => setZoomedIndex(index)}
|
||||
aria-label={`Zoom ${image.altText || 'product image'}`}
|
||||
className={`relative aspect-square w-full shrink-0 snap-center overflow-hidden pointer-events-none sm:pointer-events-auto sm:shrink sm:cursor-zoom-in ${
|
||||
isSingle ? 'sm:col-span-2' : ''
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={image.url}
|
||||
alt={image.altText || 'Product image'}
|
||||
fill
|
||||
sizes="(min-width: 1024px) 30vw, (min-width: 640px) 50vw, 100vw"
|
||||
priority={index === 0}
|
||||
draggable={false}
|
||||
className="object-cover select-none"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Carousel pagination — the grid needs no dots, so mobile only */}
|
||||
{!isSingle && (
|
||||
<div className="flex justify-center gap-2 pt-4 sm:hidden">
|
||||
{images.map((_, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => scrollToIndex(index)}
|
||||
aria-label={`Go to image ${index + 1}`}
|
||||
aria-current={index === activeIndex}
|
||||
className={`h-1.5 rounded-full transition-all ${
|
||||
index === activeIndex
|
||||
? 'w-5 bg-foreground'
|
||||
: 'w-1.5 bg-border hover:bg-foreground/40'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{zoomedImage && (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={zoomedImage.altText || 'Product image'}
|
||||
onClick={close}
|
||||
className="fixed inset-0 z-100 flex items-center justify-center bg-foreground/20 backdrop-blur-md p-6 md:p-10"
|
||||
>
|
||||
<Image
|
||||
src={zoomedImage.url}
|
||||
alt={zoomedImage.altText || 'Product image'}
|
||||
// Shopify gives us the intrinsic size; the square fallback only
|
||||
// reserves space until CSS scales it down to fit the overlay.
|
||||
width={zoomedImage.width || 1600}
|
||||
height={zoomedImage.height || 1600}
|
||||
sizes="100vw"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
// w/h-auto keeps the box at the image's own ratio; without it the
|
||||
// width+height attributes make both axes definite and the element
|
||||
// stretches to the overlay, swallowing backdrop clicks that close it.
|
||||
className="max-h-full max-w-full w-auto h-auto object-contain"
|
||||
/>
|
||||
|
||||
<Button
|
||||
onClick={close}
|
||||
variant="ghost"
|
||||
size="icon-lg"
|
||||
aria-label="Close"
|
||||
className="absolute top-4 right-4 rounded-full bg-background shadow-sm hover:bg-secondary"
|
||||
>
|
||||
<RiCloseLine size={20} />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductDetailGallery;
|
||||
@@ -0,0 +1,282 @@
|
||||
import React from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
import { RiSubtractLine, RiAddLine } from '@remixicon/react';
|
||||
import ShopPayButton from '@/components/shopify/shop-pay-button';
|
||||
import type { ProductOption, ProductOptionValue } from '@/hooks/use-shopify-products';
|
||||
import { isSwatchOptionName, swatchColorForName } from '@/config/swatches';
|
||||
import { isDefaultTitleOption } from '@/services/shopify/catalog';
|
||||
|
||||
interface ProductPrice {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
interface ProductVariant {
|
||||
id: string;
|
||||
title: string;
|
||||
price: ProductPrice;
|
||||
availableForSale: boolean;
|
||||
selectedOptions: Array<{
|
||||
name: string;
|
||||
value: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
descriptionHtml?: string;
|
||||
handle: string;
|
||||
priceRange: {
|
||||
minVariantPrice: ProductPrice;
|
||||
};
|
||||
compareAtPriceRange?: {
|
||||
minVariantPrice: ProductPrice;
|
||||
};
|
||||
options: ProductOption[];
|
||||
}
|
||||
|
||||
export interface ProductFeature {
|
||||
icon: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface ProductDetailInfoProps {
|
||||
product: Product;
|
||||
selectedVariant: ProductVariant | null;
|
||||
selectedOptions: Record<string, string>;
|
||||
quantity: number;
|
||||
setQuantity: (quantity: number) => void;
|
||||
handleAddToCart: () => void;
|
||||
handleBuyNow?: () => void;
|
||||
onOptionChange: (optionName: string, value: string) => void;
|
||||
/** Whether an option value still has an in-stock variant behind it. */
|
||||
isOptionValueAvailable?: (optionName: string, value: string) => boolean;
|
||||
loading?: boolean;
|
||||
buyingNow?: boolean;
|
||||
addToCartLabel?: string;
|
||||
}
|
||||
|
||||
// A swatch comes from the option value's own swatch (colour or image) or the
|
||||
// colour its name implies (see config/swatches) — never a variant photo.
|
||||
const swatchStyle = (
|
||||
value: ProductOptionValue
|
||||
): { background?: string; image?: string } => {
|
||||
if (value.swatch?.color) return { background: value.swatch.color };
|
||||
|
||||
const swatchImage = value.swatch?.image?.previewImage?.url;
|
||||
if (swatchImage) return { image: swatchImage };
|
||||
|
||||
const namedColor = swatchColorForName(value.name);
|
||||
if (namedColor) return { background: namedColor };
|
||||
|
||||
return {};
|
||||
};
|
||||
|
||||
const ProductDetailInfo: React.FC<ProductDetailInfoProps> = ({
|
||||
product,
|
||||
selectedVariant,
|
||||
selectedOptions,
|
||||
quantity,
|
||||
setQuantity,
|
||||
handleAddToCart,
|
||||
handleBuyNow,
|
||||
onOptionChange,
|
||||
isOptionValueAvailable,
|
||||
loading = false,
|
||||
buyingNow = false,
|
||||
addToCartLabel = 'Add to Cart',
|
||||
}) => {
|
||||
const formatPrice = (amount: string) => {
|
||||
return `$${parseFloat(amount).toFixed(2)}`;
|
||||
};
|
||||
|
||||
const price = selectedVariant?.price || product.priceRange.minVariantPrice;
|
||||
const compareAtPrice = product.compareAtPriceRange?.minVariantPrice;
|
||||
const hasDiscount =
|
||||
compareAtPrice &&
|
||||
parseFloat(compareAtPrice.amount) > parseFloat(price.amount);
|
||||
const isAvailable = selectedVariant?.availableForSale ?? false;
|
||||
|
||||
const isSwatchOption = (option: ProductOption) =>
|
||||
isSwatchOptionName(option.name);
|
||||
|
||||
// Some products return Size before Color; show the swatches first either way.
|
||||
// Single-SKU products expose a synthetic `Title: Default Title` option — drop it.
|
||||
const orderedOptions = [...(product.options ?? [])]
|
||||
.filter((option) => !isDefaultTitleOption(option))
|
||||
.sort((a, b) => Number(isSwatchOption(b)) - Number(isSwatchOption(a)));
|
||||
|
||||
// `optionValues` carries the swatch data; fall back to plain `values`.
|
||||
const optionValuesFor = (option: ProductOption): ProductOptionValue[] =>
|
||||
option.optionValues?.length
|
||||
? option.optionValues
|
||||
: option.values.map((value) => ({ id: value, name: value }));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl md:text-3xl font-normal text-foreground">
|
||||
{product.title}
|
||||
</h1>
|
||||
<div className="flex items-baseline gap-x-3 mt-1">
|
||||
<span className="font-mono tabular-nums tracking-tight text-base text-foreground">
|
||||
{formatPrice(price.amount)}
|
||||
</span>
|
||||
{hasDiscount && compareAtPrice && (
|
||||
<span className="font-mono tabular-nums tracking-tight text-sm line-through text-muted-foreground">
|
||||
{formatPrice(compareAtPrice.amount)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Product Options — colour swatches lead, whatever order the API returns */}
|
||||
{orderedOptions.map((option) => {
|
||||
const isSwatch = isSwatchOption(option);
|
||||
const selected = selectedOptions[option.name];
|
||||
|
||||
return (
|
||||
<div key={option.id} className="mt-8">
|
||||
<div className="text-sm text-muted-foreground mb-2">
|
||||
{option.name}
|
||||
{isSwatch && selected && (
|
||||
<span className="text-foreground font-medium">: {selected}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{optionValuesFor(option).map((value) => {
|
||||
const isSelected = selected === value.name;
|
||||
const isSoldOut =
|
||||
isOptionValueAvailable?.(option.name, value.name) === false;
|
||||
|
||||
if (isSwatch) {
|
||||
const { background, image } = swatchStyle(value);
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={value.id}
|
||||
onClick={() => onOptionChange(option.name, value.name)}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={value.name}
|
||||
aria-pressed={isSelected}
|
||||
title={
|
||||
isSoldOut ? `${value.name} — out of stock` : value.name
|
||||
}
|
||||
data-available={!isSoldOut}
|
||||
className={`rounded-full bg-cover bg-center hover:bg-transparent ${
|
||||
isSelected
|
||||
? 'ring-2 ring-foreground ring-offset-2'
|
||||
: 'ring-1 ring-border hover:ring-foreground/40'
|
||||
} ${isSoldOut ? 'option-unavailable text-foreground/60 opacity-60' : ''}`}
|
||||
style={{
|
||||
// With no colour and no image the circle would be fully
|
||||
// transparent, leaving just a hairline ring that
|
||||
// antialiases unevenly and reads as a speckled border.
|
||||
// A neutral fill makes the initial-letter fallback look
|
||||
// deliberate. Set inline so it beats the ghost variant's
|
||||
// hover background.
|
||||
backgroundColor:
|
||||
background ??
|
||||
(image ? undefined : 'var(--color-muted)'),
|
||||
backgroundImage: image ? `url(${image})` : undefined,
|
||||
}}
|
||||
>
|
||||
{!background && !image && (
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
{value.name.at(0)}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={value.id}
|
||||
onClick={() => onOptionChange(option.name, value.name)}
|
||||
variant="outline"
|
||||
aria-pressed={isSelected}
|
||||
title={isSoldOut ? `${value.name} — out of stock` : undefined}
|
||||
className={`min-w-14 px-5 font-normal shadow-none ${
|
||||
isSelected
|
||||
? 'border-foreground text-foreground'
|
||||
: 'text-muted-foreground hover:border-foreground hover:text-foreground'
|
||||
} ${isSoldOut ? 'option-unavailable text-muted-foreground/60' : ''}`}
|
||||
>
|
||||
{value.name}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Quantity + Add to Cart */}
|
||||
<div className="mt-8 flex items-stretch gap-3">
|
||||
<div className="flex items-center rounded-md border border-border h-11">
|
||||
<Button
|
||||
onClick={() => setQuantity(Math.max(1, quantity - 1))}
|
||||
disabled={quantity <= 1}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Decrease quantity"
|
||||
className="h-full rounded-none rounded-l-md"
|
||||
>
|
||||
<RiSubtractLine size={16} />
|
||||
</Button>
|
||||
<span className="w-8 text-center text-sm tabular-nums">
|
||||
{quantity}
|
||||
</span>
|
||||
<Button
|
||||
onClick={() => setQuantity(quantity + 1)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Increase quantity"
|
||||
className="h-full rounded-none rounded-r-md"
|
||||
>
|
||||
<RiAddLine size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleAddToCart}
|
||||
disabled={!isAvailable || loading}
|
||||
className="flex-1 h-11"
|
||||
>
|
||||
{loading && <Loader size={16} />}
|
||||
{isAvailable ? addToCartLabel : 'Out of Stock'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Cart permalink into Shop Pay; falls back to the cart checkout URL. */}
|
||||
<ShopPayButton
|
||||
className="mt-3"
|
||||
variants={
|
||||
selectedVariant ? [{ id: selectedVariant.id, quantity }] : []
|
||||
}
|
||||
disabled={!isAvailable || buyingNow}
|
||||
loading={buyingNow}
|
||||
onFallbackClick={handleBuyNow}
|
||||
/>
|
||||
|
||||
{/* Description */}
|
||||
{(product.descriptionHtml || product.description) && (
|
||||
<div className="mt-10 text-sm leading-6 text-foreground product-description">
|
||||
{product.descriptionHtml ? (
|
||||
<div
|
||||
dangerouslySetInnerHTML={{ __html: product.descriptionHtml }}
|
||||
/>
|
||||
) : (
|
||||
<p>{product.description}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductDetailInfo;
|
||||
@@ -0,0 +1,256 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetBody,
|
||||
AnimatePresence,
|
||||
} from '@/components/ui/sheet';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { RiCloseLine, RiCheckLine } from '@remixicon/react';
|
||||
import { swatchColorForName } from '@/config/swatches';
|
||||
// Shape of a Storefront facet — identical for `search.productFilters` and
|
||||
// `collection.products.filters`, so both pages share this panel.
|
||||
export interface ProductFilterValue {
|
||||
id: string;
|
||||
label: string;
|
||||
count: number;
|
||||
/** JSON string accepted back as a `ProductFilter` input. */
|
||||
input: string;
|
||||
}
|
||||
|
||||
export interface ProductFilterFacet {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'LIST' | 'PRICE_RANGE' | 'BOOLEAN';
|
||||
values: ProductFilterValue[];
|
||||
}
|
||||
|
||||
interface ProductFiltersProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
filters: ProductFilterFacet[];
|
||||
activeFilters: string[];
|
||||
onActiveFiltersChange: (filters: string[]) => void;
|
||||
}
|
||||
|
||||
// Colour facets render as swatches; everything else as a labelled list.
|
||||
const isColorFilter = (filter: ProductFilterFacet) =>
|
||||
/colou?r/i.test(filter.label) || filter.id.toLowerCase().includes('color');
|
||||
|
||||
const ProductFilters: React.FC<ProductFiltersProps> = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
filters,
|
||||
activeFilters,
|
||||
onActiveFiltersChange,
|
||||
}) => {
|
||||
const [priceMin, setPriceMin] = useState('');
|
||||
const [priceMax, setPriceMax] = useState('');
|
||||
|
||||
const listFilters = filters.filter((filter) => filter.type === 'LIST');
|
||||
const priceFilter = filters.find((filter) => filter.type === 'PRICE_RANGE');
|
||||
|
||||
const activeSet = new Set(activeFilters);
|
||||
// Price is rebuilt from the inputs rather than toggled, so track it apart.
|
||||
const activePriceInput = activeFilters.find((input) =>
|
||||
input.includes('"price"')
|
||||
);
|
||||
|
||||
const toggleValue = (value: ProductFilterValue) => {
|
||||
onActiveFiltersChange(
|
||||
activeSet.has(value.input)
|
||||
? activeFilters.filter((input) => input !== value.input)
|
||||
: [...activeFilters, value.input]
|
||||
);
|
||||
};
|
||||
|
||||
const applyPrice = () => {
|
||||
const min = parseFloat(priceMin);
|
||||
const max = parseFloat(priceMax);
|
||||
const withoutPrice = activeFilters.filter(
|
||||
(input) => !input.includes('"price"')
|
||||
);
|
||||
|
||||
if (Number.isNaN(min) && Number.isNaN(max)) {
|
||||
onActiveFiltersChange(withoutPrice);
|
||||
return;
|
||||
}
|
||||
|
||||
const price: { min?: number; max?: number } = {};
|
||||
if (!Number.isNaN(min)) price.min = min;
|
||||
if (!Number.isNaN(max)) price.max = max;
|
||||
|
||||
onActiveFiltersChange([...withoutPrice, JSON.stringify({ price })]);
|
||||
};
|
||||
|
||||
const clearAll = () => {
|
||||
setPriceMin('');
|
||||
setPriceMax('');
|
||||
onActiveFiltersChange([]);
|
||||
};
|
||||
|
||||
// Labels for the chips at the top of the panel.
|
||||
const activeChips = filters
|
||||
.flatMap((filter) => filter.values)
|
||||
.filter((value) => activeSet.has(value.input));
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange} side="left">
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<SheetContent className="w-full max-w-sm" showCloseButton={false}>
|
||||
<SheetHeader className="min-h-0 border-b-0 px-5 py-4">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<SheetTitle className="text-lg font-medium">Filters</SheetTitle>
|
||||
<Button
|
||||
onClick={() => onOpenChange(false)}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Close filters"
|
||||
>
|
||||
<RiCloseLine size={20} />
|
||||
</Button>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
<SheetBody className="px-5">
|
||||
{/* Active selections */}
|
||||
{(activeChips.length > 0 || activePriceInput) && (
|
||||
<div className="mb-6 flex flex-wrap items-center gap-2">
|
||||
{activeChips.map((value) => (
|
||||
<button
|
||||
key={value.id}
|
||||
onClick={() => toggleValue(value)}
|
||||
className="flex items-center gap-x-1 rounded-md bg-secondary px-2 py-1 text-xs text-foreground"
|
||||
>
|
||||
{value.label}
|
||||
<RiCloseLine size={12} />
|
||||
</button>
|
||||
))}
|
||||
<Button
|
||||
onClick={clearAll}
|
||||
variant="link"
|
||||
className="h-auto px-0 text-xs font-normal text-muted-foreground"
|
||||
>
|
||||
Clear all
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{filters.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No filters available for these results.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Price */}
|
||||
{priceFilter && (
|
||||
<div className="mb-8">
|
||||
<h3 className="mb-3 text-base text-foreground">Price</h3>
|
||||
<div className="flex items-center gap-x-2">
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={priceMin}
|
||||
onChange={(event) => setPriceMin(event.target.value)}
|
||||
placeholder="$ From"
|
||||
aria-label="Minimum price"
|
||||
className="h-10 w-full rounded-md bg-secondary px-3 text-sm outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
<span className="text-muted-foreground">–</span>
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={priceMax}
|
||||
onChange={(event) => setPriceMax(event.target.value)}
|
||||
placeholder="$ To"
|
||||
aria-label="Maximum price"
|
||||
className="h-10 w-full rounded-md bg-secondary px-3 text-sm outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
<Button
|
||||
onClick={applyPrice}
|
||||
size="icon"
|
||||
aria-label="Apply price range"
|
||||
className="shrink-0"
|
||||
>
|
||||
<RiCheckLine size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Facets */}
|
||||
{listFilters.map((filter) => (
|
||||
<div key={filter.id} className="mb-8">
|
||||
<h3 className="mb-3 text-base text-foreground">
|
||||
{filter.label}
|
||||
</h3>
|
||||
|
||||
{isColorFilter(filter) ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{filter.values.map((value) => {
|
||||
const isActive = activeSet.has(value.input);
|
||||
const color = swatchColorForName(value.label);
|
||||
|
||||
return (
|
||||
<button
|
||||
key={value.id}
|
||||
onClick={() => toggleValue(value)}
|
||||
title={`${value.label} (${value.count})`}
|
||||
aria-label={value.label}
|
||||
aria-pressed={isActive}
|
||||
className={`h-8 w-8 rounded-full transition-shadow ${
|
||||
isActive
|
||||
? 'ring-2 ring-foreground ring-offset-2'
|
||||
: 'ring-1 ring-border hover:ring-foreground/40'
|
||||
}`}
|
||||
style={{
|
||||
// A colourless swatch would otherwise be a fully
|
||||
// transparent circle behind a hairline ring,
|
||||
// which antialiases into a speckled border.
|
||||
backgroundColor: color ?? 'var(--color-muted)',
|
||||
}}
|
||||
>
|
||||
{!color && (
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
{value.label.at(0)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col">
|
||||
{filter.values.map((value) => {
|
||||
const isActive = activeSet.has(value.input);
|
||||
|
||||
return (
|
||||
<button
|
||||
key={value.id}
|
||||
onClick={() => toggleValue(value)}
|
||||
aria-pressed={isActive}
|
||||
className="flex items-center justify-between py-1.5 text-left text-sm text-foreground hover:text-muted-foreground"
|
||||
>
|
||||
<span>
|
||||
{value.label} ({value.count})
|
||||
</span>
|
||||
{isActive && <RiCheckLine size={16} />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</SheetBody>
|
||||
</SheetContent>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductFilters;
|
||||
@@ -0,0 +1,70 @@
|
||||
import React from 'react';
|
||||
import { useParams } from '@tanstack/react-router';
|
||||
import {
|
||||
useProduct,
|
||||
useProductRecommendations,
|
||||
} from '@/hooks/use-shopify-products';
|
||||
import ProductCard from './product-card';
|
||||
|
||||
interface ProductRecommendationsProps {
|
||||
productId?: string;
|
||||
title?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
const ProductRecommendations: React.FC<ProductRecommendationsProps> = ({
|
||||
productId: productIdProp,
|
||||
title = 'You May Also Like',
|
||||
limit = 4,
|
||||
}) => {
|
||||
const handle = useParams({ strict: false }).handle;
|
||||
const { product } = useProduct(productIdProp ? null : (handle ?? null));
|
||||
const resolvedProductId = productIdProp || product?.id || '';
|
||||
|
||||
const { recommendations, loading, error } = useProductRecommendations(
|
||||
resolvedProductId || null
|
||||
);
|
||||
|
||||
if (!loading && (!recommendations || recommendations.length === 0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="bg-background py-16">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<h2 className="text-2xl md:text-3xl font-normal text-foreground mb-8">
|
||||
{title}
|
||||
</h2>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Recommendations could not be loaded
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-x-8 gap-y-12">
|
||||
{loading
|
||||
? Array.from({ length: limit }).map((_, index) => (
|
||||
<div key={index} className="animate-pulse">
|
||||
<div className="aspect-square bg-zinc-100"></div>
|
||||
<div className="pt-4 space-y-2">
|
||||
<div className="h-4 bg-zinc-200 w-4/5"></div>
|
||||
<div className="h-4 bg-zinc-200 w-1/4"></div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
: recommendations
|
||||
.slice(0, limit)
|
||||
.map((recommendedProduct) => (
|
||||
<ProductCard
|
||||
key={recommendedProduct.id}
|
||||
product={recommendedProduct}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductRecommendations;
|
||||
@@ -0,0 +1,98 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
RiEqualizerLine,
|
||||
RiArrowDownSLine,
|
||||
RiCheckLine,
|
||||
} from '@remixicon/react';
|
||||
|
||||
export interface ToolbarSortOption {
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface ProductToolbarProps {
|
||||
totalCount?: number | null;
|
||||
onOpenFilters: () => void;
|
||||
sortOptions: ToolbarSortOption[];
|
||||
sortIndex: number;
|
||||
onSortChange: (index: number) => void;
|
||||
activeFilterCount?: number;
|
||||
}
|
||||
|
||||
// Filters trigger on the left, item count and sort menu on the right — shared
|
||||
// by the search results and collection pages.
|
||||
const ProductToolbar: React.FC<ProductToolbarProps> = ({
|
||||
totalCount,
|
||||
onOpenFilters,
|
||||
sortOptions,
|
||||
sortIndex,
|
||||
onSortChange,
|
||||
activeFilterCount = 0,
|
||||
}) => {
|
||||
const [sortOpen, setSortOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
onClick={onOpenFilters}
|
||||
variant="ghost"
|
||||
className="gap-x-2 px-0 font-normal hover:bg-transparent"
|
||||
>
|
||||
<RiEqualizerLine size={18} />
|
||||
Filters
|
||||
{activeFilterCount > 0 && (
|
||||
<span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-foreground px-1.5 text-[11px] font-medium text-background">
|
||||
{activeFilterCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-x-4">
|
||||
{typeof totalCount === 'number' && (
|
||||
<span className="text-sm text-muted-foreground tabular-nums">
|
||||
{totalCount} {totalCount === 1 ? 'Item' : 'Items'}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div className="relative">
|
||||
<Button
|
||||
onClick={() => setSortOpen((prev) => !prev)}
|
||||
variant="ghost"
|
||||
aria-expanded={sortOpen}
|
||||
className="gap-x-1 px-0 font-normal hover:bg-transparent"
|
||||
>
|
||||
Sort
|
||||
<RiArrowDownSLine size={16} />
|
||||
</Button>
|
||||
|
||||
{sortOpen && (
|
||||
<>
|
||||
{/* Click-away layer sits under the menu, above the page. */}
|
||||
<div
|
||||
className="fixed inset-0 z-40"
|
||||
onClick={() => setSortOpen(false)}
|
||||
/>
|
||||
<div className="absolute right-0 top-full z-50 mt-1 w-56 rounded-md border border-border bg-background py-1 shadow-md">
|
||||
{sortOptions.map((option, index) => (
|
||||
<button
|
||||
key={option.label}
|
||||
onClick={() => {
|
||||
onSortChange(index);
|
||||
setSortOpen(false);
|
||||
}}
|
||||
className="flex w-full items-center justify-between px-4 py-2 text-left text-sm text-foreground hover:bg-accent"
|
||||
>
|
||||
{option.label}
|
||||
{index === sortIndex && <RiCheckLine size={16} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductToolbar;
|
||||
@@ -0,0 +1,140 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import ProductCard from './product-card';
|
||||
import { productsInfiniteQueryOptions } from '@/hooks/use-shopify-products';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
|
||||
interface ProductsProps {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
limit?: number;
|
||||
showLoadMore?: boolean;
|
||||
}
|
||||
|
||||
const Products: React.FC<ProductsProps> = ({
|
||||
title = 'Shopify Hydrogen Storefront',
|
||||
subtitle = 'A Shopify storefront built with Vite, TanStack and Hydrogen.',
|
||||
limit = 12,
|
||||
showLoadMore = true,
|
||||
}) => {
|
||||
const {
|
||||
data,
|
||||
isPending: loading,
|
||||
error: queryError,
|
||||
refetch,
|
||||
fetchNextPage,
|
||||
hasNextPage: hasMoreProducts,
|
||||
isFetchingNextPage: loadingMore,
|
||||
} = useInfiniteQuery(productsInfiniteQueryOptions({ first: limit }));
|
||||
|
||||
const error = queryError
|
||||
? queryError.message || 'Failed to load products'
|
||||
: null;
|
||||
|
||||
// Pages can overlap if the catalogue shifts between requests, so de-dupe.
|
||||
const products = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
return (data?.pages ?? [])
|
||||
.flatMap((page) => page.products)
|
||||
.filter((product) => !seen.has(product.id) && seen.add(product.id));
|
||||
}, [data]);
|
||||
|
||||
const handleLoadMore = () => {
|
||||
if (!loadingMore && hasMoreProducts) {
|
||||
fetchNextPage();
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="py-20">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<h2 className="text-center text-2xl md:text-3xl font-normal max-w-3xl mx-auto text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-center text-sm font-normal max-w-xl mx-auto text-muted-foreground mt-2.5 mb-16">
|
||||
{subtitle}
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
|
||||
{Array.from({ length: 8 }).map((_, index) => (
|
||||
<div key={index} className="animate-pulse">
|
||||
<div className="aspect-square bg-zinc-100"></div>
|
||||
<div className="pt-4 space-y-2">
|
||||
<div className="h-4 bg-zinc-200 w-4/5"></div>
|
||||
<div className="h-4 bg-zinc-200 w-1/4"></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || products.length === 0) {
|
||||
return (
|
||||
<div className="py-20 bg-background">
|
||||
<div className="max-w-screen-2xl mx-auto px-8 text-center">
|
||||
<h2 className="text-2xl md:text-3xl font-normal max-w-3xl mx-auto text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-sm font-normal max-w-xl mx-auto text-muted-foreground mt-2.5 mb-12">
|
||||
{subtitle}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
{error ||
|
||||
'Our curated collection is being prepared. Please check back shortly.'}
|
||||
</p>
|
||||
{error && (
|
||||
<Button
|
||||
onClick={() => refetch()}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Try again
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="py-20">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<h2 className="text-center text-2xl md:text-3xl font-normal max-w-3xl mx-auto text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
<p className="text-center text-sm font-normal max-w-xl mx-auto text-muted-foreground mt-2.5 mb-16">
|
||||
{subtitle}
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-x-8 gap-y-16 mb-20">
|
||||
{products.map((product) => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{showLoadMore && hasMoreProducts && (
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleLoadMore}
|
||||
disabled={loadingMore}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{loadingMore && <Loader size={16} />}
|
||||
{loadingMore ? 'Loading' : 'Load more'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Products;
|
||||
@@ -0,0 +1,190 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import Image from '@/components/ui/image';
|
||||
import {
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
} from '@/components/ui/command';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
import { RiSearchLine, RiImageLine, RiCloseLine } from '@remixicon/react';
|
||||
import { searchSuggestionsQueryOptions } from '@/hooks/use-shopify-search';
|
||||
|
||||
const DEBOUNCE_MS = 250;
|
||||
const SUGGESTION_COUNT = 3;
|
||||
|
||||
const formatPrice = (amount: string) => `$${parseFloat(amount).toFixed(2)}`;
|
||||
|
||||
const SearchDialog: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [term, setTerm] = useState('');
|
||||
// The term the suggestions query actually runs with, trailing the input.
|
||||
const [debouncedTerm, setDebouncedTerm] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedTerm(term.trim()), DEBOUNCE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [term]);
|
||||
|
||||
// Query keys are per-term, so a slow early response can never overwrite a
|
||||
// newer one; the previous results stay up while the next term loads.
|
||||
const { data, isFetching } = useQuery({
|
||||
...searchSuggestionsQueryOptions(debouncedTerm, SUGGESTION_COUNT),
|
||||
enabled: Boolean(debouncedTerm),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
|
||||
const hasQuery = Boolean(term.trim());
|
||||
const results = hasQuery && debouncedTerm ? (data?.products ?? []) : [];
|
||||
const searching = hasQuery && (term.trim() !== debouncedTerm || isFetching);
|
||||
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
setTerm('');
|
||||
setDebouncedTerm('');
|
||||
};
|
||||
|
||||
const goToSearchPage = () => {
|
||||
const query = term.trim();
|
||||
close();
|
||||
navigate({ to: '/search', search: query ? { q: query } : {} });
|
||||
};
|
||||
|
||||
const goToProduct = (handle: string) => {
|
||||
close();
|
||||
navigate({ to: '/products/$handle', params: { handle } });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => setOpen(true)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Search"
|
||||
className="rounded-full"
|
||||
>
|
||||
<RiSearchLine className="size-5" />
|
||||
</Button>
|
||||
|
||||
<CommandDialog
|
||||
open={open}
|
||||
onOpenChange={(next) => !next && close()}
|
||||
title="Search"
|
||||
description="Search products"
|
||||
showCloseButton={false}
|
||||
className="top-24 max-w-xl translate-y-0"
|
||||
// Results come from the Storefront API, so cmdk must not re-filter them.
|
||||
shouldFilter={false}
|
||||
>
|
||||
<div className="relative">
|
||||
<CommandInput
|
||||
value={term}
|
||||
onValueChange={setTerm}
|
||||
placeholder="Search products"
|
||||
className="pr-28"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') goToSearchPage();
|
||||
}}
|
||||
/>
|
||||
<div className="absolute right-2 top-0 flex h-12 items-center gap-1">
|
||||
{hasQuery && (
|
||||
<Button
|
||||
onClick={() => setTerm('')}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={close}
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Close search"
|
||||
>
|
||||
<RiCloseLine className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasQuery && (
|
||||
<>
|
||||
<div className="px-3 pt-3">
|
||||
<button
|
||||
onClick={goToSearchPage}
|
||||
className="rounded-full border border-border px-3 py-1 text-sm text-foreground transition-colors hover:border-foreground"
|
||||
>
|
||||
{term.trim()}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<CommandList className="max-h-80">
|
||||
{searching && results.length === 0 ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<Loader size={20} />
|
||||
</div>
|
||||
) : results.length === 0 ? (
|
||||
<CommandEmpty>No products found.</CommandEmpty>
|
||||
) : (
|
||||
<CommandGroup heading="Products">
|
||||
{results.map((product) => (
|
||||
<CommandItem
|
||||
key={product.id}
|
||||
value={product.handle}
|
||||
onSelect={() => goToProduct(product.handle)}
|
||||
className="gap-3 py-2"
|
||||
>
|
||||
<div className="h-14 w-14 shrink-0 overflow-hidden bg-zinc-100">
|
||||
{product.featuredImage ? (
|
||||
<Image
|
||||
src={product.featuredImage.url}
|
||||
alt={product.featuredImage.altText || product.title}
|
||||
width={56}
|
||||
height={56}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-zinc-400">
|
||||
<RiImageLine className="size-4" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-medium text-foreground">
|
||||
{product.title}
|
||||
</div>
|
||||
<div className="font-mono text-sm tabular-nums tracking-tight text-foreground">
|
||||
{formatPrice(
|
||||
product.priceRange.minVariantPrice.amount
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
</CommandList>
|
||||
|
||||
{results.length > 0 && (
|
||||
<div className="flex justify-center px-4 pb-5 pt-2">
|
||||
<Button onClick={goToSearchPage} className="px-8">
|
||||
View All
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CommandDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SearchDialog;
|
||||
@@ -0,0 +1,157 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import ProductCard from './product-card';
|
||||
import ProductFilters from './product-filters';
|
||||
import ProductToolbar from './product-toolbar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
import {
|
||||
searchInfiniteQueryOptions,
|
||||
type SearchFilter,
|
||||
type SearchSortKey,
|
||||
} from '@/hooks/use-shopify-search';
|
||||
|
||||
const PAGE_SIZE = 24;
|
||||
|
||||
interface SortOption {
|
||||
label: string;
|
||||
sortKey: SearchSortKey;
|
||||
reverse: boolean;
|
||||
}
|
||||
|
||||
const SORT_OPTIONS: SortOption[] = [
|
||||
{ label: 'Best Matches', sortKey: 'RELEVANCE', reverse: false },
|
||||
{ label: 'Price: Low to High', sortKey: 'PRICE', reverse: false },
|
||||
{ label: 'Price: High to Low', sortKey: 'PRICE', reverse: true },
|
||||
];
|
||||
|
||||
interface SearchResultsProps {
|
||||
/** The `q` search param; empty shows the whole catalogue. */
|
||||
query: string;
|
||||
}
|
||||
|
||||
const SearchResults: React.FC<SearchResultsProps> = ({ query }) => {
|
||||
const [filters, setFilters] = useState<SearchFilter[]>([]);
|
||||
const [sortIndex, setSortIndex] = useState(0);
|
||||
const [filtersOpen, setFiltersOpen] = useState(false);
|
||||
const [activeFilters, setActiveFilters] = useState<string[]>([]);
|
||||
|
||||
const sort = SORT_OPTIONS[sortIndex];
|
||||
|
||||
const {
|
||||
data,
|
||||
isPending: loading,
|
||||
error: queryError,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage: loadingMore,
|
||||
} = useInfiniteQuery(
|
||||
searchInfiniteQueryOptions({
|
||||
// An empty term still returns the catalogue, which is what an
|
||||
// unqualified /search visit should show.
|
||||
query,
|
||||
first: PAGE_SIZE,
|
||||
sortKey: sort.sortKey,
|
||||
reverse: sort.reverse,
|
||||
filterInputs: activeFilters,
|
||||
})
|
||||
);
|
||||
|
||||
const firstPage = data?.pages[0];
|
||||
const totalCount = firstPage?.totalCount ?? 0;
|
||||
const error = queryError ? queryError.message || 'Search failed' : null;
|
||||
|
||||
const products = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
return (data?.pages ?? [])
|
||||
.flatMap((page) => page.products)
|
||||
.filter((product) => !seen.has(product.id) && seen.add(product.id));
|
||||
}, [data]);
|
||||
|
||||
// Facet counts change with the result set, but keep the panel stable while
|
||||
// filters are applied so options don't vanish mid-selection.
|
||||
useEffect(() => {
|
||||
if (firstPage && activeFilters.length === 0) setFilters(firstPage.filters);
|
||||
}, [firstPage, activeFilters.length]);
|
||||
|
||||
const handleLoadMore = () => {
|
||||
if (!loadingMore && hasNextPage) fetchNextPage();
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="bg-background py-10">
|
||||
<div className="max-w-screen-2xl mx-auto px-8">
|
||||
<h1 className="text-3xl md:text-4xl font-normal text-foreground">
|
||||
Search
|
||||
</h1>
|
||||
|
||||
<div className="mt-6">
|
||||
<ProductToolbar
|
||||
totalCount={totalCount}
|
||||
onOpenFilters={() => setFiltersOpen(true)}
|
||||
sortOptions={SORT_OPTIONS}
|
||||
sortIndex={sortIndex}
|
||||
onSortChange={setSortIndex}
|
||||
activeFilterCount={activeFilters.length}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div className="mt-8">
|
||||
{loading ? (
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 gap-x-8 gap-y-12">
|
||||
{Array.from({ length: 10 }).map((_, index) => (
|
||||
<div key={index} className="animate-pulse">
|
||||
<div className="aspect-square bg-zinc-100"></div>
|
||||
<div className="pt-4 space-y-2">
|
||||
<div className="h-4 w-4/5 bg-zinc-200"></div>
|
||||
<div className="h-4 w-1/4 bg-zinc-200"></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : error ? (
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
) : products.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No products matched{query ? ` “${query}”` : ' your filters'}.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 gap-x-8 gap-y-12">
|
||||
{products.map((product) => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{hasNextPage && (
|
||||
<div className="mt-16 flex justify-center">
|
||||
<Button
|
||||
onClick={handleLoadMore}
|
||||
disabled={loadingMore}
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="font-normal text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{loadingMore && <Loader size={16} />}
|
||||
{loadingMore ? 'Loading' : 'Load more'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProductFilters
|
||||
open={filtersOpen}
|
||||
onOpenChange={setFiltersOpen}
|
||||
filters={filters}
|
||||
activeFilters={activeFilters}
|
||||
onActiveFiltersChange={setActiveFilters}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default SearchResults;
|
||||
@@ -0,0 +1,151 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { RiArrowDownSLine } from '@remixicon/react';
|
||||
import { useCollectionsOnDemand } from '@/hooks/use-shopify-collections';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ShopMenuProps {
|
||||
label?: string;
|
||||
/** Renders inline inside the mobile menu instead of as a floating panel. */
|
||||
mobile?: boolean;
|
||||
/** Fires after a collection is picked, so the mobile menu can close itself. */
|
||||
onNavigate?: () => void;
|
||||
}
|
||||
|
||||
const ShopMenu: React.FC<ShopMenuProps> = ({
|
||||
label = 'Shop',
|
||||
mobile = false,
|
||||
onNavigate,
|
||||
}) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { collections, loading, error, load } = useCollectionsOnDemand();
|
||||
|
||||
// The collection list is only worth fetching once someone opens the menu.
|
||||
const toggle = () => {
|
||||
const next = !open;
|
||||
setOpen(next);
|
||||
if (next) load();
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
onNavigate?.();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') setOpen(false);
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [open]);
|
||||
|
||||
const itemClasses = cn(
|
||||
'block text-sm text-foreground hover:bg-accent transition-colors',
|
||||
mobile ? 'px-3 py-2' : 'px-4 py-2'
|
||||
);
|
||||
|
||||
const body = (
|
||||
<>
|
||||
{loading &&
|
||||
Array.from({ length: 5 }).map((_, index) => (
|
||||
<div key={index} className={cn(itemClasses, 'py-2.5')}>
|
||||
<div className="h-3 w-2/3 animate-pulse bg-muted" />
|
||||
</div>
|
||||
))}
|
||||
|
||||
{error && (
|
||||
<div className={cn(itemClasses, 'hover:bg-transparent')}>
|
||||
<p className="text-muted-foreground">{error}</p>
|
||||
<button
|
||||
onClick={load}
|
||||
className="mt-1 underline underline-offset-2 hover:text-muted-foreground"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && collections.length === 0 && (
|
||||
<p className={cn(itemClasses, 'text-muted-foreground hover:bg-transparent')}>
|
||||
No collections yet.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{collections.map((collection) => (
|
||||
<Link
|
||||
key={collection.id}
|
||||
to="/collections/$handle"
|
||||
params={{ handle: collection.handle }}
|
||||
onClick={close}
|
||||
className={itemClasses}
|
||||
>
|
||||
{collection.title}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{collections.length > 0 && (
|
||||
<>
|
||||
<div className="my-1 h-px bg-border" />
|
||||
<Link
|
||||
to="/collections"
|
||||
onClick={close}
|
||||
className={cn(itemClasses, 'text-muted-foreground')}
|
||||
>
|
||||
View all collections
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const trigger = (
|
||||
<button
|
||||
onClick={toggle}
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
'flex items-center gap-x-1 text-foreground hover:text-muted-foreground transition-colors',
|
||||
mobile && 'w-full justify-between'
|
||||
)}
|
||||
>
|
||||
<span>{label}</span>
|
||||
<RiArrowDownSLine
|
||||
className={cn('size-4 transition-transform', open && 'rotate-180')}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
|
||||
if (mobile) {
|
||||
return (
|
||||
<div>
|
||||
{trigger}
|
||||
{open && (
|
||||
<div className="mt-2 flex flex-col border-l border-border pl-1">
|
||||
{body}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{trigger}
|
||||
|
||||
{open && (
|
||||
<>
|
||||
{/* Catches the click that dismisses the panel. */}
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
<div className="absolute left-0 top-full z-50 mt-2 max-h-[70vh] w-64 overflow-y-auto rounded-md border border-border bg-background py-1 shadow-md">
|
||||
{body}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ShopMenu;
|
||||
@@ -0,0 +1,98 @@
|
||||
import React from 'react';
|
||||
import { SHOPIFY_STORE_DOMAIN } from '@/services/shopify/config';
|
||||
import ShopPayLogo from '@/components/shopify/shop-pay-logo';
|
||||
import { Loader } from '@/components/ui/loader';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export interface ShopPayVariant {
|
||||
id: string;
|
||||
quantity?: number;
|
||||
}
|
||||
|
||||
interface ShopPayButtonProps {
|
||||
variants: ShopPayVariant[];
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
className?: string;
|
||||
/** Used when no permalink can be built (missing domain or unusable IDs). */
|
||||
onFallbackClick?: () => void;
|
||||
}
|
||||
|
||||
// Cart permalinks need the bare numeric ID; the Storefront API returns GIDs.
|
||||
function toNumericVariantId(id: string): string | null {
|
||||
const trimmed = id.trim();
|
||||
const gid = trimmed.match(/^gid:\/\/shopify\/ProductVariant\/(\d+)/);
|
||||
if (gid) return gid[1];
|
||||
return /^\d+$/.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function toStoreUrl(domain?: string): string | null {
|
||||
if (!domain) return null;
|
||||
try {
|
||||
return new URL(domain.startsWith('http') ? domain : `https://${domain}`)
|
||||
.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// https://{shop}/cart/{variantId}:{qty},{variantId}:{qty}?payment=shop_pay
|
||||
// Loads the cart and drops the buyer straight into the Shop Pay checkout.
|
||||
export function buildShopPayUrl(variants: ShopPayVariant[]): string | null {
|
||||
const storeUrl = toStoreUrl(SHOPIFY_STORE_DOMAIN);
|
||||
if (!storeUrl || variants.length === 0) return null;
|
||||
|
||||
const lines: string[] = [];
|
||||
for (const { id, quantity = 1 } of variants) {
|
||||
const numericId = toNumericVariantId(id);
|
||||
if (!numericId || !Number.isInteger(quantity) || quantity < 1) return null;
|
||||
lines.push(`${numericId}:${quantity}`);
|
||||
}
|
||||
|
||||
return `${storeUrl}/cart/${lines.join(',')}?payment=shop_pay`;
|
||||
}
|
||||
|
||||
const BUTTON_CLASSES =
|
||||
'flex h-11 w-full cursor-pointer items-center justify-center rounded-md bg-shop px-4 text-white transition-colors hover:bg-shop/85 disabled:cursor-not-allowed disabled:opacity-50';
|
||||
|
||||
const ShopPayButton: React.FC<ShopPayButtonProps> = ({
|
||||
variants,
|
||||
disabled = false,
|
||||
loading = false,
|
||||
className = '',
|
||||
onFallbackClick,
|
||||
}) => {
|
||||
const shopPayUrl = buildShopPayUrl(variants);
|
||||
const contents = (
|
||||
<>
|
||||
<span className="sr-only">Buy with</span>
|
||||
{loading ? <Loader size={16} /> : <ShopPayLogo />}
|
||||
</>
|
||||
);
|
||||
|
||||
// An anchor keeps the checkout URL visible, openable in a new tab, and
|
||||
// navigable without JS; the button only stands in when there's no URL.
|
||||
if (shopPayUrl && !disabled) {
|
||||
return (
|
||||
<a
|
||||
href={shopPayUrl}
|
||||
className={`${BUTTON_CLASSES} ${className}`.trim()}
|
||||
>
|
||||
{contents}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onFallbackClick}
|
||||
disabled={disabled || (!shopPayUrl && !onFallbackClick)}
|
||||
className={`${BUTTON_CLASSES} ${className}`.trim()}
|
||||
>
|
||||
{contents}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export default ShopPayButton;
|
||||
@@ -0,0 +1,50 @@
|
||||
import React from 'react';
|
||||
|
||||
// "Buy with shop" lockup — the wordmark and the Shop mark are both in the path
|
||||
// data, so the button needs no additional text beyond a screen-reader label.
|
||||
const ShopPayLogo: React.FC<{ className?: string }> = ({
|
||||
className = 'h-auto w-[98px]',
|
||||
}) => (
|
||||
<svg
|
||||
fill="none"
|
||||
viewBox="0 0 10885 2079"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden="true"
|
||||
className={className}
|
||||
>
|
||||
<path
|
||||
d="M158.355 1621V448.811H637.207C856.681 448.811 994.683 565.198 994.683 748.093C994.683 874.457 923.188 967.567 800.15 1004.15V1010.8C943.14 1039.06 1024.61 1145.47 1024.61 1296.78C1024.61 1494.64 884.946 1621 665.473 1621H158.355ZM630.556 1459.72C745.281 1459.72 813.451 1391.55 813.451 1278.49C813.451 1162.1 743.619 1093.93 630.556 1093.93H362.865V1459.72H630.556ZM605.616 939.301C713.69 939.301 781.86 874.457 781.86 774.696C781.86 671.61 713.69 610.091 605.616 610.091H362.865V939.301H605.616ZM1486.02 1645.94C1328.06 1645.94 1200.04 1547.84 1200.04 1323.38V764.72H1394.57V1290.13C1394.57 1411.5 1456.09 1479.67 1557.51 1479.67C1675.56 1479.67 1742.07 1394.88 1742.07 1268.51V764.72H1938.27V1621H1750.38V1501.29H1742.07C1693.85 1599.39 1604.07 1645.94 1486.02 1645.94ZM2229.79 1895.34L2392.74 1537.87L2053.55 764.72H2271.36L2430.98 1167.09C2455.92 1233.6 2474.21 1288.46 2492.5 1356.63H2499.15C2515.78 1290.13 2534.06 1231.93 2557.34 1167.09L2716.96 764.72H2934.77L2445.94 1895.34H2229.79ZM3535.97 1621L3266.62 764.72H3472.79L3585.85 1185.38C3607.47 1266.85 3624.09 1345 3639.06 1429.79H3645.71C3662.34 1343.33 3677.3 1271.84 3702.24 1185.38L3820.29 764.72H4021.47L4139.53 1185.38C4164.47 1273.5 4181.09 1348.32 4196.06 1429.79H4204.37C4217.67 1346.66 4234.3 1270.17 4255.91 1185.38L4368.97 764.72H4576.81L4305.79 1621H4104.61L3984.9 1195.35C3958.29 1102.24 3941.67 1029.09 3925.04 942.627H3918.39C3900.1 1030.75 3883.47 1103.91 3856.87 1195.35L3738.82 1621H3535.97ZM4696.08 1621V764.72H4890.61V1621H4696.08ZM4794.18 633.368C4724.35 633.368 4672.8 578.5 4672.8 510.33C4672.8 442.16 4726.01 388.954 4794.18 388.954C4864.01 388.954 4917.22 442.16 4917.22 510.33C4917.22 580.162 4864.01 633.368 4794.18 633.368ZM5389.5 1637.63C5249.83 1637.63 5163.37 1572.78 5163.37 1426.47V926H5025.37V776.359H5111.83C5160.05 776.359 5176.67 758.069 5176.67 709.851V560.21H5359.57V764.72H5520.85V926H5359.57V1363.28C5359.57 1433.12 5384.51 1461.38 5441.04 1461.38C5465.98 1461.38 5489.26 1458.06 5520.85 1451.41V1616.01C5474.29 1630.98 5437.71 1637.63 5389.5 1637.63ZM5694.66 1621V418.883H5890.86V877.782H5897.51C5947.39 784.672 6040.5 739.78 6153.56 739.78C6316.51 739.78 6444.53 837.878 6444.53 1062.34V1621H6248.34V1095.59C6248.34 974.218 6186.82 906.048 6080.4 906.048C5959.03 906.048 5889.2 990.844 5889.2 1117.21V1621H5694.66Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<g clipPath="url(#shop-pay-logo-clip)">
|
||||
<path
|
||||
d="M7406 1027.33C7247.3 992.071 7176.6 978.274 7176.6 915.639C7176.6 856.727 7224.44 827.38 7320.13 827.38C7404.29 827.38 7465.8 865.049 7511.08 938.853C7514.5 944.547 7521.55 946.518 7527.32 943.452L7705.88 851.032C7712.29 847.747 7714.64 839.425 7711 833.074C7636.89 701.453 7499.98 629.4 7319.71 629.4C7082.83 629.4 6935.67 748.976 6935.67 939.072C6935.67 1140.99 7114.87 1192.02 7273.78 1227.28C7432.7 1262.54 7503.61 1276.34 7503.61 1338.97C7503.61 1401.61 7451.92 1431.17 7348.75 1431.17C7253.49 1431.17 7182.79 1386.5 7140.08 1299.77C7136.87 1293.42 7129.4 1290.79 7123.2 1294.08L6945.07 1384.53C6938.87 1387.81 6936.31 1395.48 6939.51 1402.05C7010.21 1547.68 7155.24 1629.59 7348.97 1629.59C7595.67 1629.59 7744.75 1511.99 7744.75 1315.98C7744.75 1119.97 7564.69 1063.03 7406 1027.77V1027.33Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M8362.88 629.4C8261.64 629.4 8172.15 666.193 8107.86 731.675C8103.8 735.617 8097.18 732.77 8097.18 727.076V308.997C8097.18 301.77 8091.62 296.076 8084.57 296.076H7861.16C7854.11 296.076 7848.56 301.77 7848.56 308.997V1606.6C7848.56 1613.82 7854.11 1619.52 7861.16 1619.52H8084.57C8091.62 1619.52 8097.18 1613.82 8097.18 1606.6V1037.41C8097.18 927.465 8179.41 843.148 8290.26 843.148C8401.12 843.148 8481.43 925.713 8481.43 1037.41V1606.6C8481.43 1613.82 8486.98 1619.52 8494.03 1619.52H8717.44C8724.49 1619.52 8730.05 1613.82 8730.05 1606.6V1037.41C8730.05 798.253 8577.11 629.4 8362.88 629.4Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M9183.28 592.17C9061.97 592.17 8948.34 630.276 8866.74 685.246C8861.19 688.969 8859.27 696.634 8862.69 702.548L8961.15 874.904C8964.78 881.036 8972.47 883.226 8978.45 879.503C9040.39 841.177 9111.3 821.248 9183.71 821.686C9378.72 821.686 9522.04 962.725 9522.04 1149.1C9522.04 1307.88 9407.34 1425.48 9261.89 1425.48C9143.34 1425.48 9061.11 1354.74 9061.11 1254.88C9061.11 1197.72 9084.82 1150.85 9146.55 1117.78C9152.95 1114.28 9155.3 1106.17 9151.46 1099.82L9058.55 938.634C9055.56 933.378 9049.15 930.969 9043.38 933.159C8918.86 980.464 8831.5 1094.35 8831.5 1247.21C8831.5 1478.48 9011.13 1651.05 9261.67 1651.05C9554.29 1651.05 9764.68 1443.22 9764.68 1145.16C9764.68 825.628 9519.9 592.17 9183.28 592.17Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M10418.3 627.429C10305.3 627.429 10204.2 670.354 10130.6 745.692C10126.5 749.853 10119.9 746.787 10119.9 741.092V650.425C10119.9 643.198 10114.3 637.504 10107.3 637.504H9889.63C9882.58 637.504 9877.03 643.198 9877.03 650.425V1946.05C9877.03 1953.28 9882.58 1958.97 9889.63 1958.97H10113C10120.1 1958.97 10125.6 1953.28 10125.6 1946.05V1521.19C10125.6 1515.49 10132.3 1512.64 10136.3 1516.37C10209.8 1586.45 10307 1627.4 10418.3 1627.4C10680.3 1627.4 10884.7 1409.93 10884.7 1127.42C10884.7 844.9 10680.1 627.429 10418.3 627.429ZM10376 1407.96C10226.9 1407.96 10113.9 1286.41 10113.9 1125.66C10113.9 964.915 10226.7 843.367 10376 843.367C10525.3 843.367 10637.8 962.944 10637.8 1125.66C10637.8 1288.38 10526.8 1407.96 10375.8 1407.96H10376Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="shop-pay-logo-clip">
|
||||
<rect
|
||||
width="3948.86"
|
||||
height="1662.68"
|
||||
fill="white"
|
||||
transform="translate(6935.67 296.076)"
|
||||
/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default ShopPayLogo;
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,193 @@
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
|
||||
"transition-none animate-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
// Forwarded to the inner Command so callers can drive filtering themselves
|
||||
// (e.g. results already filtered server-side).
|
||||
shouldFilter,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
shouldFilter?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn(
|
||||
"overflow-hidden p-0",
|
||||
// No fade/zoom on the command palette — it should appear instantly.
|
||||
"transition-none animate-none duration-0",
|
||||
"data-[state=closed]:animate-none data-[state=open]:animate-none",
|
||||
className
|
||||
)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<Command shouldFilter={shouldFilter} className="**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="command-input-wrapper"
|
||||
className="flex h-9 items-center gap-2 border-b px-3"
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
data-slot="command-input"
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
return (
|
||||
<CommandPrimitive.List
|
||||
data-slot="command-list"
|
||||
className={cn(
|
||||
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandEmpty({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return (
|
||||
<CommandPrimitive.Empty
|
||||
data-slot="command-empty"
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<CommandPrimitive.Group
|
||||
data-slot="command-group"
|
||||
className={cn(
|
||||
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("-mx-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import * as React from "react"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Empty({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty"
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-header"
|
||||
className={cn(
|
||||
"flex max-w-sm flex-col items-center gap-2 text-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const emptyMediaVariants = cva(
|
||||
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function EmptyMedia({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-icon"
|
||||
data-variant={variant}
|
||||
className={cn(emptyMediaVariants({ variant, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-title"
|
||||
className={cn("text-lg font-medium tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-description"
|
||||
className={cn(
|
||||
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-content"
|
||||
className={cn(
|
||||
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Empty,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
EmptyDescription,
|
||||
EmptyContent,
|
||||
EmptyMedia,
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// A small stand-in for `next/image`, covering the props this storefront uses.
|
||||
// Shopify's CDN resizes on request via `?width=`, so CDN images get a real
|
||||
// `srcset` and the browser picks a size from `sizes` — the same job Next's
|
||||
// image optimiser did, without a server in the loop.
|
||||
|
||||
const WIDTHS = [160, 320, 480, 640, 960, 1280, 1600, 2048];
|
||||
|
||||
const isShopifyCdn = (src: string) => {
|
||||
try {
|
||||
const { hostname } = new URL(src);
|
||||
return hostname === 'cdn.shopify.com' || hostname.endsWith('.shopify.com');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const withWidth = (src: string, width: number) => {
|
||||
const url = new URL(src);
|
||||
url.searchParams.set('width', String(width));
|
||||
return url.toString();
|
||||
};
|
||||
|
||||
type ImageProps = Omit<
|
||||
React.ImgHTMLAttributes<HTMLImageElement>,
|
||||
'src' | 'width' | 'height'
|
||||
> & {
|
||||
src: string;
|
||||
alt: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
/** Absolutely fills the nearest positioned ancestor, like next/image. */
|
||||
fill?: boolean;
|
||||
/** Above-the-fold image: load eagerly at high priority. */
|
||||
priority?: boolean;
|
||||
};
|
||||
|
||||
export const Image: React.FC<ImageProps> = ({
|
||||
src,
|
||||
alt,
|
||||
width,
|
||||
height,
|
||||
fill = false,
|
||||
priority = false,
|
||||
sizes,
|
||||
className,
|
||||
...props
|
||||
}) => {
|
||||
const resizable = isShopifyCdn(src);
|
||||
// With `sizes` (or `fill`) the browser picks from a width ladder; a fixed
|
||||
// thumbnail only needs its own size at 1x and 2x.
|
||||
const fixedWidth = !fill && !sizes ? width : undefined;
|
||||
|
||||
const srcSet = !resizable
|
||||
? undefined
|
||||
: fixedWidth
|
||||
? `${withWidth(src, fixedWidth)} 1x, ${withWidth(src, fixedWidth * 2)} 2x`
|
||||
: WIDTHS.map((w) => `${withWidth(src, w)} ${w}w`).join(', ');
|
||||
|
||||
return (
|
||||
<img
|
||||
{...props}
|
||||
src={resizable ? withWidth(src, fixedWidth ?? 1280) : src}
|
||||
srcSet={srcSet}
|
||||
sizes={fill ? (sizes ?? '100vw') : sizes}
|
||||
alt={alt}
|
||||
width={fill ? undefined : width}
|
||||
height={fill ? undefined : height}
|
||||
loading={priority ? 'eager' : 'lazy'}
|
||||
fetchPriority={priority ? 'high' : undefined}
|
||||
decoding="async"
|
||||
className={cn(fill && 'absolute inset-0 h-full w-full', className)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default Image;
|
||||
@@ -0,0 +1,96 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { HTMLAttributes } from "react";
|
||||
|
||||
interface LoaderIconProps {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
const LoaderIcon = ({ size = 16 }: LoaderIconProps) => (
|
||||
<svg
|
||||
height={size}
|
||||
strokeLinejoin="round"
|
||||
style={{ color: "currentcolor" }}
|
||||
viewBox="0 0 16 16"
|
||||
width={size}
|
||||
>
|
||||
<title>Loader</title>
|
||||
<g clipPath="url(#clip0_2393_1490)">
|
||||
<path d="M8 0V4" stroke="currentColor" strokeWidth="1.5" />
|
||||
<path
|
||||
d="M8 16V12"
|
||||
opacity="0.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M3.29773 1.52783L5.64887 4.7639"
|
||||
opacity="0.9"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M12.7023 1.52783L10.3511 4.7639"
|
||||
opacity="0.1"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M12.7023 14.472L10.3511 11.236"
|
||||
opacity="0.4"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M3.29773 14.472L5.64887 11.236"
|
||||
opacity="0.6"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M15.6085 5.52783L11.8043 6.7639"
|
||||
opacity="0.2"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M0.391602 10.472L4.19583 9.23598"
|
||||
opacity="0.7"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M15.6085 10.4722L11.8043 9.2361"
|
||||
opacity="0.3"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M0.391602 5.52783L4.19583 6.7639"
|
||||
opacity="0.8"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_2393_1490">
|
||||
<rect fill="white" height="16" width="16" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export type LoaderProps = HTMLAttributes<HTMLDivElement> & {
|
||||
size?: number;
|
||||
};
|
||||
|
||||
export const Loader = ({ className, size = 16, ...props }: LoaderProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex animate-spin items-center justify-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<LoaderIcon size={size} />
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,308 @@
|
||||
import React, { useState, useCallback, useContext, createContext } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SheetContextType {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
side: 'top' | 'right' | 'bottom' | 'left';
|
||||
}
|
||||
|
||||
const SheetContext = createContext<SheetContextType | undefined>(undefined);
|
||||
|
||||
function useSheet() {
|
||||
const context = useContext(SheetContext);
|
||||
if (!context) {
|
||||
throw new Error('Sheet components must be used within a Sheet');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface SheetProps {
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
children: React.ReactNode;
|
||||
side?: 'top' | 'right' | 'bottom' | 'left';
|
||||
}
|
||||
|
||||
function Sheet({
|
||||
open: controlledOpen,
|
||||
onOpenChange,
|
||||
children,
|
||||
side = 'right',
|
||||
}: SheetProps) {
|
||||
const [internalOpen, setInternalOpen] = useState(false);
|
||||
const isControlled = controlledOpen !== undefined;
|
||||
const open = isControlled ? controlledOpen : internalOpen;
|
||||
|
||||
const setOpen = useCallback(
|
||||
(newOpen: boolean) => {
|
||||
if (!isControlled) {
|
||||
setInternalOpen(newOpen);
|
||||
}
|
||||
onOpenChange?.(newOpen);
|
||||
},
|
||||
[isControlled, onOpenChange]
|
||||
);
|
||||
|
||||
return (
|
||||
<SheetContext.Provider value={{ open, setOpen, side }}>
|
||||
{children}
|
||||
</SheetContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetTrigger(
|
||||
props: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }
|
||||
) {
|
||||
const { setOpen } = useSheet();
|
||||
const { children, asChild, ...rest } = props;
|
||||
|
||||
if (asChild && React.isValidElement(children)) {
|
||||
const child = children as React.ReactElement<any>;
|
||||
return React.cloneElement(child, {
|
||||
...rest,
|
||||
onClick: (e: React.MouseEvent) => {
|
||||
setOpen(true);
|
||||
child.props.onClick?.(e);
|
||||
},
|
||||
} as any);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
data-slot="sheet-trigger"
|
||||
{...rest}
|
||||
onClick={(e) => {
|
||||
setOpen(true);
|
||||
props.onClick?.(e);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetPortal({ children }: { children: React.ReactNode }) {
|
||||
return createPortal(children, document.body);
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
const { setOpen } = useSheet();
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="sheet-overlay"
|
||||
className={cn('fixed inset-0 z-50 bg-black/50', className)}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
onClick={(e) => {
|
||||
setOpen(false);
|
||||
onClick?.(e);
|
||||
}}
|
||||
{...(props as any)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface SheetContentProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
showCloseButton?: boolean;
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: SheetContentProps) {
|
||||
const { setOpen, side } = useSheet();
|
||||
|
||||
const sideClasses = {
|
||||
right: 'inset-y-0 right-0 h-full w-3/4 sm:max-w-sm border-l',
|
||||
left: 'inset-y-0 left-0 h-full w-3/4 sm:max-w-sm border-r',
|
||||
top: 'inset-x-0 top-0 h-auto border-b',
|
||||
bottom: 'inset-x-0 bottom-0 h-auto border-t',
|
||||
};
|
||||
|
||||
const slideVariants = {
|
||||
right: {
|
||||
initial: { x: 400, opacity: 0 },
|
||||
animate: { x: 0, opacity: 1 },
|
||||
exit: { x: 400, opacity: 0 },
|
||||
},
|
||||
left: {
|
||||
initial: { x: -400, opacity: 0 },
|
||||
animate: { x: 0, opacity: 1 },
|
||||
exit: { x: -400, opacity: 0 },
|
||||
},
|
||||
top: {
|
||||
initial: { y: -400, opacity: 0 },
|
||||
animate: { y: 0, opacity: 1 },
|
||||
exit: { y: -400, opacity: 0 },
|
||||
},
|
||||
bottom: {
|
||||
initial: { y: 400, opacity: 0 },
|
||||
animate: { y: 0, opacity: 1 },
|
||||
exit: { y: 400, opacity: 0 },
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<motion.div
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
'bg-background fixed z-50 flex flex-col gap-0 shadow-lg',
|
||||
sideClasses[side]
|
||||
)}
|
||||
variants={slideVariants[side]}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
transition={{ type: 'spring', stiffness: 300, damping: 30 }}
|
||||
{...(props as any)}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<button
|
||||
data-slot="sheet-close"
|
||||
onClick={() => setOpen(false)}
|
||||
className="absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none"
|
||||
aria-label="Close"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="size-4"
|
||||
>
|
||||
<path d="M18 6l-12 12M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</motion.div>
|
||||
</SheetPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetClose(
|
||||
props: React.ButtonHTMLAttributes<HTMLButtonElement> & { asChild?: boolean }
|
||||
) {
|
||||
const { setOpen } = useSheet();
|
||||
const { children, asChild, ...rest } = props;
|
||||
|
||||
if (asChild && React.isValidElement(children)) {
|
||||
const child = children as React.ReactElement<any>;
|
||||
return React.cloneElement(child, {
|
||||
...rest,
|
||||
onClick: (e: React.MouseEvent) => {
|
||||
setOpen(false);
|
||||
child.props.onClick?.(e);
|
||||
},
|
||||
} as any);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
data-slot="sheet-close"
|
||||
{...rest}
|
||||
onClick={(e) => {
|
||||
setOpen(false);
|
||||
props.onClick?.(e);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn(
|
||||
'flex flex-col gap-1.5 p-6 border-b border-border',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn(
|
||||
'flex flex-col-reverse gap-2 p-6 border-t border-border sm:flex-row sm:justify-end',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetTitle({ className, ...props }: React.ComponentProps<'h2'>) {
|
||||
return (
|
||||
<h2
|
||||
data-slot="sheet-title"
|
||||
className={cn('text-lg leading-none font-semibold', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetDescription({ className, ...props }: React.ComponentProps<'p'>) {
|
||||
return (
|
||||
<p
|
||||
data-slot="sheet-description"
|
||||
className={cn('text-muted-foreground text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface SheetBodyProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
function SheetBody({ className, children, ...props }: SheetBodyProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-body"
|
||||
className={cn('flex-1 overflow-y-auto px-6 py-4', className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
SheetBody,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
AnimatePresence,
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
/** Chrome shared by every route — rendered once in the root layout. */
|
||||
export const site = {
|
||||
storeName: 'Shop',
|
||||
description: 'A Shopify storefront built with Vite, TanStack and Hydrogen.',
|
||||
// Absolute origin for canonical and Open Graph URLs.
|
||||
url:
|
||||
import.meta.env.VITE_SITE_URL ??
|
||||
(typeof window !== 'undefined'
|
||||
? window.location.origin
|
||||
: 'http://localhost:5173'),
|
||||
logoUrl: '',
|
||||
copyright: '© 2026 Shop. All rights reserved.',
|
||||
// Literal paths (not `string`), so the router's typed links accept them.
|
||||
// Kept free of router imports: the route tree imports this file.
|
||||
navLinks: [
|
||||
{ label: 'Products', url: '/' },
|
||||
{ label: 'Collections', url: '/collections' },
|
||||
] as const,
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
// Swatch configuration for product option pickers.
|
||||
//
|
||||
// Shopify exposes a `swatch` on each option value, but plenty of products ship
|
||||
// without one configured. These settings decide which options render as colour
|
||||
// circles and what colour to use when the API doesn't supply one.
|
||||
|
||||
// Option names (case-insensitive) rendered as colour circles instead of pills.
|
||||
export const SWATCH_OPTION_NAMES = ['color', 'colour'];
|
||||
|
||||
// Fallback colours, keyed by lowercased option value name. The first group
|
||||
// mirrors hexes the store defines on other products, so a product missing its
|
||||
// swatches still matches the ones that have them. Add your own names here.
|
||||
export const SWATCH_COLORS: Record<string, string> = {
|
||||
clay: '#5a4b3c',
|
||||
green: '#81a69b',
|
||||
ocean: '#768da0',
|
||||
olive: '#7f8060',
|
||||
purple: '#766589',
|
||||
red: '#a88084',
|
||||
|
||||
beige: '#e8dcc8',
|
||||
black: '#000000',
|
||||
blue: '#2563eb',
|
||||
brown: '#7c5c40',
|
||||
burgundy: '#6d2532',
|
||||
charcoal: '#36393d',
|
||||
cream: '#f3ead8',
|
||||
gold: '#c9a227',
|
||||
gray: '#8a8d91',
|
||||
grey: '#8a8d91',
|
||||
ivory: '#f6f2e6',
|
||||
khaki: '#a89d78',
|
||||
lavender: '#b9a8d0',
|
||||
mint: '#a8d5ba',
|
||||
navy: '#1f2a44',
|
||||
orange: '#e2733a',
|
||||
pink: '#e3a7b5',
|
||||
sand: '#d9c9a8',
|
||||
silver: '#c4c6c8',
|
||||
stone: '#a9a294',
|
||||
tan: '#c8a882',
|
||||
teal: '#3f8f8b',
|
||||
white: '#ffffff',
|
||||
yellow: '#e5c34a',
|
||||
};
|
||||
|
||||
export const swatchColorForName = (name: string): string | undefined =>
|
||||
SWATCH_COLORS[name.trim().toLowerCase()];
|
||||
|
||||
export const isSwatchOptionName = (name: string): boolean =>
|
||||
SWATCH_OPTION_NAMES.includes(name.trim().toLowerCase());
|
||||
@@ -0,0 +1,177 @@
|
||||
import { gql } from '@shopify/hydrogen';
|
||||
|
||||
// Cart Fragment for consistent cart data
|
||||
const CartFragment = gql(`
|
||||
fragment CartFragment on Cart {
|
||||
id
|
||||
checkoutUrl
|
||||
totalQuantity
|
||||
discountCodes {
|
||||
code
|
||||
applicable
|
||||
}
|
||||
cost {
|
||||
subtotalAmount {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
totalAmount {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
totalTaxAmount {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
lines(first: 100) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
quantity
|
||||
cost {
|
||||
totalAmount {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
merchandise {
|
||||
... on ProductVariant {
|
||||
id
|
||||
title
|
||||
selectedOptions {
|
||||
name
|
||||
value
|
||||
}
|
||||
price {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
image {
|
||||
id
|
||||
url
|
||||
altText
|
||||
width
|
||||
height
|
||||
}
|
||||
product {
|
||||
id
|
||||
title
|
||||
handle
|
||||
vendor
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
// Create a new cart
|
||||
export const CREATE_CART_MUTATION = gql(
|
||||
`
|
||||
mutation CreateCart($lines: [CartLineInput!], $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
cartCreate(input: { lines: $lines }) {
|
||||
cart {
|
||||
...CartFragment
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CartFragment]
|
||||
);
|
||||
|
||||
// Add lines to cart
|
||||
export const ADD_CART_LINES_MUTATION = gql(
|
||||
`
|
||||
mutation AddCartLines($cartId: ID!, $lines: [CartLineInput!]!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
cartLinesAdd(cartId: $cartId, lines: $lines) {
|
||||
cart {
|
||||
...CartFragment
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CartFragment]
|
||||
);
|
||||
|
||||
// Update cart lines
|
||||
export const UPDATE_CART_LINES_MUTATION = gql(
|
||||
`
|
||||
mutation UpdateCartLines($cartId: ID!, $lines: [CartLineUpdateInput!]!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
cartLinesUpdate(cartId: $cartId, lines: $lines) {
|
||||
cart {
|
||||
...CartFragment
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CartFragment]
|
||||
);
|
||||
|
||||
// Remove lines from cart
|
||||
export const REMOVE_CART_LINES_MUTATION = gql(
|
||||
`
|
||||
mutation RemoveCartLines($cartId: ID!, $lineIds: [ID!]!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
|
||||
cart {
|
||||
...CartFragment
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CartFragment]
|
||||
);
|
||||
|
||||
// Apply (or clear) discount codes on the cart
|
||||
export const UPDATE_CART_DISCOUNT_CODES_MUTATION = gql(
|
||||
`
|
||||
mutation UpdateCartDiscountCodes($cartId: ID!, $discountCodes: [String!]!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {
|
||||
cart {
|
||||
...CartFragment
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CartFragment]
|
||||
);
|
||||
|
||||
// Get cart by ID
|
||||
export const GET_CART_QUERY = gql(
|
||||
`
|
||||
query GetCart($cartId: ID!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
cart(id: $cartId) {
|
||||
...CartFragment
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CartFragment]
|
||||
);
|
||||
@@ -0,0 +1,91 @@
|
||||
import { gql } from '@shopify/hydrogen';
|
||||
import { ProductFragment } from '@/graphql/products';
|
||||
|
||||
// Get all collections
|
||||
export const GET_COLLECTIONS_QUERY = gql(`
|
||||
query GetCollections($first: Int!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
collections(first: $first) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
handle
|
||||
description
|
||||
descriptionHtml
|
||||
image {
|
||||
id
|
||||
url
|
||||
altText
|
||||
width
|
||||
height
|
||||
}
|
||||
}
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
// Get products in a collection
|
||||
export const GET_COLLECTION_PRODUCTS_QUERY = gql(
|
||||
`
|
||||
query GetCollectionProducts(
|
||||
$handle: String!
|
||||
$first: Int!
|
||||
$after: String
|
||||
$sortKey: ProductCollectionSortKeys
|
||||
$reverse: Boolean
|
||||
$filters: [ProductFilter!]
|
||||
$country: CountryCode
|
||||
$language: LanguageCode
|
||||
) @inContext(country: $country, language: $language) {
|
||||
collection(handle: $handle) {
|
||||
id
|
||||
title
|
||||
handle
|
||||
description
|
||||
descriptionHtml
|
||||
image {
|
||||
id
|
||||
url
|
||||
altText
|
||||
width
|
||||
height
|
||||
}
|
||||
products(
|
||||
first: $first
|
||||
after: $after
|
||||
sortKey: $sortKey
|
||||
reverse: $reverse
|
||||
filters: $filters
|
||||
) {
|
||||
filters {
|
||||
id
|
||||
label
|
||||
type
|
||||
values {
|
||||
id
|
||||
label
|
||||
count
|
||||
input
|
||||
}
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
...ProductFragment
|
||||
}
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[ProductFragment]
|
||||
);
|
||||
@@ -0,0 +1,178 @@
|
||||
// Customer account operations (classic Storefront customer accounts).
|
||||
// https://shopify.dev/docs/api/storefront/latest/objects/Customer
|
||||
import { gql } from '@shopify/hydrogen';
|
||||
|
||||
const CustomerFragment = gql(`
|
||||
fragment CustomerFragment on Customer {
|
||||
id
|
||||
email
|
||||
firstName
|
||||
lastName
|
||||
phone
|
||||
displayName
|
||||
acceptsMarketing
|
||||
createdAt
|
||||
defaultAddress {
|
||||
id
|
||||
firstName
|
||||
lastName
|
||||
address1
|
||||
address2
|
||||
city
|
||||
province
|
||||
zip
|
||||
country
|
||||
phone
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const CUSTOMER_QUERY = gql(
|
||||
`
|
||||
query GetCustomer($customerAccessToken: String!, $orderCount: Int!) {
|
||||
customer(customerAccessToken: $customerAccessToken) {
|
||||
...CustomerFragment
|
||||
orders(first: $orderCount, reverse: true) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
orderNumber
|
||||
processedAt
|
||||
financialStatus
|
||||
fulfillmentStatus
|
||||
statusUrl
|
||||
currentTotalPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
lineItems(first: 5) {
|
||||
edges {
|
||||
node {
|
||||
title
|
||||
quantity
|
||||
variant {
|
||||
image {
|
||||
url
|
||||
altText
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CustomerFragment]
|
||||
);
|
||||
|
||||
export const CUSTOMER_CREATE_MUTATION = gql(`
|
||||
mutation CustomerCreate($input: CustomerCreateInput!) {
|
||||
customerCreate(input: $input) {
|
||||
customer {
|
||||
id
|
||||
email
|
||||
}
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION = gql(`
|
||||
mutation CustomerAccessTokenCreate($input: CustomerAccessTokenCreateInput!) {
|
||||
customerAccessTokenCreate(input: $input) {
|
||||
customerAccessToken {
|
||||
accessToken
|
||||
expiresAt
|
||||
}
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION = gql(`
|
||||
mutation CustomerAccessTokenDelete($customerAccessToken: String!) {
|
||||
customerAccessTokenDelete(customerAccessToken: $customerAccessToken) {
|
||||
deletedAccessToken
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
// Sends the "reset your password" email.
|
||||
export const CUSTOMER_RECOVER_MUTATION = gql(`
|
||||
mutation CustomerRecover($email: String!) {
|
||||
customerRecover(email: $email) {
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
// Completes the reset using the id + token from the emailed link.
|
||||
export const CUSTOMER_RESET_MUTATION = gql(`
|
||||
mutation CustomerReset($id: ID!, $input: CustomerResetInput!) {
|
||||
customerReset(id: $id, input: $input) {
|
||||
customerAccessToken {
|
||||
accessToken
|
||||
expiresAt
|
||||
}
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
// Activation link sent to customers created by the merchant.
|
||||
export const CUSTOMER_ACTIVATE_MUTATION = gql(`
|
||||
mutation CustomerActivate($id: ID!, $input: CustomerActivateInput!) {
|
||||
customerActivate(id: $id, input: $input) {
|
||||
customerAccessToken {
|
||||
accessToken
|
||||
expiresAt
|
||||
}
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
export const CUSTOMER_UPDATE_MUTATION = gql(
|
||||
`
|
||||
mutation CustomerUpdate($customerAccessToken: String!, $customer: CustomerUpdateInput!) {
|
||||
customerUpdate(customerAccessToken: $customerAccessToken, customer: $customer) {
|
||||
customer {
|
||||
...CustomerFragment
|
||||
}
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[CustomerFragment]
|
||||
);
|
||||
@@ -0,0 +1,45 @@
|
||||
import { gql } from '@shopify/hydrogen';
|
||||
|
||||
// Shop policies are exposed on the `shop` object of the Storefront API.
|
||||
// There is no lookup-by-handle field, so we fetch all of them and match.
|
||||
export const GET_SHOP_POLICIES_QUERY = gql(`
|
||||
query GetShopPolicies {
|
||||
shop {
|
||||
privacyPolicy {
|
||||
id
|
||||
title
|
||||
handle
|
||||
body
|
||||
url
|
||||
}
|
||||
termsOfService {
|
||||
id
|
||||
title
|
||||
handle
|
||||
body
|
||||
url
|
||||
}
|
||||
refundPolicy {
|
||||
id
|
||||
title
|
||||
handle
|
||||
body
|
||||
url
|
||||
}
|
||||
shippingPolicy {
|
||||
id
|
||||
title
|
||||
handle
|
||||
body
|
||||
url
|
||||
}
|
||||
subscriptionPolicy {
|
||||
id
|
||||
title
|
||||
handle
|
||||
body
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
@@ -0,0 +1,149 @@
|
||||
import { gql } from '@shopify/hydrogen';
|
||||
|
||||
// Product Fragment for consistent product data
|
||||
export const ProductFragment = gql(`
|
||||
fragment ProductFragment on Product {
|
||||
id
|
||||
title
|
||||
handle
|
||||
description
|
||||
descriptionHtml
|
||||
vendor
|
||||
productType
|
||||
tags
|
||||
availableForSale
|
||||
priceRange {
|
||||
minVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
maxVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
compareAtPriceRange {
|
||||
minVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
maxVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
images(first: 10) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
url
|
||||
altText
|
||||
width
|
||||
height
|
||||
}
|
||||
}
|
||||
}
|
||||
variants(first: 100) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
availableForSale
|
||||
selectedOptions {
|
||||
name
|
||||
value
|
||||
}
|
||||
price {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
compareAtPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
image {
|
||||
id
|
||||
url
|
||||
altText
|
||||
width
|
||||
height
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
options {
|
||||
id
|
||||
name
|
||||
values
|
||||
optionValues {
|
||||
id
|
||||
name
|
||||
swatch {
|
||||
color
|
||||
image {
|
||||
previewImage {
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
firstSelectableVariant {
|
||||
id
|
||||
image {
|
||||
id
|
||||
url
|
||||
altText
|
||||
width
|
||||
height
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
|
||||
// Get multiple products
|
||||
export const GET_PRODUCTS_QUERY = gql(
|
||||
`
|
||||
query GetProducts($first: Int!, $after: String, $query: String, $sortKey: ProductSortKeys, $reverse: Boolean, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
products(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) {
|
||||
edges {
|
||||
node {
|
||||
...ProductFragment
|
||||
}
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[ProductFragment]
|
||||
);
|
||||
|
||||
// Get a single product by handle
|
||||
export const GET_PRODUCT_QUERY = gql(
|
||||
`
|
||||
query GetProduct($handle: String!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
product(handle: $handle) {
|
||||
...ProductFragment
|
||||
}
|
||||
}
|
||||
`,
|
||||
[ProductFragment]
|
||||
);
|
||||
|
||||
// Get product recommendations
|
||||
export const QUERY_PRODUCT_RECOMMENDATIONS = gql(
|
||||
`
|
||||
query GetProductRecommendations($productId: ID!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
productRecommendations(productId: $productId) {
|
||||
...ProductFragment
|
||||
}
|
||||
}
|
||||
`,
|
||||
[ProductFragment]
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
import { gql } from '@shopify/hydrogen';
|
||||
import { ProductFragment } from '@/graphql/products';
|
||||
|
||||
// Storefront search over products. `productFilters` accepts the raw `input`
|
||||
// values returned in `productFilters[].values[].input`, so facets round-trip
|
||||
// without the client needing to know each filter's shape.
|
||||
export const SEARCH_PRODUCTS_QUERY = gql(
|
||||
`
|
||||
query SearchProducts(
|
||||
$query: String!
|
||||
$first: Int!
|
||||
$after: String
|
||||
$sortKey: SearchSortKeys
|
||||
$reverse: Boolean
|
||||
$productFilters: [ProductFilter!]
|
||||
$country: CountryCode
|
||||
$language: LanguageCode
|
||||
) @inContext(country: $country, language: $language) {
|
||||
search(
|
||||
query: $query
|
||||
first: $first
|
||||
after: $after
|
||||
types: PRODUCT
|
||||
sortKey: $sortKey
|
||||
reverse: $reverse
|
||||
productFilters: $productFilters
|
||||
) {
|
||||
totalCount
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
productFilters {
|
||||
id
|
||||
label
|
||||
type
|
||||
values {
|
||||
id
|
||||
label
|
||||
count
|
||||
input
|
||||
}
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
# types: PRODUCT already narrows the results, but the schema still
|
||||
# types nodes as a union — __typename lets callers narrow too.
|
||||
__typename
|
||||
... on Product {
|
||||
...ProductFragment
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
[ProductFragment]
|
||||
);
|
||||
|
||||
// Lightweight variant for the autocomplete dropdown — just enough to render a
|
||||
// row, so the dialog stays responsive while typing.
|
||||
export const SEARCH_SUGGESTIONS_QUERY = gql(`
|
||||
query SearchSuggestions($query: String!, $first: Int!, $country: CountryCode, $language: LanguageCode)
|
||||
@inContext(country: $country, language: $language) {
|
||||
search(query: $query, first: $first, types: PRODUCT) {
|
||||
totalCount
|
||||
edges {
|
||||
node {
|
||||
__typename
|
||||
... on Product {
|
||||
id
|
||||
title
|
||||
handle
|
||||
featuredImage {
|
||||
url
|
||||
altText
|
||||
}
|
||||
priceRange {
|
||||
minVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`);
|
||||
@@ -0,0 +1,41 @@
|
||||
import { queryOptions } from '@tanstack/react-query';
|
||||
import type { Customer } from '@/services/shopify/customer';
|
||||
|
||||
// The customer token lives in an httpOnly cookie, so account state always comes
|
||||
// from the Hono API (server/account.ts) rather than from Shopify directly.
|
||||
|
||||
export interface SessionCustomer {
|
||||
displayName: string;
|
||||
email: string;
|
||||
firstName?: string | null;
|
||||
}
|
||||
|
||||
async function getJson<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url, { credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/** Every account query shares this prefix, so sign-in/out can reset them all. */
|
||||
export const ACCOUNT_QUERY_KEY = ['account'] as const;
|
||||
|
||||
export const sessionQueryOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: [...ACCOUNT_QUERY_KEY, 'me'],
|
||||
queryFn: () =>
|
||||
getJson<{ customer: SessionCustomer | null }>('/api/account/me')
|
||||
.then((data) => data.customer)
|
||||
// A failed probe reads as signed out.
|
||||
.catch(() => null),
|
||||
});
|
||||
|
||||
export const customerQueryOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: [...ACCOUNT_QUERY_KEY, 'customer'],
|
||||
queryFn: () =>
|
||||
getJson<{ customer: Customer | null }>('/api/account/customer').then(
|
||||
(data) => data.customer
|
||||
),
|
||||
// Orders should reflect a purchase made a moment ago.
|
||||
staleTime: 0,
|
||||
});
|
||||
@@ -0,0 +1,440 @@
|
||||
import { create } from 'zustand';
|
||||
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
|
||||
import {
|
||||
CREATE_CART_MUTATION,
|
||||
ADD_CART_LINES_MUTATION,
|
||||
UPDATE_CART_LINES_MUTATION,
|
||||
REMOVE_CART_LINES_MUTATION,
|
||||
UPDATE_CART_DISCOUNT_CODES_MUTATION,
|
||||
GET_CART_QUERY,
|
||||
} from '@/graphql/cart';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────────────
|
||||
|
||||
export interface CartLineInput {
|
||||
merchandiseId: string;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export interface CartLineUpdateInput {
|
||||
id: string;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface CartLine {
|
||||
id: string;
|
||||
quantity: number;
|
||||
cost: {
|
||||
totalAmount: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
};
|
||||
};
|
||||
merchandise: {
|
||||
id: string;
|
||||
title: string;
|
||||
selectedOptions: Array<{
|
||||
name: string;
|
||||
value: string;
|
||||
}>;
|
||||
price: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
};
|
||||
image?: {
|
||||
id?: string | null;
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
} | null;
|
||||
product: {
|
||||
id: string;
|
||||
title: string;
|
||||
handle: string;
|
||||
vendor?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface CartDiscountCode {
|
||||
code: string;
|
||||
applicable: boolean;
|
||||
}
|
||||
|
||||
export interface Cart {
|
||||
id: string;
|
||||
checkoutUrl: string;
|
||||
totalQuantity: number;
|
||||
discountCodes?: CartDiscountCode[];
|
||||
cost: {
|
||||
subtotalAmount: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
};
|
||||
totalAmount: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
};
|
||||
totalTaxAmount?: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
} | null;
|
||||
};
|
||||
lines: {
|
||||
edges: Array<{
|
||||
node: CartLine;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Shopify API functions ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Every cart mutation returns the same `{ cart, userErrors }` payload, and both
|
||||
* the payload and the cart inside it are nullable — Shopify returns no cart when
|
||||
* the mutation could not be applied. Callers want a cart or an exception.
|
||||
*/
|
||||
function unwrapCartPayload<T>(
|
||||
payload:
|
||||
| {
|
||||
cart?: T | null;
|
||||
userErrors: ReadonlyArray<{ message: string }>;
|
||||
}
|
||||
| null
|
||||
| undefined
|
||||
): T {
|
||||
if (payload?.userErrors.length) {
|
||||
throw new Error(payload.userErrors[0].message);
|
||||
}
|
||||
|
||||
if (!payload?.cart) {
|
||||
throw new Error('Cart update failed. Please try again.');
|
||||
}
|
||||
|
||||
return payload.cart;
|
||||
}
|
||||
|
||||
async function createCartApi(lines: CartLineInput[] = []): Promise<Cart> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CREATE_CART_MUTATION, {
|
||||
variables: { lines: lines.length > 0 ? lines : null },
|
||||
}),
|
||||
'CreateCart'
|
||||
);
|
||||
|
||||
return unwrapCartPayload(data.cartCreate);
|
||||
}
|
||||
|
||||
async function addCartLinesApi(
|
||||
cartId: string,
|
||||
lines: CartLineInput[]
|
||||
): Promise<Cart> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(ADD_CART_LINES_MUTATION, {
|
||||
variables: { cartId, lines },
|
||||
}),
|
||||
'AddCartLines'
|
||||
);
|
||||
|
||||
return unwrapCartPayload(data.cartLinesAdd);
|
||||
}
|
||||
|
||||
async function updateCartLinesApi(
|
||||
cartId: string,
|
||||
lines: CartLineUpdateInput[]
|
||||
): Promise<Cart> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(UPDATE_CART_LINES_MUTATION, {
|
||||
variables: { cartId, lines },
|
||||
}),
|
||||
'UpdateCartLines'
|
||||
);
|
||||
|
||||
return unwrapCartPayload(data.cartLinesUpdate);
|
||||
}
|
||||
|
||||
async function removeCartLinesApi(
|
||||
cartId: string,
|
||||
lineIds: string[]
|
||||
): Promise<Cart> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(REMOVE_CART_LINES_MUTATION, {
|
||||
variables: { cartId, lineIds },
|
||||
}),
|
||||
'RemoveCartLines'
|
||||
);
|
||||
|
||||
return unwrapCartPayload(data.cartLinesRemove);
|
||||
}
|
||||
|
||||
async function updateCartDiscountCodesApi(
|
||||
cartId: string,
|
||||
discountCodes: string[]
|
||||
): Promise<Cart> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(UPDATE_CART_DISCOUNT_CODES_MUTATION, {
|
||||
variables: { cartId, discountCodes },
|
||||
}),
|
||||
'UpdateCartDiscountCodes'
|
||||
);
|
||||
|
||||
return unwrapCartPayload(data.cartDiscountCodesUpdate);
|
||||
}
|
||||
|
||||
async function getCartApi(cartId: string): Promise<Cart | null> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(GET_CART_QUERY, { variables: { cartId } }),
|
||||
'GetCart'
|
||||
);
|
||||
|
||||
return data.cart;
|
||||
}
|
||||
|
||||
export function redirectToCheckout(checkoutUrl: string): void {
|
||||
if (checkoutUrl) {
|
||||
window.location.href = checkoutUrl;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Zustand Store ───────────────────────────────────────────────────
|
||||
|
||||
const CART_ID_KEY = 'cartId';
|
||||
|
||||
interface CartState {
|
||||
// State
|
||||
isOpen: boolean;
|
||||
cartId: string | null;
|
||||
cart: Cart | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
_initialized: boolean;
|
||||
|
||||
// Computed (derived in the hook)
|
||||
// items, itemCount, totalAmount, checkoutUrl
|
||||
|
||||
// Actions
|
||||
openCart: () => void;
|
||||
closeCart: () => void;
|
||||
toggleCart: () => void;
|
||||
initCart: () => void;
|
||||
addItem: (variantId: string, quantity?: number) => Promise<Cart>;
|
||||
removeItem: (lineId: string) => Promise<Cart>;
|
||||
updateItemQuantity: (lineId: string, quantity: number) => Promise<Cart>;
|
||||
applyDiscountCode: (code: string) => Promise<Cart>;
|
||||
refreshCart: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useCartStore = create<CartState>((set, get) => ({
|
||||
// Initial state
|
||||
isOpen: false,
|
||||
cartId: null,
|
||||
cart: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
_initialized: false,
|
||||
|
||||
// UI actions
|
||||
openCart: () => set({ isOpen: true }),
|
||||
closeCart: () => set({ isOpen: false }),
|
||||
toggleCart: () => set((s) => ({ isOpen: !s.isOpen })),
|
||||
|
||||
// Initialize cart from localStorage
|
||||
initCart: () => {
|
||||
if (get()._initialized) return;
|
||||
set({ _initialized: true });
|
||||
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const storedCartId = localStorage.getItem(CART_ID_KEY);
|
||||
if (!storedCartId) {
|
||||
set({ loading: false });
|
||||
return;
|
||||
}
|
||||
|
||||
set({ loading: true });
|
||||
getCartApi(storedCartId)
|
||||
.then((fetchedCart) => {
|
||||
if (fetchedCart) {
|
||||
set({ cart: fetchedCart, cartId: storedCartId, loading: false });
|
||||
} else {
|
||||
localStorage.removeItem(CART_ID_KEY);
|
||||
set({ cartId: null, cart: null, loading: false });
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem(CART_ID_KEY);
|
||||
set({
|
||||
cartId: null,
|
||||
cart: null,
|
||||
loading: false,
|
||||
error: 'Failed to fetch cart',
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// Add item to cart (creates cart if needed)
|
||||
addItem: async (variantId: string, quantity: number = 1) => {
|
||||
try {
|
||||
set({ loading: true, error: null });
|
||||
|
||||
// Get or create cart
|
||||
let currentCartId = get().cartId;
|
||||
if (!currentCartId) {
|
||||
const storedCartId = localStorage.getItem(CART_ID_KEY);
|
||||
if (storedCartId) {
|
||||
currentCartId = storedCartId;
|
||||
set({ cartId: storedCartId });
|
||||
} else {
|
||||
const newCart = await createCartApi();
|
||||
localStorage.setItem(CART_ID_KEY, newCart.id);
|
||||
set({ cart: newCart, cartId: newCart.id });
|
||||
currentCartId = newCart.id;
|
||||
}
|
||||
}
|
||||
|
||||
const updatedCart = await addCartLinesApi(currentCartId, [
|
||||
{ merchandiseId: variantId, quantity },
|
||||
]);
|
||||
set({ cart: updatedCart, loading: false });
|
||||
return updatedCart;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : 'Failed to add item to cart';
|
||||
set({ error: errorMessage, loading: false });
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
// Remove item from cart
|
||||
removeItem: async (lineId: string) => {
|
||||
const { cartId } = get();
|
||||
if (!cartId) throw new Error('No cart exists');
|
||||
|
||||
try {
|
||||
set({ loading: true, error: null });
|
||||
const updatedCart = await removeCartLinesApi(cartId, [lineId]);
|
||||
set({ cart: updatedCart, loading: false });
|
||||
return updatedCart;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : 'Failed to remove item from cart';
|
||||
set({ error: errorMessage, loading: false });
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
// Update item quantity
|
||||
updateItemQuantity: async (lineId: string, quantity: number) => {
|
||||
const { cartId, removeItem } = get();
|
||||
if (!cartId) throw new Error('No cart exists');
|
||||
|
||||
if (quantity <= 0) {
|
||||
return removeItem(lineId);
|
||||
}
|
||||
|
||||
try {
|
||||
set({ loading: true, error: null });
|
||||
const updatedCart = await updateCartLinesApi(cartId, [
|
||||
{ id: lineId, quantity },
|
||||
]);
|
||||
set({ cart: updatedCart, loading: false });
|
||||
return updatedCart;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : 'Failed to update item quantity';
|
||||
set({ error: errorMessage, loading: false });
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
// Apply a discount code. Shopify accepts unknown codes and reports them back
|
||||
// as `applicable: false`, so callers should check the returned cart.
|
||||
applyDiscountCode: async (code: string) => {
|
||||
const { cartId } = get();
|
||||
if (!cartId) throw new Error('No cart exists');
|
||||
|
||||
try {
|
||||
set({ loading: true, error: null });
|
||||
const trimmed = code.trim();
|
||||
const updatedCart = await updateCartDiscountCodesApi(
|
||||
cartId,
|
||||
trimmed ? [trimmed] : []
|
||||
);
|
||||
set({ cart: updatedCart, loading: false });
|
||||
return updatedCart;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : 'Failed to apply discount code';
|
||||
set({ error: errorMessage, loading: false });
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
// Refresh cart from Shopify
|
||||
refreshCart: async () => {
|
||||
const storedCartId = localStorage.getItem(CART_ID_KEY);
|
||||
if (!storedCartId) {
|
||||
set({ loading: false });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
set({ loading: true, error: null });
|
||||
const fetchedCart = await getCartApi(storedCartId);
|
||||
if (fetchedCart) {
|
||||
set({ cart: fetchedCart, cartId: storedCartId, loading: false });
|
||||
} else {
|
||||
localStorage.removeItem(CART_ID_KEY);
|
||||
set({ cartId: null, cart: null, loading: false });
|
||||
}
|
||||
} catch (err) {
|
||||
localStorage.removeItem(CART_ID_KEY);
|
||||
set({
|
||||
cartId: null,
|
||||
cart: null,
|
||||
loading: false,
|
||||
error: 'Failed to fetch cart',
|
||||
});
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// ─── Hook (backwards-compatible API) ─────────────────────────────────
|
||||
|
||||
export function useShopifyCart() {
|
||||
const store = useCartStore();
|
||||
|
||||
// Initialize cart safely in an effect, not during render
|
||||
useEffect(() => {
|
||||
if (!store._initialized) {
|
||||
store.initCart();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const items = store.cart?.lines?.edges?.map((edge) => edge.node) ?? [];
|
||||
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
|
||||
const totalAmount = parseFloat(store.cart?.cost?.totalAmount?.amount ?? '0');
|
||||
const checkoutUrl = store.cart?.checkoutUrl ?? null;
|
||||
|
||||
return {
|
||||
isOpen: store.isOpen,
|
||||
openCart: store.openCart,
|
||||
closeCart: store.closeCart,
|
||||
toggleCart: store.toggleCart,
|
||||
cartId: store.cartId,
|
||||
cart: store.cart,
|
||||
items,
|
||||
itemCount,
|
||||
totalAmount,
|
||||
checkoutUrl,
|
||||
loading: store.loading,
|
||||
error: store.error,
|
||||
addItem: store.addItem,
|
||||
removeItem: store.removeItem,
|
||||
updateItemQuantity: store.updateItemQuantity,
|
||||
applyDiscountCode: store.applyDiscountCode,
|
||||
refreshCart: store.refreshCart,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
infiniteQueryOptions,
|
||||
queryOptions,
|
||||
useQuery,
|
||||
} from '@tanstack/react-query';
|
||||
import {
|
||||
getCollections,
|
||||
getCollectionProductsPage,
|
||||
type CollectionSortKey,
|
||||
} from '@/services/shopify/catalog';
|
||||
|
||||
export {
|
||||
getCollections,
|
||||
getCollectionProducts,
|
||||
getCollectionProductsPage,
|
||||
} from '@/services/shopify/catalog';
|
||||
export type {
|
||||
Collection,
|
||||
CollectionWithProducts,
|
||||
CollectionSortKey,
|
||||
CollectionProductsPage,
|
||||
ProductFilterFacet,
|
||||
} from '@/services/shopify/catalog';
|
||||
|
||||
export const collectionsQueryOptions = (first = 50) =>
|
||||
queryOptions({
|
||||
queryKey: ['collections', first],
|
||||
queryFn: () => getCollections(first),
|
||||
});
|
||||
|
||||
export const collectionProductsInfiniteQueryOptions = (
|
||||
handle: string,
|
||||
{
|
||||
first = 24,
|
||||
sortKey = 'COLLECTION_DEFAULT',
|
||||
reverse = false,
|
||||
filterInputs = [],
|
||||
}: {
|
||||
first?: number;
|
||||
sortKey?: CollectionSortKey;
|
||||
reverse?: boolean;
|
||||
filterInputs?: string[];
|
||||
} = {}
|
||||
) =>
|
||||
infiniteQueryOptions({
|
||||
queryKey: [
|
||||
'collection-products',
|
||||
handle,
|
||||
{ first, sortKey, reverse, filterInputs },
|
||||
],
|
||||
queryFn: ({ pageParam }) =>
|
||||
getCollectionProductsPage(handle, {
|
||||
first,
|
||||
after: pageParam,
|
||||
sortKey,
|
||||
reverse,
|
||||
filterInputs,
|
||||
}),
|
||||
initialPageParam: null as string | null,
|
||||
getNextPageParam: (page) => (page.hasNextPage ? page.endCursor : undefined),
|
||||
});
|
||||
|
||||
// Hook for fetching all collections
|
||||
export function useCollections(first = 50) {
|
||||
const { data, isPending, error, refetch } = useQuery(
|
||||
collectionsQueryOptions(first)
|
||||
);
|
||||
|
||||
return {
|
||||
collections: data ?? [],
|
||||
loading: isPending,
|
||||
error: error ? error.message || 'Failed to load collections' : null,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
|
||||
// Deferred variant of useCollections: nothing is requested until `load` runs,
|
||||
// so a menu can hold off until it's actually opened. Re-opening reuses the
|
||||
// cached result; after a failure, `load` retries.
|
||||
export function useCollectionsOnDemand(first = 50) {
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const { data, isFetching, error, refetch } = useQuery({
|
||||
...collectionsQueryOptions(first),
|
||||
enabled,
|
||||
});
|
||||
|
||||
const load = () => {
|
||||
if (!enabled) setEnabled(true);
|
||||
else if (error) refetch();
|
||||
};
|
||||
|
||||
return {
|
||||
collections: data ?? [],
|
||||
loading: isFetching && !data,
|
||||
error: error ? error.message || 'Failed to load collections' : null,
|
||||
load,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { queryOptions } from '@tanstack/react-query';
|
||||
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
|
||||
import { GET_SHOP_POLICIES_QUERY } from '@/graphql/policies';
|
||||
|
||||
export interface ShopPolicy {
|
||||
id: string;
|
||||
title: string;
|
||||
handle: string;
|
||||
body: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
// Handles Shopify uses for each policy — also the routes under /policies/$handle.
|
||||
export const POLICY_HANDLES = [
|
||||
'terms-of-service',
|
||||
'privacy-policy',
|
||||
'refund-policy',
|
||||
'shipping-policy',
|
||||
'subscription-policy',
|
||||
] as const;
|
||||
|
||||
export async function getShopPolicies(): Promise<ShopPolicy[]> {
|
||||
try {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(GET_SHOP_POLICIES_QUERY),
|
||||
'GetShopPolicies'
|
||||
);
|
||||
|
||||
return Object.values(data.shop ?? {}).filter(
|
||||
(policy): policy is ShopPolicy => Boolean(policy?.handle)
|
||||
);
|
||||
} catch (err) {
|
||||
// A storefront without policies configured shouldn't break the page.
|
||||
console.error('Failed to load shop policies:', err);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Policies change rarely, so they stay fresh for an hour rather than the
|
||||
// app-wide default.
|
||||
export const shopPoliciesQueryOptions = () =>
|
||||
queryOptions({
|
||||
queryKey: ['shop-policies'],
|
||||
queryFn: getShopPolicies,
|
||||
staleTime: 60 * 60 * 1000,
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import {
|
||||
infiniteQueryOptions,
|
||||
queryOptions,
|
||||
useQuery,
|
||||
} from '@tanstack/react-query';
|
||||
import {
|
||||
getProduct,
|
||||
getProductsPage,
|
||||
getProductRecommendations,
|
||||
} from '@/services/shopify/catalog';
|
||||
|
||||
// Pure fetchers live in services/shopify/catalog so server code can use them
|
||||
// too; re-exported here so components have one place to import from.
|
||||
export {
|
||||
getProducts,
|
||||
getProductsPage,
|
||||
getProduct,
|
||||
getProductRecommendations,
|
||||
} from '@/services/shopify/catalog';
|
||||
export type {
|
||||
Product,
|
||||
ProductOption,
|
||||
ProductOptionValue,
|
||||
ProductsPage,
|
||||
} from '@/services/shopify/catalog';
|
||||
|
||||
type ProductsSortKey = 'BEST_SELLING' | 'CREATED_AT' | 'PRICE' | 'TITLE';
|
||||
|
||||
export const productQueryOptions = (handle: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['product', handle],
|
||||
queryFn: () => getProduct(handle),
|
||||
});
|
||||
|
||||
export const productRecommendationsQueryOptions = (productId: string) =>
|
||||
queryOptions({
|
||||
queryKey: ['product-recommendations', productId],
|
||||
queryFn: () => getProductRecommendations(productId),
|
||||
});
|
||||
|
||||
// Paging is cursor-based: each page's `endCursor` becomes the next `after`.
|
||||
export const productsInfiniteQueryOptions = ({
|
||||
first = 12,
|
||||
sortKey = 'CREATED_AT',
|
||||
reverse = true,
|
||||
}: {
|
||||
first?: number;
|
||||
sortKey?: ProductsSortKey;
|
||||
reverse?: boolean;
|
||||
} = {}) =>
|
||||
infiniteQueryOptions({
|
||||
queryKey: ['products', { first, sortKey, reverse }],
|
||||
queryFn: ({ pageParam }) =>
|
||||
getProductsPage({ first, after: pageParam, sortKey, reverse }),
|
||||
initialPageParam: null as string | null,
|
||||
getNextPageParam: (page) => (page.hasNextPage ? page.endCursor : undefined),
|
||||
});
|
||||
|
||||
const errorMessage = (error: Error | null, fallback: string) =>
|
||||
error ? error.message || fallback : null;
|
||||
|
||||
// Fetch a single product
|
||||
export function useProduct(handle: string | null) {
|
||||
const { data, isPending, error, refetch } = useQuery({
|
||||
...productQueryOptions(handle ?? ''),
|
||||
enabled: Boolean(handle),
|
||||
});
|
||||
|
||||
return {
|
||||
product: data ?? null,
|
||||
loading: Boolean(handle) && isPending,
|
||||
error:
|
||||
errorMessage(error, 'Failed to load product') ??
|
||||
(data === null ? 'Product not found' : null),
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
|
||||
// Fetch product recommendations
|
||||
export function useProductRecommendations(productId: string | null) {
|
||||
const { data, isPending, error, refetch } = useQuery({
|
||||
...productRecommendationsQueryOptions(productId ?? ''),
|
||||
enabled: Boolean(productId),
|
||||
});
|
||||
|
||||
return {
|
||||
recommendations: data ?? [],
|
||||
loading: Boolean(productId) && isPending,
|
||||
error: errorMessage(error, 'Failed to load recommendations'),
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { infiniteQueryOptions, queryOptions } from '@tanstack/react-query';
|
||||
import {
|
||||
searchProducts,
|
||||
searchSuggestions,
|
||||
type SearchSortKey,
|
||||
} from '@/services/shopify/catalog';
|
||||
|
||||
// Re-exported from the catalogue module so both components and the Hono server
|
||||
// can search the storefront.
|
||||
export { searchProducts, searchSuggestions } from '@/services/shopify/catalog';
|
||||
export type {
|
||||
SearchSortKey,
|
||||
SearchFilter,
|
||||
SearchFilterValue,
|
||||
SearchProductsResult,
|
||||
SearchSuggestion,
|
||||
} from '@/services/shopify/catalog';
|
||||
|
||||
export const searchInfiniteQueryOptions = ({
|
||||
query,
|
||||
first = 24,
|
||||
sortKey = 'RELEVANCE',
|
||||
reverse = false,
|
||||
filterInputs = [],
|
||||
}: {
|
||||
query: string;
|
||||
first?: number;
|
||||
sortKey?: SearchSortKey;
|
||||
reverse?: boolean;
|
||||
filterInputs?: string[];
|
||||
}) =>
|
||||
infiniteQueryOptions({
|
||||
queryKey: ['search', { query, first, sortKey, reverse, filterInputs }],
|
||||
queryFn: ({ pageParam }) =>
|
||||
searchProducts({
|
||||
query,
|
||||
first,
|
||||
after: pageParam,
|
||||
sortKey,
|
||||
reverse,
|
||||
filterInputs,
|
||||
}),
|
||||
initialPageParam: null as string | null,
|
||||
getNextPageParam: (page) => (page.hasNextPage ? page.endCursor : undefined),
|
||||
});
|
||||
|
||||
export const searchSuggestionsQueryOptions = (query: string, first = 3) =>
|
||||
queryOptions({
|
||||
queryKey: ['search-suggestions', query, first],
|
||||
queryFn: () => searchSuggestions(query, first),
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { site } from '@/config/site';
|
||||
|
||||
// Builds the head tags each route used to declare through Next's `metadata`.
|
||||
// Routes pass their own title; the store name is appended unless `absolute`.
|
||||
|
||||
interface SeoOptions {
|
||||
title: string;
|
||||
/** Use the title as-is rather than appending the store name. */
|
||||
absolute?: boolean;
|
||||
description?: string;
|
||||
/** Path for the canonical link and og:url, e.g. `/products/shirt`. */
|
||||
path?: string;
|
||||
image?: { url: string; alt?: string } | null;
|
||||
}
|
||||
|
||||
export function seo({
|
||||
title,
|
||||
absolute = false,
|
||||
description = site.description,
|
||||
path,
|
||||
image,
|
||||
}: SeoOptions) {
|
||||
const fullTitle = absolute ? title : `${title} — ${site.storeName}`;
|
||||
const url = path ? new URL(path, site.url).toString() : undefined;
|
||||
|
||||
const meta = [
|
||||
{ title: fullTitle },
|
||||
{ name: 'description', content: description },
|
||||
{ property: 'og:type', content: 'website' },
|
||||
{ property: 'og:site_name', content: site.storeName },
|
||||
{ property: 'og:title', content: title },
|
||||
{ property: 'og:description', content: description },
|
||||
...(url ? [{ property: 'og:url', content: url }] : []),
|
||||
...(image
|
||||
? [
|
||||
{ property: 'og:image', content: image.url },
|
||||
{ property: 'og:image:alt', content: image.alt ?? title },
|
||||
{ name: 'twitter:image', content: image.url },
|
||||
]
|
||||
: []),
|
||||
{ name: 'twitter:card', content: 'summary_large_image' },
|
||||
{ name: 'twitter:title', content: title },
|
||||
{ name: 'twitter:description', content: description },
|
||||
];
|
||||
|
||||
const links = url ? [{ rel: 'canonical', href: url }] : [];
|
||||
|
||||
return { meta, links };
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function truncate(str: string, maxLength: number): string {
|
||||
if (!str) return '';
|
||||
if (str.length <= maxLength) return str;
|
||||
return str.slice(0, maxLength).trim() + '...';
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { RouterProvider, createRouter } from '@tanstack/react-router';
|
||||
import { routeTree } from './routeTree.gen';
|
||||
import { ErrorMessage } from '@/components/route-states';
|
||||
import './styles.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// Catalogue data is fine to reuse for a minute across navigations.
|
||||
staleTime: 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
context: { queryClient },
|
||||
// Hovering a link starts its route loader, so most pages open instantly.
|
||||
defaultPreload: 'intent',
|
||||
// TanStack Query owns caching; always let loaders ask it.
|
||||
defaultPreloadStaleTime: 0,
|
||||
scrollRestoration: true,
|
||||
defaultErrorComponent: ({ error }) => <ErrorMessage error={error} />,
|
||||
});
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface Register {
|
||||
router: typeof router;
|
||||
}
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,56 @@
|
||||
import {
|
||||
HeadContent,
|
||||
Outlet,
|
||||
createRootRouteWithContext,
|
||||
useRouterState,
|
||||
} from '@tanstack/react-router';
|
||||
import type { QueryClient } from '@tanstack/react-query';
|
||||
import Header from '@/components/shopify/header';
|
||||
import Footer from '@/components/shopify/footer';
|
||||
import { site } from '@/config/site';
|
||||
import { seo } from '@/lib/seo';
|
||||
import { NotFound } from '@/components/route-states';
|
||||
|
||||
export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()(
|
||||
{
|
||||
head: () => seo({ title: site.storeName, absolute: true }),
|
||||
component: RootLayout,
|
||||
notFoundComponent: NotFound,
|
||||
}
|
||||
);
|
||||
|
||||
// Thin bar along the top while a route loader is still running.
|
||||
function NavigationProgress() {
|
||||
const loading = useRouterState({ select: (s) => s.status === 'pending' });
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
className={`fixed inset-x-0 top-0 z-100 h-0.5 origin-left bg-foreground transition-transform duration-500 ${
|
||||
loading ? 'scale-x-75' : 'scale-x-0 duration-0'
|
||||
}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RootLayout() {
|
||||
return (
|
||||
<>
|
||||
<HeadContent />
|
||||
<NavigationProgress />
|
||||
<div className="font-body antialiased bg-background text-foreground m-0 p-0 flex min-h-screen flex-col">
|
||||
{/* Header owns the cart drawer, search and account menu, so every
|
||||
route gets them by rendering here rather than page by page. */}
|
||||
<Header
|
||||
storeName={site.storeName}
|
||||
logoUrl={site.logoUrl}
|
||||
links={site.navLinks}
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Outlet />
|
||||
</div>
|
||||
<Footer storeName={site.storeName} copyright={site.copyright} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import AccountForm from '@/components/shopify/account-form';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
// Shopify's emailed activation link is /account/activate/{id}/{token}.
|
||||
export const Route = createFileRoute('/account/activate/$id/$token')({
|
||||
head: () => seo({ title: 'Activate your account' }),
|
||||
component: ActivatePage,
|
||||
});
|
||||
|
||||
function ActivatePage() {
|
||||
const { id, token } = Route.useParams();
|
||||
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-8 py-16">
|
||||
<AccountForm
|
||||
title="Activate your account"
|
||||
description="Choose a password to finish setting up your account."
|
||||
fields={[
|
||||
{
|
||||
name: 'password',
|
||||
label: 'Password',
|
||||
type: 'password',
|
||||
autoComplete: 'new-password',
|
||||
},
|
||||
]}
|
||||
submitLabel="Activate account"
|
||||
endpoint="/api/account/activate"
|
||||
extraPayload={{ id, activationToken: token }}
|
||||
redirectTo="/account"
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createFileRoute, redirect } from '@tanstack/react-router';
|
||||
import OrderHistory from '@/components/shopify/order-history';
|
||||
import { customerQueryOptions } from '@/hooks/use-account';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/account/')({
|
||||
loader: async ({ context: { queryClient } }) => {
|
||||
const customer = await queryClient
|
||||
.fetchQuery(customerQueryOptions())
|
||||
.catch(() => null);
|
||||
|
||||
// No session, or an expired or revoked token: both read as signed out.
|
||||
if (!customer) throw redirect({ to: '/account/login' });
|
||||
|
||||
return { customer };
|
||||
},
|
||||
head: () => seo({ title: 'Order history' }),
|
||||
component: AccountPage,
|
||||
});
|
||||
|
||||
function AccountPage() {
|
||||
const { customer } = Route.useLoaderData();
|
||||
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-8 py-12">
|
||||
<h1 className="text-2xl md:text-3xl font-normal text-foreground">
|
||||
Order history
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
{customer.displayName} · {customer.email}
|
||||
</p>
|
||||
|
||||
<div className="mt-10">
|
||||
<OrderHistory customer={customer} />
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import AccountForm, { AccountFormLink } from '@/components/shopify/account-form';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/account/login')({
|
||||
head: () => seo({ title: 'Sign in' }),
|
||||
component: LoginPage,
|
||||
});
|
||||
|
||||
function LoginPage() {
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-8 py-16">
|
||||
<AccountForm
|
||||
title="Sign in"
|
||||
fields={[
|
||||
{ name: 'email', label: 'Email', type: 'email', autoComplete: 'email' },
|
||||
{
|
||||
name: 'password',
|
||||
label: 'Password',
|
||||
type: 'password',
|
||||
autoComplete: 'current-password',
|
||||
},
|
||||
]}
|
||||
submitLabel="Sign in"
|
||||
endpoint="/api/account/login"
|
||||
redirectTo="/account"
|
||||
footer={
|
||||
<>
|
||||
<span>
|
||||
New here?{' '}
|
||||
<AccountFormLink to="/account/register">
|
||||
Create an account
|
||||
</AccountFormLink>
|
||||
</span>
|
||||
<AccountFormLink to="/account/recover">
|
||||
Forgot your password?
|
||||
</AccountFormLink>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import AccountForm, { AccountFormLink } from '@/components/shopify/account-form';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/account/recover')({
|
||||
head: () => seo({ title: 'Reset password' }),
|
||||
component: RecoverPage,
|
||||
});
|
||||
|
||||
function RecoverPage() {
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-8 py-16">
|
||||
<AccountForm
|
||||
title="Reset password"
|
||||
description="Enter your email and we'll send you a link to set a new password."
|
||||
fields={[
|
||||
{ name: 'email', label: 'Email', type: 'email', autoComplete: 'email' },
|
||||
]}
|
||||
submitLabel="Send reset link"
|
||||
endpoint="/api/account/recover"
|
||||
successMessage="If that email has an account, a reset link is on its way."
|
||||
footer={
|
||||
<AccountFormLink to="/account/login">Back to sign in</AccountFormLink>
|
||||
}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import AccountForm, { AccountFormLink } from '@/components/shopify/account-form';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/account/register')({
|
||||
head: () => seo({ title: 'Create account' }),
|
||||
component: RegisterPage,
|
||||
});
|
||||
|
||||
function RegisterPage() {
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-8 py-16">
|
||||
<AccountForm
|
||||
title="Create account"
|
||||
fields={[
|
||||
{
|
||||
name: 'firstName',
|
||||
label: 'First name',
|
||||
autoComplete: 'given-name',
|
||||
required: false,
|
||||
},
|
||||
{
|
||||
name: 'lastName',
|
||||
label: 'Last name',
|
||||
autoComplete: 'family-name',
|
||||
required: false,
|
||||
},
|
||||
{ name: 'email', label: 'Email', type: 'email', autoComplete: 'email' },
|
||||
{
|
||||
name: 'password',
|
||||
label: 'Password',
|
||||
type: 'password',
|
||||
autoComplete: 'new-password',
|
||||
},
|
||||
]}
|
||||
submitLabel="Create account"
|
||||
endpoint="/api/account/register"
|
||||
redirectTo="/account"
|
||||
footer={
|
||||
<span>
|
||||
Already have an account?{' '}
|
||||
<AccountFormLink to="/account/login">Sign in</AccountFormLink>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import AccountForm from '@/components/shopify/account-form';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
// Shopify's emailed reset link is /account/reset/{id}/{token}.
|
||||
export const Route = createFileRoute('/account/reset/$id/$token')({
|
||||
head: () => seo({ title: 'Set a new password' }),
|
||||
component: ResetPage,
|
||||
});
|
||||
|
||||
function ResetPage() {
|
||||
const { id, token } = Route.useParams();
|
||||
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-8 py-16">
|
||||
<AccountForm
|
||||
title="Set a new password"
|
||||
fields={[
|
||||
{
|
||||
name: 'password',
|
||||
label: 'New password',
|
||||
type: 'password',
|
||||
autoComplete: 'new-password',
|
||||
},
|
||||
]}
|
||||
submitLabel="Save password"
|
||||
endpoint="/api/account/reset"
|
||||
extraPayload={{ id, resetToken: token }}
|
||||
redirectTo="/account"
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { CollectionPage } from '@/components/shopify/collection-detail';
|
||||
import { collectionProductsInfiniteQueryOptions } from '@/hooks/use-shopify-collections';
|
||||
import { truncate } from '@/lib/utils';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
// Must match the component's first-page options so the loader's fetch is the
|
||||
// one the page renders from.
|
||||
const FIRST_PAGE = { first: 24 } as const;
|
||||
|
||||
export const Route = createFileRoute('/collections/$handle')({
|
||||
// Split the page and its pending state into one chunk; they share a body.
|
||||
codeSplitGroupings: [['component', 'pendingComponent']],
|
||||
loader: async ({ params: { handle }, context: { queryClient } }) => {
|
||||
// A failed lookup renders the component's own error state, not a 500.
|
||||
const data = await queryClient
|
||||
.ensureInfiniteQueryData(
|
||||
collectionProductsInfiniteQueryOptions(handle, FIRST_PAGE)
|
||||
)
|
||||
.catch(() => null);
|
||||
|
||||
return { collection: data?.pages[0]?.collection ?? null };
|
||||
},
|
||||
head: ({ loaderData }) => {
|
||||
const collection = loaderData?.collection;
|
||||
if (!collection) return seo({ title: 'Collection' });
|
||||
|
||||
return seo({
|
||||
title: collection.title,
|
||||
description: collection.description
|
||||
? truncate(collection.description, 160)
|
||||
: `Shop the ${collection.title} collection.`,
|
||||
path: `/collections/${collection.handle}`,
|
||||
image: collection.image
|
||||
? {
|
||||
url: collection.image.url,
|
||||
alt: collection.image.altText ?? collection.title,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
},
|
||||
// The page has its own skeleton, driven by the same in-flight query.
|
||||
pendingComponent: CollectionPage,
|
||||
component: CollectionPage,
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import Collections from '@/components/shopify/collections';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/collections/')({
|
||||
head: () =>
|
||||
seo({
|
||||
title: 'Collections',
|
||||
description: 'Browse every collection in the store.',
|
||||
path: '/collections',
|
||||
}),
|
||||
component: () => <Collections title="Our Collections" />,
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import Products from '@/components/shopify/products';
|
||||
import { site } from '@/config/site';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/')({
|
||||
// The home page keeps the bare store name rather than "Shop — Shop".
|
||||
head: () => seo({ title: site.storeName, absolute: true, path: '/' }),
|
||||
component: () => (
|
||||
<Products
|
||||
title="Shopify Hydrogen Storefront"
|
||||
subtitle="A Shopify storefront built with Vite, TanStack and Hydrogen."
|
||||
/>
|
||||
),
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { createFileRoute, notFound } from '@tanstack/react-router';
|
||||
import { shopPoliciesQueryOptions } from '@/hooks/use-shopify-policies';
|
||||
import { site } from '@/config/site';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/policies/$handle')({
|
||||
loader: async ({ params: { handle }, context: { queryClient } }) => {
|
||||
// There is no lookup-by-handle field, so fetch them all and match.
|
||||
const policies = await queryClient.ensureQueryData(
|
||||
shopPoliciesQueryOptions()
|
||||
);
|
||||
const policy = policies.find((p) => p.handle === handle);
|
||||
|
||||
if (!policy) throw notFound();
|
||||
return { policy };
|
||||
},
|
||||
head: ({ loaderData }) => {
|
||||
const policy = loaderData?.policy;
|
||||
if (!policy) return seo({ title: 'Policy' });
|
||||
|
||||
return seo({
|
||||
title: policy.title,
|
||||
description: `Read the ${policy.title.toLowerCase()} for ${site.storeName}.`,
|
||||
path: `/policies/${policy.handle}`,
|
||||
});
|
||||
},
|
||||
component: PolicyPage,
|
||||
});
|
||||
|
||||
function PolicyPage() {
|
||||
const { policy } = Route.useLoaderData();
|
||||
|
||||
return (
|
||||
<main className="max-w-screen-2xl mx-auto w-full px-5 lg:px-10 py-16">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h1 className="text-3xl md:text-4xl font-normal text-foreground">
|
||||
{policy.title}
|
||||
</h1>
|
||||
|
||||
<div
|
||||
className="policy-body mt-8 text-[15px] leading-7 text-foreground"
|
||||
dangerouslySetInnerHTML={{ __html: policy.body }}
|
||||
/>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { ProductPage } from '@/components/shopify/product-detail';
|
||||
import {
|
||||
productQueryOptions,
|
||||
productRecommendationsQueryOptions,
|
||||
} from '@/hooks/use-shopify-products';
|
||||
import { truncate } from '@/lib/utils';
|
||||
import { site } from '@/config/site';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/products/$handle')({
|
||||
// Split the page and its pending state into one chunk; they share a body.
|
||||
codeSplitGroupings: [['component', 'pendingComponent']],
|
||||
loader: async ({ params: { handle }, context: { queryClient } }) => {
|
||||
// ProductDetail renders its own empty state, so a failed lookup here falls
|
||||
// back to generic tags rather than an error page.
|
||||
const product = await queryClient
|
||||
.ensureQueryData(productQueryOptions(handle))
|
||||
.catch(() => null);
|
||||
|
||||
// Warm the recommendations without holding up the page.
|
||||
if (product) {
|
||||
queryClient.prefetchQuery(productRecommendationsQueryOptions(product.id));
|
||||
}
|
||||
|
||||
return { product };
|
||||
},
|
||||
head: ({ loaderData }) => {
|
||||
const product = loaderData?.product;
|
||||
if (!product) return seo({ title: 'Product' });
|
||||
|
||||
const image = product.images.edges[0]?.node;
|
||||
|
||||
return seo({
|
||||
title: product.title,
|
||||
description: product.description
|
||||
? truncate(product.description, 160)
|
||||
: site.description,
|
||||
path: `/products/${product.handle}`,
|
||||
image: image ? { url: image.url, alt: image.altText ?? product.title } : null,
|
||||
});
|
||||
},
|
||||
pendingComponent: ProductPage,
|
||||
component: ProductPage,
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import SearchResults from '@/components/shopify/search-results';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
interface SearchParams {
|
||||
q?: string;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/search')({
|
||||
validateSearch: (search: Record<string, unknown>): SearchParams => ({
|
||||
q: typeof search.q === 'string' && search.q ? search.q : undefined,
|
||||
}),
|
||||
head: () =>
|
||||
seo({
|
||||
title: 'Search',
|
||||
description: 'Search the catalogue by product name, description or type.',
|
||||
path: '/search',
|
||||
}),
|
||||
component: SearchPage,
|
||||
});
|
||||
|
||||
function SearchPage() {
|
||||
const { q } = Route.useSearch();
|
||||
return <SearchResults query={q ?? ''} />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import Collections from '@/components/shopify/collections';
|
||||
import { seo } from '@/lib/seo';
|
||||
|
||||
export const Route = createFileRoute('/shop/collections')({
|
||||
head: () =>
|
||||
seo({
|
||||
title: 'Collections',
|
||||
description: 'Browse every collection in the store.',
|
||||
// Same listing as /collections; point crawlers at the canonical route.
|
||||
path: '/collections',
|
||||
}),
|
||||
component: () => <Collections title="Our Collections" />,
|
||||
});
|
||||
@@ -0,0 +1,446 @@
|
||||
// Server-safe Shopify catalogue access.
|
||||
//
|
||||
// These are plain async functions with no React imports, so they can be called
|
||||
// from the Hono server as well as from the TanStack Query options in
|
||||
// hooks/use-shopify-*.ts, which re-export them.
|
||||
import type { StorefrontApi } from '@shopify/hydrogen';
|
||||
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
|
||||
import {
|
||||
GET_PRODUCTS_QUERY,
|
||||
GET_PRODUCT_QUERY,
|
||||
QUERY_PRODUCT_RECOMMENDATIONS,
|
||||
} from '@/graphql/products';
|
||||
import {
|
||||
GET_COLLECTIONS_QUERY,
|
||||
GET_COLLECTION_PRODUCTS_QUERY,
|
||||
} from '@/graphql/collections';
|
||||
import {
|
||||
SEARCH_PRODUCTS_QUERY,
|
||||
SEARCH_SUGGESTIONS_QUERY,
|
||||
} from '@/graphql/search';
|
||||
|
||||
// Optional fields are `| null` rather than just optional: the Storefront API
|
||||
// returns explicit nulls, and the typed `gql()` documents now surface that.
|
||||
interface ProductImage {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
}
|
||||
|
||||
interface ProductPrice {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
interface ProductVariant {
|
||||
id: string;
|
||||
title: string;
|
||||
price: ProductPrice;
|
||||
availableForSale: boolean;
|
||||
selectedOptions: Array<{
|
||||
name: string;
|
||||
value: string;
|
||||
}>;
|
||||
image?: ProductImage | null;
|
||||
}
|
||||
|
||||
export interface ProductOptionValue {
|
||||
id: string;
|
||||
name: string;
|
||||
swatch?: {
|
||||
color?: string | null;
|
||||
image?: {
|
||||
previewImage?: {
|
||||
url: string;
|
||||
} | null;
|
||||
} | null;
|
||||
} | null;
|
||||
firstSelectableVariant?: {
|
||||
id: string;
|
||||
image?: ProductImage | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ProductOption {
|
||||
id: string;
|
||||
name: string;
|
||||
values: string[];
|
||||
optionValues?: ProductOptionValue[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-variant products still carry one synthetic option — `Title` with the
|
||||
* lone value `Default Title`. It isn't a real choice, so keep it out of the UI.
|
||||
*/
|
||||
export const isDefaultTitleOption = (option: {
|
||||
name: string;
|
||||
values: string[];
|
||||
}): boolean =>
|
||||
option.name === 'Title' &&
|
||||
option.values.length === 1 &&
|
||||
option.values[0] === 'Default Title';
|
||||
|
||||
/** Same synthetic option, as it appears on a variant's `selectedOptions`. */
|
||||
export const isDefaultTitleSelection = (selection: {
|
||||
name: string;
|
||||
value: string;
|
||||
}): boolean =>
|
||||
selection.name === 'Title' && selection.value === 'Default Title';
|
||||
|
||||
export interface Product {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
descriptionHtml?: string;
|
||||
handle: string;
|
||||
images: {
|
||||
edges: Array<{
|
||||
node: ProductImage;
|
||||
}>;
|
||||
};
|
||||
priceRange: {
|
||||
minVariantPrice: ProductPrice;
|
||||
};
|
||||
compareAtPriceRange?: {
|
||||
minVariantPrice: ProductPrice;
|
||||
};
|
||||
variants: {
|
||||
edges: Array<{
|
||||
node: ProductVariant;
|
||||
}>;
|
||||
};
|
||||
options: ProductOption[];
|
||||
}
|
||||
|
||||
interface UseProductsOptions {
|
||||
first?: number;
|
||||
/** Cursor from a previous page's `endCursor`; omit for the first page. */
|
||||
after?: string | null;
|
||||
query?: string;
|
||||
sortKey?: 'BEST_SELLING' | 'CREATED_AT' | 'PRICE' | 'TITLE';
|
||||
reverse?: boolean;
|
||||
}
|
||||
|
||||
export interface ProductsPage {
|
||||
products: Product[];
|
||||
hasNextPage: boolean;
|
||||
endCursor: string | null;
|
||||
}
|
||||
|
||||
interface UseProductsReturn {
|
||||
products: Product[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refetch: () => Promise<void>;
|
||||
}
|
||||
|
||||
// Fetch multiple products
|
||||
export async function getProducts(
|
||||
options: UseProductsOptions = {}
|
||||
): Promise<Product[]> {
|
||||
const { products } = await getProductsPage(options);
|
||||
return products;
|
||||
}
|
||||
|
||||
// Same fetch, but keeps the cursor so callers can page through the catalogue.
|
||||
export async function getProductsPage({
|
||||
first = 20,
|
||||
after = null,
|
||||
query = '',
|
||||
sortKey = 'BEST_SELLING',
|
||||
reverse = false,
|
||||
}: UseProductsOptions = {}): Promise<ProductsPage> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(GET_PRODUCTS_QUERY, {
|
||||
variables: { first, after, query, sortKey, reverse },
|
||||
}),
|
||||
'GetProducts'
|
||||
);
|
||||
|
||||
const { edges, pageInfo } = data.products;
|
||||
|
||||
return {
|
||||
products: edges.map((edge: { node: Product }) => edge.node),
|
||||
hasNextPage: Boolean(pageInfo?.hasNextPage),
|
||||
endCursor: pageInfo?.endCursor ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// Fetch a single product by handle
|
||||
export async function getProduct(handle: string): Promise<Product | null> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(GET_PRODUCT_QUERY, { variables: { handle } }),
|
||||
'GetProduct'
|
||||
);
|
||||
|
||||
return data.product;
|
||||
}
|
||||
|
||||
// Fetch product recommendations
|
||||
export async function getProductRecommendations(productId: string): Promise<Product[]> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(QUERY_PRODUCT_RECOMMENDATIONS, {
|
||||
variables: { productId },
|
||||
}),
|
||||
'GetProductRecommendations'
|
||||
);
|
||||
|
||||
return data.productRecommendations ?? [];
|
||||
}
|
||||
|
||||
|
||||
interface CollectionImage {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
}
|
||||
|
||||
export interface Collection {
|
||||
id: string;
|
||||
title: string;
|
||||
handle: string;
|
||||
description?: string;
|
||||
descriptionHtml?: string;
|
||||
image?: CollectionImage | null;
|
||||
}
|
||||
|
||||
export interface CollectionWithProducts extends Collection {
|
||||
products: Product[];
|
||||
}
|
||||
|
||||
export type CollectionSortKey =
|
||||
| 'COLLECTION_DEFAULT'
|
||||
| 'BEST_SELLING'
|
||||
| 'CREATED'
|
||||
| 'PRICE'
|
||||
| 'TITLE';
|
||||
|
||||
interface UseCollectionProductsOptions {
|
||||
first?: number;
|
||||
after?: string | null;
|
||||
sortKey?: CollectionSortKey;
|
||||
reverse?: boolean;
|
||||
/** Raw `input` strings from the connection's `filters` facets. */
|
||||
filterInputs?: string[];
|
||||
}
|
||||
|
||||
export interface CollectionProductsPage {
|
||||
collection: Collection | null;
|
||||
products: Product[];
|
||||
filters: ProductFilterFacet[];
|
||||
hasNextPage: boolean;
|
||||
endCursor: string | null;
|
||||
}
|
||||
|
||||
export interface ProductFilterFacet {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'LIST' | 'PRICE_RANGE' | 'BOOLEAN';
|
||||
values: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
count: number;
|
||||
input: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
// Fetch all collections
|
||||
export async function getCollections(first = 50): Promise<Collection[]> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(GET_COLLECTIONS_QUERY, { variables: { first } }),
|
||||
'GetCollections'
|
||||
);
|
||||
|
||||
return data.collections.edges.map((edge) => edge.node);
|
||||
}
|
||||
|
||||
// Fetch products in a collection by handle
|
||||
export async function getCollectionProducts(
|
||||
handle: string,
|
||||
options: UseCollectionProductsOptions = {}
|
||||
): Promise<CollectionWithProducts | null> {
|
||||
const page = await getCollectionProductsPage(handle, options);
|
||||
if (!page.collection) return null;
|
||||
|
||||
return { ...page.collection, products: page.products };
|
||||
}
|
||||
|
||||
// Same fetch, but keeps the cursor and facet list for filtering and paging.
|
||||
export async function getCollectionProductsPage(
|
||||
handle: string,
|
||||
{
|
||||
first = 50,
|
||||
after = null,
|
||||
sortKey = 'COLLECTION_DEFAULT',
|
||||
reverse = false,
|
||||
filterInputs = [],
|
||||
}: UseCollectionProductsOptions = {}
|
||||
): Promise<CollectionProductsPage> {
|
||||
const filters = parseFilterInputs(filterInputs);
|
||||
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(GET_COLLECTION_PRODUCTS_QUERY, {
|
||||
variables: {
|
||||
handle,
|
||||
first,
|
||||
after,
|
||||
sortKey,
|
||||
reverse,
|
||||
filters: filters.length ? filters : null,
|
||||
},
|
||||
}),
|
||||
'GetCollectionProducts'
|
||||
);
|
||||
|
||||
const collection = data.collection;
|
||||
if (!collection) {
|
||||
return {
|
||||
collection: null,
|
||||
products: [],
|
||||
filters: [],
|
||||
hasNextPage: false,
|
||||
endCursor: null,
|
||||
};
|
||||
}
|
||||
|
||||
const { edges, pageInfo, filters: facets } = collection.products;
|
||||
|
||||
return {
|
||||
collection,
|
||||
products: edges.map((edge: { node: Product }) => edge.node),
|
||||
filters: facets ?? [],
|
||||
hasNextPage: Boolean(pageInfo?.hasNextPage),
|
||||
endCursor: pageInfo?.endCursor ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export type SearchSortKey = 'RELEVANCE' | 'PRICE';
|
||||
|
||||
export interface SearchFilterValue {
|
||||
id: string;
|
||||
label: string;
|
||||
count: number;
|
||||
/** JSON string accepted back as a `ProductFilter` input. */
|
||||
input: string;
|
||||
}
|
||||
|
||||
export interface SearchFilter {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'LIST' | 'PRICE_RANGE' | 'BOOLEAN';
|
||||
values: SearchFilterValue[];
|
||||
}
|
||||
|
||||
export interface SearchProductsResult {
|
||||
products: Product[];
|
||||
totalCount: number;
|
||||
filters: SearchFilter[];
|
||||
hasNextPage: boolean;
|
||||
endCursor: string | null;
|
||||
}
|
||||
|
||||
export interface SearchSuggestion {
|
||||
id: string;
|
||||
title: string;
|
||||
handle: string;
|
||||
featuredImage?: {
|
||||
url: string;
|
||||
altText?: string | null;
|
||||
} | null;
|
||||
priceRange: {
|
||||
minVariantPrice: {
|
||||
amount: string;
|
||||
currencyCode: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface SearchProductsOptions {
|
||||
query: string;
|
||||
first?: number;
|
||||
after?: string | null;
|
||||
sortKey?: SearchSortKey;
|
||||
reverse?: boolean;
|
||||
/** Raw `input` strings from the facets, parsed back into filter objects. */
|
||||
filterInputs?: string[];
|
||||
}
|
||||
|
||||
// The `ProductFilter` input shape, taken from the query that consumes it so it
|
||||
// tracks the schema rather than being restated here.
|
||||
type ProductFilterInput = NonNullable<
|
||||
StorefrontApi.VariablesOf<typeof GET_COLLECTION_PRODUCTS_QUERY>['filters']
|
||||
>[number];
|
||||
|
||||
// Facet `input` values are opaque JSON strings produced by Shopify and handed
|
||||
// straight back as filter inputs, so they are parsed, not constructed.
|
||||
function parseFilterInputs(inputs: string[]): ProductFilterInput[] {
|
||||
return inputs.flatMap((input) => {
|
||||
try {
|
||||
return [JSON.parse(input) as ProductFilterInput];
|
||||
} catch {
|
||||
console.warn('Ignoring malformed product filter input:', input);
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function searchProducts({
|
||||
query,
|
||||
first = 24,
|
||||
after = null,
|
||||
sortKey = 'RELEVANCE',
|
||||
reverse = false,
|
||||
filterInputs = [],
|
||||
}: SearchProductsOptions): Promise<SearchProductsResult> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(SEARCH_PRODUCTS_QUERY, {
|
||||
variables: {
|
||||
query,
|
||||
first,
|
||||
after,
|
||||
sortKey,
|
||||
reverse,
|
||||
productFilters: filterInputs.length
|
||||
? parseFilterInputs(filterInputs)
|
||||
: null,
|
||||
},
|
||||
}),
|
||||
'SearchProducts'
|
||||
);
|
||||
|
||||
const search = data.search;
|
||||
|
||||
return {
|
||||
products: search.edges
|
||||
.map((edge) => edge.node)
|
||||
.filter((node): node is Extract<typeof node, { __typename: 'Product' }> =>
|
||||
node.__typename === 'Product'
|
||||
),
|
||||
totalCount: search.totalCount ?? 0,
|
||||
filters: search.productFilters ?? [],
|
||||
hasNextPage: Boolean(search.pageInfo?.hasNextPage),
|
||||
endCursor: search.pageInfo?.endCursor ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchSuggestions(
|
||||
query: string,
|
||||
first = 3
|
||||
): Promise<{ products: SearchSuggestion[]; totalCount: number }> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(SEARCH_SUGGESTIONS_QUERY, {
|
||||
variables: { query, first },
|
||||
}),
|
||||
'SearchSuggestions'
|
||||
);
|
||||
|
||||
const search = data.search;
|
||||
|
||||
return {
|
||||
products: search.edges
|
||||
.map((edge) => edge.node)
|
||||
.filter((node): node is Extract<typeof node, { __typename: 'Product' }> =>
|
||||
node.__typename === 'Product'
|
||||
),
|
||||
totalCount: search.totalCount ?? 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Storefront API clients, built on `@shopify/hydrogen`.
|
||||
//
|
||||
// Call sites use the package's own API — `storefront.graphql(DOCUMENT, {
|
||||
// variables })` — and pass the result through `unwrapStorefrontResult`, which
|
||||
// applies this app's error policy: fail loudly. Hydrogen deliberately does not
|
||||
// do that itself, because a 200 carrying partial data and GraphQL errors is a
|
||||
// valid response that some callers want to render.
|
||||
import {
|
||||
createShopifyRequestContext,
|
||||
createStorefrontClient,
|
||||
type GraphQLFormattedError,
|
||||
} from '@shopify/hydrogen';
|
||||
import {
|
||||
SHOPIFY_API_VERSION,
|
||||
SHOPIFY_PUBLIC_ACCESS_TOKEN,
|
||||
SHOPIFY_STORE_DOMAIN,
|
||||
} from '@/services/shopify/config';
|
||||
|
||||
// No incoming request and no buyer context: this client is module-scoped and
|
||||
// serves both the Hono API and the browser-side hooks, so it must not close
|
||||
// over per-request state. `$country`/`$language` are injected from this i18n.
|
||||
const requestContext = createShopifyRequestContext({
|
||||
request: { headers: new Headers() },
|
||||
i18n: { country: 'US', language: 'EN' },
|
||||
});
|
||||
|
||||
/**
|
||||
* Workaround for a bug in this preview build of `@shopify/hydrogen`.
|
||||
*
|
||||
* The client tags every request with `X-Hydrogen-Version`, but the Storefront
|
||||
* API does not list that header in its CORS `access-control-allow-headers`.
|
||||
* Browsers therefore reject the preflight and `fetch` throws, which hydrogen
|
||||
* reports as the generic "SFAPI request failed". It only bites against real
|
||||
* stores — `mock.shop` answers `access-control-allow-headers: *`.
|
||||
*
|
||||
* Stripped in the browser only: server-side requests are not subject to CORS,
|
||||
* so they keep sending the header. Remove this once the API allows it (or once
|
||||
* these queries move server-side, which is the better long-term fix).
|
||||
*/
|
||||
const CORS_BLOCKED_HEADERS = ['X-Hydrogen-Version'];
|
||||
|
||||
const storefrontFetch = ((url, init) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
for (const header of CORS_BLOCKED_HEADERS) headers.delete(header);
|
||||
}
|
||||
|
||||
return globalThis.fetch(url, { ...init, cache: 'no-store', headers });
|
||||
}) as typeof globalThis.fetch;
|
||||
|
||||
/**
|
||||
* The one Storefront client. Uncached at the HTTP layer, because carts and
|
||||
* customer reads must never serve a stale response — response caching for
|
||||
* catalogue data happens in TanStack Query instead (see `staleTime`s).
|
||||
*/
|
||||
export const storefront = createStorefrontClient({
|
||||
type: 'public',
|
||||
requestContext,
|
||||
config: {
|
||||
storeDomain: SHOPIFY_STORE_DOMAIN!,
|
||||
apiVersion: SHOPIFY_API_VERSION,
|
||||
publicStorefrontToken: SHOPIFY_PUBLIC_ACCESS_TOKEN,
|
||||
fetch: storefrontFetch,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the data from a `graphql()` result, throwing if Shopify reported any
|
||||
* GraphQL errors. Transport failures — non-200, timeouts, unparseable bodies —
|
||||
* have already thrown as `StorefrontApiError` by this point.
|
||||
*
|
||||
* `operation` names the query in the log and the thrown message, so a failure
|
||||
* points at the call site rather than just at "Shopify".
|
||||
*/
|
||||
export function unwrapStorefrontResult<TData>(
|
||||
result: { data: TData | null; errors?: GraphQLFormattedError[] },
|
||||
operation: string
|
||||
): TData {
|
||||
if (result.errors?.length) {
|
||||
console.error(`Shopify GraphQL errors (${operation}):`, result.errors);
|
||||
throw new Error(
|
||||
`Shopify GraphQL errors (${operation}): ${JSON.stringify(result.errors)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (result.data == null) {
|
||||
throw new Error(`Shopify returned no data for ${operation}.`);
|
||||
}
|
||||
|
||||
return result.data;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Storefront configuration, read from the environment in one place.
|
||||
//
|
||||
// These are all `VITE_*`, so Vite inlines them at build time and they are safe
|
||||
// to read from the browser bundle as well as the Hono server.
|
||||
export const SHOPIFY_STORE_DOMAIN = import.meta.env.VITE_SHOPIFY_DOMAIN;
|
||||
|
||||
/**
|
||||
* Public Storefront API access token. Safe to expose to the browser — that is
|
||||
* what "public" means here. Omitted for tokenless storefronts such as
|
||||
* `mock.shop`. Never put a *private* token behind a `VITE_` name.
|
||||
*/
|
||||
export const SHOPIFY_PUBLIC_ACCESS_TOKEN = import.meta.env
|
||||
.VITE_SHOPIFY_PUBLIC_ACCESS_TOKEN;
|
||||
|
||||
export const SHOPIFY_API_VERSION =
|
||||
import.meta.env.VITE_SHOPIFY_API_VERSION || '2026-07';
|
||||
@@ -0,0 +1,248 @@
|
||||
// Server-safe customer account access.
|
||||
//
|
||||
// The customer access token is a credential: it is only ever handled here and
|
||||
// in the /api/account route handlers, and is stored in an httpOnly cookie so
|
||||
// client JavaScript can never read it.
|
||||
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
|
||||
import {
|
||||
CUSTOMER_QUERY,
|
||||
CUSTOMER_CREATE_MUTATION,
|
||||
CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION,
|
||||
CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION,
|
||||
CUSTOMER_RECOVER_MUTATION,
|
||||
CUSTOMER_RESET_MUTATION,
|
||||
CUSTOMER_ACTIVATE_MUTATION,
|
||||
CUSTOMER_UPDATE_MUTATION,
|
||||
} from '@/graphql/customer';
|
||||
|
||||
export const CUSTOMER_TOKEN_COOKIE = 'customerAccessToken';
|
||||
|
||||
export interface CustomerUserError {
|
||||
/** One of `CustomerErrorCode`; kept as a string so new codes don't break. */
|
||||
code?: string | null;
|
||||
field?: string[] | null;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface CustomerAddress {
|
||||
id: string;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
address1?: string | null;
|
||||
address2?: string | null;
|
||||
city?: string | null;
|
||||
province?: string | null;
|
||||
zip?: string | null;
|
||||
country?: string | null;
|
||||
phone?: string | null;
|
||||
}
|
||||
|
||||
export interface CustomerOrder {
|
||||
id: string;
|
||||
orderNumber: number;
|
||||
processedAt: string;
|
||||
financialStatus?: string | null;
|
||||
fulfillmentStatus?: string | null;
|
||||
statusUrl?: string | null;
|
||||
currentTotalPrice: { amount: string; currencyCode: string };
|
||||
lineItems: {
|
||||
edges: Array<{
|
||||
node: {
|
||||
title: string;
|
||||
quantity: number;
|
||||
variant?: { image?: { url: string; altText?: string | null } | null } | null;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Customer {
|
||||
id: string;
|
||||
email: string | null;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
phone?: string | null;
|
||||
displayName: string;
|
||||
acceptsMarketing?: boolean;
|
||||
createdAt?: string;
|
||||
defaultAddress?: CustomerAddress | null;
|
||||
orders?: { edges: Array<{ node: CustomerOrder }> };
|
||||
}
|
||||
|
||||
export interface AccessToken {
|
||||
accessToken: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
/** Either a token (success) or the errors Shopify reported. */
|
||||
export interface AuthResult {
|
||||
token: AccessToken | null;
|
||||
errors: CustomerUserError[];
|
||||
}
|
||||
|
||||
const firstMessage = (errors: CustomerUserError[]) =>
|
||||
errors[0]?.message ?? 'Something went wrong. Please try again.';
|
||||
|
||||
export { firstMessage as customerErrorMessage };
|
||||
|
||||
// Shopify returns a null mutation payload when the mutation could not run at
|
||||
// all. That is not a success, so it surfaces as a generic error rather than an
|
||||
// empty error list, which callers read as "it worked".
|
||||
const MUTATION_FAILED: CustomerUserError[] = [
|
||||
{ message: 'Something went wrong. Please try again.' },
|
||||
];
|
||||
|
||||
export async function createCustomer(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
acceptsMarketing?: boolean;
|
||||
}): Promise<{ errors: CustomerUserError[] }> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CUSTOMER_CREATE_MUTATION, {
|
||||
variables: { input },
|
||||
}),
|
||||
'CustomerCreate'
|
||||
);
|
||||
|
||||
const result = data.customerCreate;
|
||||
if (!result) return { errors: MUTATION_FAILED };
|
||||
|
||||
return { errors: result.customerUserErrors ?? [] };
|
||||
}
|
||||
|
||||
export async function login(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION, {
|
||||
variables: { input: { email, password } },
|
||||
}),
|
||||
'CustomerAccessTokenCreate'
|
||||
);
|
||||
|
||||
const result = data.customerAccessTokenCreate;
|
||||
if (!result) return { token: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function logout(accessToken: string): Promise<void> {
|
||||
try {
|
||||
await storefront.graphql(CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION, {
|
||||
variables: { customerAccessToken: accessToken },
|
||||
});
|
||||
} catch (err) {
|
||||
// The cookie is cleared regardless; a failed revoke shouldn't block logout.
|
||||
console.error('Failed to revoke customer access token:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Always resolves without error detail: revealing whether an address exists
|
||||
// would leak account membership.
|
||||
export async function recoverPassword(email: string): Promise<void> {
|
||||
try {
|
||||
await storefront.graphql(CUSTOMER_RECOVER_MUTATION, {
|
||||
variables: { email },
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Password recovery request failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function resetPassword(
|
||||
id: string,
|
||||
resetToken: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CUSTOMER_RESET_MUTATION, {
|
||||
variables: { id, input: { resetToken, password } },
|
||||
}),
|
||||
'CustomerReset'
|
||||
);
|
||||
|
||||
const result = data.customerReset;
|
||||
if (!result) return { token: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function activateAccount(
|
||||
id: string,
|
||||
activationToken: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CUSTOMER_ACTIVATE_MUTATION, {
|
||||
variables: { id, input: { activationToken, password } },
|
||||
}),
|
||||
'CustomerActivate'
|
||||
);
|
||||
|
||||
const result = data.customerActivate;
|
||||
if (!result) return { token: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCustomer(
|
||||
accessToken: string,
|
||||
orderCount = 10
|
||||
): Promise<Customer | null> {
|
||||
try {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CUSTOMER_QUERY, {
|
||||
variables: { customerAccessToken: accessToken, orderCount },
|
||||
}),
|
||||
'GetCustomer'
|
||||
);
|
||||
|
||||
return data.customer ?? null;
|
||||
} catch (err) {
|
||||
// An expired or revoked token reads as "not signed in".
|
||||
console.error('Failed to load customer:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateCustomer(
|
||||
accessToken: string,
|
||||
customer: {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
}
|
||||
): Promise<{ customer: Customer | null; errors: CustomerUserError[] }> {
|
||||
const data = unwrapStorefrontResult(
|
||||
await storefront.graphql(CUSTOMER_UPDATE_MUTATION, {
|
||||
variables: { customerAccessToken: accessToken, customer },
|
||||
}),
|
||||
'CustomerUpdate'
|
||||
);
|
||||
|
||||
const result = data.customerUpdate;
|
||||
if (!result) return { customer: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
customer: result.customer ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
// Shopify's emailed links carry a numeric id; the mutations want a GID.
|
||||
export function toCustomerGid(id: string): string {
|
||||
return id.startsWith('gid://') ? id : `gid://shopify/Customer/${id}`;
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
@import 'tailwindcss';
|
||||
@import '@fontsource-variable/geist';
|
||||
@import '@fontsource-variable/geist-mono';
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme {
|
||||
/* Refined neutral modern palette */
|
||||
--color-background: hsl(0 0% 100%);
|
||||
--color-foreground: hsl(240 10% 3.9%);
|
||||
|
||||
/* Card */
|
||||
--color-card: hsl(0 0% 100%);
|
||||
--color-card-foreground: hsl(240 10% 3.9%);
|
||||
|
||||
/* Popover */
|
||||
--color-popover: hsl(0 0% 100%);
|
||||
--color-popover-foreground: hsl(240 10% 3.9%);
|
||||
|
||||
/* Primary - Deep neutral slate for professional look */
|
||||
--color-primary: hsl(240 5.9% 10%);
|
||||
--color-primary-foreground: hsl(0 0% 98%);
|
||||
|
||||
/* Secondary */
|
||||
--color-secondary: hsl(240 4.8% 95.9%);
|
||||
--color-secondary-foreground: hsl(240 5.9% 10%);
|
||||
|
||||
/* Muted */
|
||||
--color-muted: hsl(240 4.8% 95.9%);
|
||||
--color-muted-foreground: hsl(240 3.8% 46.1%);
|
||||
|
||||
/* Accent - Subtle warm gray */
|
||||
--color-accent: hsl(30 6.7% 95%);
|
||||
--color-accent-foreground: hsl(240 5.9% 10%);
|
||||
|
||||
/* Destructive */
|
||||
--color-destructive: hsl(0 84.2% 60.2%);
|
||||
--color-destructive-foreground: hsl(0 0% 98%);
|
||||
|
||||
/* Shop (accelerated checkout) purple */
|
||||
--color-shop: #5a31f4;
|
||||
|
||||
/* Border */
|
||||
--color-border: hsl(240 5.9% 90%);
|
||||
--color-input: hsl(240 5.9% 90%);
|
||||
--color-ring: hsl(240 5.9% 10%);
|
||||
|
||||
/* Radius - Modern larger corners */
|
||||
--radius-sm: 0.5rem;
|
||||
--radius-md: 0.75rem;
|
||||
--radius-lg: 1rem;
|
||||
--radius-xl: 1.25rem;
|
||||
|
||||
/* Typography — Geist Sans / Geist Mono */
|
||||
--font-sans: 'Geist Variable', system-ui, sans-serif;
|
||||
--font-mono: 'Geist Mono Variable', ui-monospace, SFMono-Regular, monospace;
|
||||
--font-heading: 'Geist Variable', system-ui, sans-serif;
|
||||
--font-body: 'Geist Variable', system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* Base styles for light, modern Shopify storefront */
|
||||
/* Tailwind v4 defaults an unqualified `border` to currentColor. shadcn
|
||||
components (e.g. Button's outline variant) rely on this base layer to pick up
|
||||
the theme's border colour instead of the text colour. */
|
||||
@layer base {
|
||||
* {
|
||||
border-color: var(--color-border);
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
font-feature-settings:
|
||||
'kern' 1,
|
||||
'tnum' 1;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
/* Modern card design for products and collections */
|
||||
.card-modern {
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.card-modern:hover {
|
||||
transform: translateY(-8px);
|
||||
box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.1);
|
||||
border-color: hsl(240 5.9% 85%);
|
||||
}
|
||||
|
||||
/* Heading styles — regular weight, slightly tightened like the Geist reference */
|
||||
h1,
|
||||
h2,
|
||||
.font-heading {
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
/* Swipeable rows (mobile galleries) without a visible scrollbar */
|
||||
.no-scrollbar {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Diagonal strike marking an unavailable product option (size pill, swatch) */
|
||||
.option-unavailable {
|
||||
background-image: linear-gradient(
|
||||
to top right,
|
||||
transparent calc(50% - 0.5px),
|
||||
currentColor calc(50% - 0.5px),
|
||||
currentColor calc(50% + 0.5px),
|
||||
transparent calc(50% + 0.5px)
|
||||
);
|
||||
}
|
||||
|
||||
/* Product description (HTML returned by the Storefront API) */
|
||||
.product-description p {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.product-description > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* Shop policy body (HTML returned by the Storefront API) */
|
||||
.policy-body p,
|
||||
.policy-body ul,
|
||||
.policy-body ol {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.policy-body ul,
|
||||
.policy-body ol {
|
||||
padding-left: 1.25rem;
|
||||
list-style: revert;
|
||||
}
|
||||
|
||||
.policy-body li {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.policy-body h2,
|
||||
.policy-body h3,
|
||||
.policy-body h4 {
|
||||
margin-top: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.policy-body a {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.policy-body strong {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.policy-body > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* Enhanced button styles */
|
||||
button,
|
||||
.btn-modern {
|
||||
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.btn-modern:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow:
|
||||
0 10px 15px -3px rgb(0 0 0 / 0.1),
|
||||
0 4px 6px -4px rgb(0 0 0 / 0.1);
|
||||
}
|
||||
|
||||
/* Hero section styles */
|
||||
.hero-bg {
|
||||
background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f5 100%);
|
||||
}
|
||||
|
||||
/* Product gallery improvements */
|
||||
.product-gallery-main {
|
||||
transition: box-shadow 0.3s ease;
|
||||
}
|
||||
|
||||
.product-gallery-main:hover {
|
||||
box-shadow: 0 0 0 1px hsl(240 5.9% 80%) inset;
|
||||
}
|
||||
|
||||
/* Clean price display */
|
||||
.price-display {
|
||||
font-feature-settings: 'tnum';
|
||||
}
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_SHOPIFY_DOMAIN?: string;
|
||||
readonly VITE_SHOPIFY_PUBLIC_ACCESS_TOKEN?: string;
|
||||
readonly VITE_SHOPIFY_API_VERSION?: string;
|
||||
readonly VITE_SITE_URL?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"types": ["vite/client", "node"],
|
||||
"plugins": [{ "name": "@shopify/hydrogen/ts-plugin" }],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src", "server", "vite.config.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { tanstackRouter } from '@tanstack/router-plugin/vite';
|
||||
import devServer from '@hono/vite-dev-server';
|
||||
import { fileURLToPath, URL } from 'node:url';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
// Must run before the React plugin so the generated route tree is in place.
|
||||
tanstackRouter({ target: 'react', autoCodeSplitting: true }),
|
||||
react(),
|
||||
tailwindcss(),
|
||||
// Serves the Hono API in dev. Everything outside /api falls through to
|
||||
// Vite, which serves the SPA.
|
||||
devServer({
|
||||
entry: 'server/app.ts',
|
||||
exclude: [/^(?!\/api(\/|$)).*/],
|
||||
injectClientScript: false,
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist/client',
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user