Features: 1) Next.js storefront
14
.claude/settings.local.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(cat:*)",
|
||||
"Bash(xargs:*)",
|
||||
"Bash(grep:*)",
|
||||
"Bash(npx create-next-app@latest . --typescript --tailwind --eslint --app --src-dir --import-alias \"@/*\" --use-npm --yes)",
|
||||
"Bash(npm install:*)",
|
||||
"Bash(npx shadcn@latest init:*)",
|
||||
"Bash(npx shadcn@latest add:*)",
|
||||
"Bash(npm run build:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -1,38 +1,72 @@
|
|||
# syntax=docker/dockerfile:1
|
||||
FROM node:22-bookworm-slim AS build
|
||||
FROM node:22-bookworm-slim AS base
|
||||
|
||||
# Install dependencies only when needed
|
||||
FROM base AS deps
|
||||
WORKDIR /app
|
||||
|
||||
ARG EVIBES_BASE_DOMAIN
|
||||
ARG EVIBES_PROJECT_NAME
|
||||
ENV EVIBES_BASE_DOMAIN=$EVIBES_BASE_DOMAIN
|
||||
ENV EVIBES_PROJECT_NAME=$EVIBES_PROJECT_NAME
|
||||
|
||||
# Copy package files
|
||||
COPY ./storefront/package.json ./storefront/package-lock.json ./
|
||||
RUN npm ci --include=optional
|
||||
|
||||
COPY ./storefront ./
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-bookworm-slim AS runtime
|
||||
# Rebuild the source code only when needed
|
||||
FROM base AS builder
|
||||
WORKDIR /app
|
||||
|
||||
# Build arguments for environment variables needed at build time
|
||||
ARG NEXT_PUBLIC_API_URL
|
||||
ARG NEXT_PUBLIC_SITE_URL
|
||||
ARG NEXT_PUBLIC_PROJECT_NAME
|
||||
ARG NEXT_PUBLIC_BASE_DOMAIN
|
||||
ARG EVIBES_BASE_DOMAIN
|
||||
ARG EVIBES_PROJECT_NAME
|
||||
|
||||
# Set build-time environment variables
|
||||
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL
|
||||
ENV NEXT_PUBLIC_PROJECT_NAME=${NEXT_PUBLIC_PROJECT_NAME:-$EVIBES_PROJECT_NAME}
|
||||
ENV NEXT_PUBLIC_BASE_DOMAIN=${NEXT_PUBLIC_BASE_DOMAIN:-$EVIBES_BASE_DOMAIN}
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY ./storefront ./
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# Production image, copy all the files and run next
|
||||
FROM base AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=3000
|
||||
|
||||
# Install curl for health checks
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN addgroup --system --gid 1001 nodeapp \
|
||||
&& adduser --system --uid 1001 --ingroup nodeapp --home /home/nodeapp nodeapp
|
||||
USER nodeapp
|
||||
# Create non-root user
|
||||
RUN addgroup --system --gid 1001 nodejs \
|
||||
&& adduser --system --uid 1001 --ingroup nodejs nextjs
|
||||
|
||||
COPY --from=build /app/.output/ ./
|
||||
# Copy built application
|
||||
COPY --from=builder /app/public ./public
|
||||
|
||||
RUN install -d -m 0755 -o nodeapp -g nodeapp /home/nodeapp \
|
||||
&& printf '#!/bin/sh\nif [ \"$DEBUG\" = \"1\" ]; then export NODE_ENV=development; else export NODE_ENV=production; fi\nexec node /app/server/index.mjs\n' > /home/nodeapp/start.sh \
|
||||
&& chown nodeapp:nodeapp /home/nodeapp/start.sh \
|
||||
&& chmod +x /home/nodeapp/start.sh
|
||||
# Set the correct permission for prerender cache
|
||||
RUN mkdir .next
|
||||
RUN chown nextjs:nodejs .next
|
||||
|
||||
USER nodeapp
|
||||
CMD ["sh", "/home/nodeapp/start.sh"]
|
||||
# Automatically leverage output traces to reduce image size
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
USER nextjs
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
|
||||
CMD curl -f http://localhost:3000/ || exit 1
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
|
|
|
|||
|
|
@ -223,22 +223,31 @@ services:
|
|||
context: .
|
||||
dockerfile: Dockerfiles/storefront.Dockerfile
|
||||
args:
|
||||
- DEBUG=${DEBUG}
|
||||
- NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-http://app:8000}
|
||||
- NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-http://localhost:3000}
|
||||
- NEXT_PUBLIC_PROJECT_NAME=${EVIBES_PROJECT_NAME}
|
||||
- NEXT_PUBLIC_BASE_DOMAIN=${EVIBES_BASE_DOMAIN}
|
||||
- EVIBES_BASE_DOMAIN=${EVIBES_BASE_DOMAIN}
|
||||
- EVIBES_PROJECT_NAME=${EVIBES_PROJECT_NAME}
|
||||
restart: always
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- NUXT_HOST=0.0.0.0
|
||||
- NUXT_PORT=3000
|
||||
- NUXT_DEVTOOLS_ENABLED=${DEBUG}
|
||||
- NODE_ENV=production
|
||||
- NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-http://app:8000}
|
||||
- NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-http://localhost:3000}
|
||||
- NEXT_PUBLIC_PROJECT_NAME=${EVIBES_PROJECT_NAME}
|
||||
- NEXT_PUBLIC_BASE_DOMAIN=${EVIBES_BASE_DOMAIN}
|
||||
ports:
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
app:
|
||||
condition: service_started
|
||||
logging: *default-logging
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:3000/"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
36
storefront/README.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
22
storefront/components.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"registries": {}
|
||||
}
|
||||
18
storefront/eslint.config.mjs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
311
storefront/messages/en.json
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
{
|
||||
"common": {
|
||||
"loading": "Loading...",
|
||||
"error": "An error occurred",
|
||||
"retry": "Try again",
|
||||
"save": "Save",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"search": "Search",
|
||||
"searchPlaceholder": "Search products...",
|
||||
"noResults": "No results found",
|
||||
"viewAll": "View all",
|
||||
"seeMore": "See more",
|
||||
"currency": "USD",
|
||||
"addToCart": "Add to cart",
|
||||
"addedToCart": "Added to cart",
|
||||
"removeFromCart": "Remove from cart",
|
||||
"addToWishlist": "Add to wishlist",
|
||||
"removeFromWishlist": "Remove from wishlist",
|
||||
"buyNow": "Buy now",
|
||||
"outOfStock": "Out of stock",
|
||||
"inStock": "In stock",
|
||||
"quantity": "Quantity",
|
||||
"price": "Price",
|
||||
"total": "Total",
|
||||
"subtotal": "Subtotal",
|
||||
"shipping": "Shipping",
|
||||
"tax": "Tax",
|
||||
"discount": "Discount",
|
||||
"free": "Free",
|
||||
"apply": "Apply",
|
||||
"promoCode": "Promo code",
|
||||
"enterPromoCode": "Enter promo code",
|
||||
"invalidPromoCode": "Invalid promo code",
|
||||
"promoApplied": "Promo code applied",
|
||||
"backToShopping": "Back to shopping",
|
||||
"continueShopping": "Continue shopping"
|
||||
},
|
||||
"nav": {
|
||||
"home": "Home",
|
||||
"catalog": "Catalog",
|
||||
"categories": "Categories",
|
||||
"brands": "Brands",
|
||||
"sale": "Sale",
|
||||
"new": "New arrivals",
|
||||
"blog": "Blog",
|
||||
"about": "About us",
|
||||
"contact": "Contact",
|
||||
"account": "My Account",
|
||||
"orders": "My Orders",
|
||||
"wishlist": "Wishlist",
|
||||
"cart": "Cart",
|
||||
"login": "Login",
|
||||
"register": "Register",
|
||||
"logout": "Logout"
|
||||
},
|
||||
"home": {
|
||||
"hero": {
|
||||
"title": "Welcome to {storeName}",
|
||||
"subtitle": "Discover amazing products at great prices",
|
||||
"cta": "Shop now"
|
||||
},
|
||||
"featured": {
|
||||
"title": "Featured Products",
|
||||
"subtitle": "Check out our top picks"
|
||||
},
|
||||
"categories": {
|
||||
"title": "Shop by Category",
|
||||
"subtitle": "Browse our collections"
|
||||
},
|
||||
"newArrivals": {
|
||||
"title": "New Arrivals",
|
||||
"subtitle": "Fresh products just for you"
|
||||
},
|
||||
"bestSellers": {
|
||||
"title": "Best Sellers",
|
||||
"subtitle": "Most popular products"
|
||||
},
|
||||
"promotions": {
|
||||
"title": "Special Offers",
|
||||
"subtitle": "Don't miss out on these deals"
|
||||
}
|
||||
},
|
||||
"product": {
|
||||
"description": "Description",
|
||||
"specifications": "Specifications",
|
||||
"reviews": "Reviews",
|
||||
"relatedProducts": "Related Products",
|
||||
"sku": "SKU",
|
||||
"brand": "Brand",
|
||||
"category": "Category",
|
||||
"tags": "Tags",
|
||||
"availability": "Availability",
|
||||
"shareProduct": "Share this product",
|
||||
"writeReview": "Write a review",
|
||||
"rating": "Rating",
|
||||
"noReviews": "No reviews yet",
|
||||
"reviewsCount": "{count} reviews",
|
||||
"selectOptions": "Select options",
|
||||
"addReview": {
|
||||
"title": "Add your review",
|
||||
"rating": "Your rating",
|
||||
"comment": "Your review",
|
||||
"submit": "Submit review",
|
||||
"success": "Review submitted successfully",
|
||||
"error": "Failed to submit review"
|
||||
}
|
||||
},
|
||||
"catalog": {
|
||||
"title": "Products",
|
||||
"filters": "Filters",
|
||||
"clearFilters": "Clear all",
|
||||
"sortBy": "Sort by",
|
||||
"sortOptions": {
|
||||
"newest": "Newest",
|
||||
"oldest": "Oldest",
|
||||
"priceAsc": "Price: Low to High",
|
||||
"priceDesc": "Price: High to Low",
|
||||
"nameAsc": "Name: A-Z",
|
||||
"nameDesc": "Name: Z-A",
|
||||
"popular": "Most Popular",
|
||||
"rating": "Highest Rated"
|
||||
},
|
||||
"priceRange": "Price range",
|
||||
"minPrice": "Min price",
|
||||
"maxPrice": "Max price",
|
||||
"showingResults": "Showing {count} products",
|
||||
"noProducts": "No products found",
|
||||
"loadMore": "Load more"
|
||||
},
|
||||
"cart": {
|
||||
"title": "Shopping Cart",
|
||||
"empty": "Your cart is empty",
|
||||
"emptyMessage": "Looks like you haven't added any items to your cart yet.",
|
||||
"items": "{count} items",
|
||||
"item": "{count} item",
|
||||
"updateQuantity": "Update quantity",
|
||||
"remove": "Remove",
|
||||
"clear": "Clear cart",
|
||||
"checkout": "Proceed to checkout",
|
||||
"orderSummary": "Order Summary",
|
||||
"estimatedTotal": "Estimated Total"
|
||||
},
|
||||
"checkout": {
|
||||
"title": "Checkout",
|
||||
"steps": {
|
||||
"shipping": "Shipping",
|
||||
"payment": "Payment",
|
||||
"review": "Review",
|
||||
"confirmation": "Confirmation"
|
||||
},
|
||||
"shippingAddress": "Shipping Address",
|
||||
"billingAddress": "Billing Address",
|
||||
"sameAsShipping": "Same as shipping address",
|
||||
"shippingMethod": "Shipping Method",
|
||||
"paymentMethod": "Payment Method",
|
||||
"orderReview": "Review Your Order",
|
||||
"placeOrder": "Place Order",
|
||||
"processing": "Processing...",
|
||||
"orderPlaced": "Order Placed Successfully!",
|
||||
"orderNumber": "Order Number",
|
||||
"orderConfirmation": "You will receive a confirmation email shortly.",
|
||||
"form": {
|
||||
"firstName": "First Name",
|
||||
"lastName": "Last Name",
|
||||
"email": "Email",
|
||||
"phone": "Phone",
|
||||
"address": "Address",
|
||||
"address2": "Apartment, suite, etc. (optional)",
|
||||
"city": "City",
|
||||
"state": "State/Province",
|
||||
"postalCode": "Postal Code",
|
||||
"country": "Country"
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
"login": {
|
||||
"title": "Sign In",
|
||||
"subtitle": "Welcome back! Please sign in to your account.",
|
||||
"email": "Email",
|
||||
"password": "Password",
|
||||
"rememberMe": "Remember me",
|
||||
"forgotPassword": "Forgot password?",
|
||||
"submit": "Sign In",
|
||||
"noAccount": "Don't have an account?",
|
||||
"createAccount": "Create one",
|
||||
"error": "Invalid email or password"
|
||||
},
|
||||
"register": {
|
||||
"title": "Create Account",
|
||||
"subtitle": "Join us and start shopping!",
|
||||
"firstName": "First Name",
|
||||
"lastName": "Last Name",
|
||||
"email": "Email",
|
||||
"password": "Password",
|
||||
"confirmPassword": "Confirm Password",
|
||||
"acceptTerms": "I accept the terms and conditions",
|
||||
"submit": "Create Account",
|
||||
"hasAccount": "Already have an account?",
|
||||
"signIn": "Sign in",
|
||||
"success": "Account created successfully!",
|
||||
"error": "Failed to create account"
|
||||
},
|
||||
"forgotPassword": {
|
||||
"title": "Forgot Password",
|
||||
"subtitle": "Enter your email to reset your password",
|
||||
"email": "Email",
|
||||
"submit": "Send Reset Link",
|
||||
"success": "Reset link sent to your email",
|
||||
"backToLogin": "Back to login"
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "Reset Password",
|
||||
"newPassword": "New Password",
|
||||
"confirmPassword": "Confirm Password",
|
||||
"submit": "Reset Password",
|
||||
"success": "Password reset successfully"
|
||||
}
|
||||
},
|
||||
"account": {
|
||||
"title": "My Account",
|
||||
"profile": {
|
||||
"title": "Profile",
|
||||
"personalInfo": "Personal Information",
|
||||
"updateProfile": "Update Profile",
|
||||
"changePassword": "Change Password",
|
||||
"currentPassword": "Current Password",
|
||||
"newPassword": "New Password",
|
||||
"confirmPassword": "Confirm Password"
|
||||
},
|
||||
"orders": {
|
||||
"title": "My Orders",
|
||||
"empty": "You haven't placed any orders yet.",
|
||||
"orderNumber": "Order #{number}",
|
||||
"date": "Date",
|
||||
"status": "Status",
|
||||
"total": "Total",
|
||||
"viewDetails": "View Details",
|
||||
"trackOrder": "Track Order",
|
||||
"reorder": "Reorder",
|
||||
"statuses": {
|
||||
"pending": "Pending",
|
||||
"processing": "Processing",
|
||||
"shipped": "Shipped",
|
||||
"delivered": "Delivered",
|
||||
"cancelled": "Cancelled",
|
||||
"refunded": "Refunded"
|
||||
}
|
||||
},
|
||||
"addresses": {
|
||||
"title": "Addresses",
|
||||
"addNew": "Add New Address",
|
||||
"edit": "Edit Address",
|
||||
"delete": "Delete Address",
|
||||
"setDefault": "Set as Default",
|
||||
"default": "Default",
|
||||
"empty": "No addresses saved yet."
|
||||
},
|
||||
"wishlist": {
|
||||
"title": "Wishlist",
|
||||
"empty": "Your wishlist is empty.",
|
||||
"emptyMessage": "Save items you love to your wishlist.",
|
||||
"moveToCart": "Move to Cart"
|
||||
}
|
||||
},
|
||||
"footer": {
|
||||
"about": {
|
||||
"title": "About Us",
|
||||
"description": "Your trusted online store for quality products."
|
||||
},
|
||||
"customerService": {
|
||||
"title": "Customer Service",
|
||||
"contactUs": "Contact Us",
|
||||
"shippingInfo": "Shipping Information",
|
||||
"returns": "Returns & Exchanges",
|
||||
"faq": "FAQ"
|
||||
},
|
||||
"legal": {
|
||||
"title": "Legal",
|
||||
"privacy": "Privacy Policy",
|
||||
"terms": "Terms of Service",
|
||||
"cookies": "Cookie Policy"
|
||||
},
|
||||
"social": {
|
||||
"title": "Follow Us"
|
||||
},
|
||||
"newsletter": {
|
||||
"title": "Newsletter",
|
||||
"description": "Subscribe to get updates on new products and offers.",
|
||||
"placeholder": "Enter your email",
|
||||
"subscribe": "Subscribe",
|
||||
"success": "Thanks for subscribing!"
|
||||
},
|
||||
"copyright": "All rights reserved."
|
||||
},
|
||||
"errors": {
|
||||
"404": {
|
||||
"title": "Page Not Found",
|
||||
"message": "The page you're looking for doesn't exist or has been moved.",
|
||||
"backHome": "Go to Homepage"
|
||||
},
|
||||
"500": {
|
||||
"title": "Server Error",
|
||||
"message": "Something went wrong on our end. Please try again later."
|
||||
},
|
||||
"network": "Network error. Please check your connection.",
|
||||
"unauthorized": "Please sign in to continue.",
|
||||
"forbidden": "You don't have permission to access this resource."
|
||||
}
|
||||
}
|
||||
311
storefront/messages/ru.json
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
{
|
||||
"common": {
|
||||
"loading": "Загрузка...",
|
||||
"error": "Произошла ошибка",
|
||||
"retry": "Попробовать снова",
|
||||
"save": "Сохранить",
|
||||
"cancel": "Отмена",
|
||||
"delete": "Удалить",
|
||||
"edit": "Редактировать",
|
||||
"search": "Поиск",
|
||||
"searchPlaceholder": "Поиск товаров...",
|
||||
"noResults": "Ничего не найдено",
|
||||
"viewAll": "Смотреть все",
|
||||
"seeMore": "Показать ещё",
|
||||
"currency": "RUB",
|
||||
"addToCart": "В корзину",
|
||||
"addedToCart": "Добавлено в корзину",
|
||||
"removeFromCart": "Удалить из корзины",
|
||||
"addToWishlist": "В избранное",
|
||||
"removeFromWishlist": "Удалить из избранного",
|
||||
"buyNow": "Купить сейчас",
|
||||
"outOfStock": "Нет в наличии",
|
||||
"inStock": "В наличии",
|
||||
"quantity": "Количество",
|
||||
"price": "Цена",
|
||||
"total": "Итого",
|
||||
"subtotal": "Подытог",
|
||||
"shipping": "Доставка",
|
||||
"tax": "Налог",
|
||||
"discount": "Скидка",
|
||||
"free": "Бесплатно",
|
||||
"apply": "Применить",
|
||||
"promoCode": "Промокод",
|
||||
"enterPromoCode": "Введите промокод",
|
||||
"invalidPromoCode": "Неверный промокод",
|
||||
"promoApplied": "Промокод применён",
|
||||
"backToShopping": "Вернуться к покупкам",
|
||||
"continueShopping": "Продолжить покупки"
|
||||
},
|
||||
"nav": {
|
||||
"home": "Главная",
|
||||
"catalog": "Каталог",
|
||||
"categories": "Категории",
|
||||
"brands": "Бренды",
|
||||
"sale": "Распродажа",
|
||||
"new": "Новинки",
|
||||
"blog": "Блог",
|
||||
"about": "О нас",
|
||||
"contact": "Контакты",
|
||||
"account": "Личный кабинет",
|
||||
"orders": "Мои заказы",
|
||||
"wishlist": "Избранное",
|
||||
"cart": "Корзина",
|
||||
"login": "Войти",
|
||||
"register": "Регистрация",
|
||||
"logout": "Выйти"
|
||||
},
|
||||
"home": {
|
||||
"hero": {
|
||||
"title": "Добро пожаловать в {storeName}",
|
||||
"subtitle": "Откройте для себя удивительные товары по отличным ценам",
|
||||
"cta": "За покупками"
|
||||
},
|
||||
"featured": {
|
||||
"title": "Рекомендуемые товары",
|
||||
"subtitle": "Наш лучший выбор для вас"
|
||||
},
|
||||
"categories": {
|
||||
"title": "Категории",
|
||||
"subtitle": "Просмотрите наши коллекции"
|
||||
},
|
||||
"newArrivals": {
|
||||
"title": "Новинки",
|
||||
"subtitle": "Свежие поступления"
|
||||
},
|
||||
"bestSellers": {
|
||||
"title": "Хиты продаж",
|
||||
"subtitle": "Самые популярные товары"
|
||||
},
|
||||
"promotions": {
|
||||
"title": "Специальные предложения",
|
||||
"subtitle": "Не упустите выгодные акции"
|
||||
}
|
||||
},
|
||||
"product": {
|
||||
"description": "Описание",
|
||||
"specifications": "Характеристики",
|
||||
"reviews": "Отзывы",
|
||||
"relatedProducts": "Похожие товары",
|
||||
"sku": "Артикул",
|
||||
"brand": "Бренд",
|
||||
"category": "Категория",
|
||||
"tags": "Теги",
|
||||
"availability": "Наличие",
|
||||
"shareProduct": "Поделиться",
|
||||
"writeReview": "Написать отзыв",
|
||||
"rating": "Рейтинг",
|
||||
"noReviews": "Отзывов пока нет",
|
||||
"reviewsCount": "{count} отзывов",
|
||||
"selectOptions": "Выберите опции",
|
||||
"addReview": {
|
||||
"title": "Добавить отзыв",
|
||||
"rating": "Ваша оценка",
|
||||
"comment": "Ваш отзыв",
|
||||
"submit": "Отправить отзыв",
|
||||
"success": "Отзыв успешно отправлен",
|
||||
"error": "Не удалось отправить отзыв"
|
||||
}
|
||||
},
|
||||
"catalog": {
|
||||
"title": "Товары",
|
||||
"filters": "Фильтры",
|
||||
"clearFilters": "Сбросить все",
|
||||
"sortBy": "Сортировка",
|
||||
"sortOptions": {
|
||||
"newest": "Сначала новые",
|
||||
"oldest": "Сначала старые",
|
||||
"priceAsc": "Цена: по возрастанию",
|
||||
"priceDesc": "Цена: по убыванию",
|
||||
"nameAsc": "Название: А-Я",
|
||||
"nameDesc": "Название: Я-А",
|
||||
"popular": "По популярности",
|
||||
"rating": "По рейтингу"
|
||||
},
|
||||
"priceRange": "Диапазон цен",
|
||||
"minPrice": "Мин. цена",
|
||||
"maxPrice": "Макс. цена",
|
||||
"showingResults": "Показано {count} товаров",
|
||||
"noProducts": "Товары не найдены",
|
||||
"loadMore": "Загрузить ещё"
|
||||
},
|
||||
"cart": {
|
||||
"title": "Корзина",
|
||||
"empty": "Ваша корзина пуста",
|
||||
"emptyMessage": "Похоже, вы ещё не добавили товары в корзину.",
|
||||
"items": "{count} товаров",
|
||||
"item": "{count} товар",
|
||||
"updateQuantity": "Изменить количество",
|
||||
"remove": "Удалить",
|
||||
"clear": "Очистить корзину",
|
||||
"checkout": "Оформить заказ",
|
||||
"orderSummary": "Сумма заказа",
|
||||
"estimatedTotal": "Предварительный итог"
|
||||
},
|
||||
"checkout": {
|
||||
"title": "Оформление заказа",
|
||||
"steps": {
|
||||
"shipping": "Доставка",
|
||||
"payment": "Оплата",
|
||||
"review": "Проверка",
|
||||
"confirmation": "Подтверждение"
|
||||
},
|
||||
"shippingAddress": "Адрес доставки",
|
||||
"billingAddress": "Платёжный адрес",
|
||||
"sameAsShipping": "Совпадает с адресом доставки",
|
||||
"shippingMethod": "Способ доставки",
|
||||
"paymentMethod": "Способ оплаты",
|
||||
"orderReview": "Проверьте ваш заказ",
|
||||
"placeOrder": "Оформить заказ",
|
||||
"processing": "Обработка...",
|
||||
"orderPlaced": "Заказ успешно оформлен!",
|
||||
"orderNumber": "Номер заказа",
|
||||
"orderConfirmation": "Вы получите письмо с подтверждением.",
|
||||
"form": {
|
||||
"firstName": "Имя",
|
||||
"lastName": "Фамилия",
|
||||
"email": "Email",
|
||||
"phone": "Телефон",
|
||||
"address": "Адрес",
|
||||
"address2": "Квартира, подъезд и т.д. (необязательно)",
|
||||
"city": "Город",
|
||||
"state": "Область/Регион",
|
||||
"postalCode": "Почтовый индекс",
|
||||
"country": "Страна"
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
"login": {
|
||||
"title": "Вход",
|
||||
"subtitle": "С возвращением! Войдите в свой аккаунт.",
|
||||
"email": "Email",
|
||||
"password": "Пароль",
|
||||
"rememberMe": "Запомнить меня",
|
||||
"forgotPassword": "Забыли пароль?",
|
||||
"submit": "Войти",
|
||||
"noAccount": "Нет аккаунта?",
|
||||
"createAccount": "Создать",
|
||||
"error": "Неверный email или пароль"
|
||||
},
|
||||
"register": {
|
||||
"title": "Регистрация",
|
||||
"subtitle": "Присоединяйтесь к нам!",
|
||||
"firstName": "Имя",
|
||||
"lastName": "Фамилия",
|
||||
"email": "Email",
|
||||
"password": "Пароль",
|
||||
"confirmPassword": "Подтвердите пароль",
|
||||
"acceptTerms": "Я принимаю условия использования",
|
||||
"submit": "Создать аккаунт",
|
||||
"hasAccount": "Уже есть аккаунт?",
|
||||
"signIn": "Войти",
|
||||
"success": "Аккаунт успешно создан!",
|
||||
"error": "Не удалось создать аккаунт"
|
||||
},
|
||||
"forgotPassword": {
|
||||
"title": "Восстановление пароля",
|
||||
"subtitle": "Введите email для сброса пароля",
|
||||
"email": "Email",
|
||||
"submit": "Отправить ссылку",
|
||||
"success": "Ссылка отправлена на ваш email",
|
||||
"backToLogin": "Вернуться ко входу"
|
||||
},
|
||||
"resetPassword": {
|
||||
"title": "Сброс пароля",
|
||||
"newPassword": "Новый пароль",
|
||||
"confirmPassword": "Подтвердите пароль",
|
||||
"submit": "Сбросить пароль",
|
||||
"success": "Пароль успешно изменён"
|
||||
}
|
||||
},
|
||||
"account": {
|
||||
"title": "Личный кабинет",
|
||||
"profile": {
|
||||
"title": "Профиль",
|
||||
"personalInfo": "Личная информация",
|
||||
"updateProfile": "Обновить профиль",
|
||||
"changePassword": "Изменить пароль",
|
||||
"currentPassword": "Текущий пароль",
|
||||
"newPassword": "Новый пароль",
|
||||
"confirmPassword": "Подтвердите пароль"
|
||||
},
|
||||
"orders": {
|
||||
"title": "Мои заказы",
|
||||
"empty": "У вас пока нет заказов.",
|
||||
"orderNumber": "Заказ #{number}",
|
||||
"date": "Дата",
|
||||
"status": "Статус",
|
||||
"total": "Сумма",
|
||||
"viewDetails": "Подробнее",
|
||||
"trackOrder": "Отследить",
|
||||
"reorder": "Повторить заказ",
|
||||
"statuses": {
|
||||
"pending": "Ожидает",
|
||||
"processing": "Обрабатывается",
|
||||
"shipped": "Отправлен",
|
||||
"delivered": "Доставлен",
|
||||
"cancelled": "Отменён",
|
||||
"refunded": "Возвращён"
|
||||
}
|
||||
},
|
||||
"addresses": {
|
||||
"title": "Адреса",
|
||||
"addNew": "Добавить адрес",
|
||||
"edit": "Редактировать",
|
||||
"delete": "Удалить",
|
||||
"setDefault": "Сделать основным",
|
||||
"default": "Основной",
|
||||
"empty": "Адреса не сохранены."
|
||||
},
|
||||
"wishlist": {
|
||||
"title": "Избранное",
|
||||
"empty": "Список избранного пуст.",
|
||||
"emptyMessage": "Сохраняйте понравившиеся товары.",
|
||||
"moveToCart": "В корзину"
|
||||
}
|
||||
},
|
||||
"footer": {
|
||||
"about": {
|
||||
"title": "О нас",
|
||||
"description": "Ваш надёжный интернет-магазин качественных товаров."
|
||||
},
|
||||
"customerService": {
|
||||
"title": "Обслуживание клиентов",
|
||||
"contactUs": "Связаться с нами",
|
||||
"shippingInfo": "Информация о доставке",
|
||||
"returns": "Возврат и обмен",
|
||||
"faq": "Частые вопросы"
|
||||
},
|
||||
"legal": {
|
||||
"title": "Правовая информация",
|
||||
"privacy": "Политика конфиденциальности",
|
||||
"terms": "Условия использования",
|
||||
"cookies": "Политика cookie"
|
||||
},
|
||||
"social": {
|
||||
"title": "Мы в соцсетях"
|
||||
},
|
||||
"newsletter": {
|
||||
"title": "Рассылка",
|
||||
"description": "Подпишитесь на новости и специальные предложения.",
|
||||
"placeholder": "Введите ваш email",
|
||||
"subscribe": "Подписаться",
|
||||
"success": "Спасибо за подписку!"
|
||||
},
|
||||
"copyright": "Все права защищены."
|
||||
},
|
||||
"errors": {
|
||||
"404": {
|
||||
"title": "Страница не найдена",
|
||||
"message": "Страница, которую вы ищете, не существует или была перемещена.",
|
||||
"backHome": "На главную"
|
||||
},
|
||||
"500": {
|
||||
"title": "Ошибка сервера",
|
||||
"message": "Что-то пошло не так. Пожалуйста, попробуйте позже."
|
||||
},
|
||||
"network": "Ошибка сети. Проверьте подключение.",
|
||||
"unauthorized": "Пожалуйста, войдите для продолжения.",
|
||||
"forbidden": "У вас нет доступа к этому ресурсу."
|
||||
}
|
||||
}
|
||||
35
storefront/next.config.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import type { NextConfig } from "next";
|
||||
import createNextIntlPlugin from "next-intl/plugin";
|
||||
|
||||
const withNextIntl = createNextIntlPlugin();
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "**",
|
||||
},
|
||||
{
|
||||
protocol: "http",
|
||||
hostname: "localhost",
|
||||
},
|
||||
{
|
||||
protocol: "http",
|
||||
hostname: "app",
|
||||
},
|
||||
],
|
||||
},
|
||||
env: {
|
||||
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || "https://api.itoption.ru",
|
||||
NEXT_PUBLIC_SITE_URL:
|
||||
process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000",
|
||||
NEXT_PUBLIC_PROJECT_NAME:
|
||||
process.env.EVIBES_PROJECT_NAME || process.env.NEXT_PUBLIC_PROJECT_NAME || "eVibes",
|
||||
NEXT_PUBLIC_BASE_DOMAIN:
|
||||
process.env.EVIBES_BASE_DOMAIN || process.env.NEXT_PUBLIC_BASE_DOMAIN || "localhost",
|
||||
},
|
||||
};
|
||||
|
||||
export default withNextIntl(nextConfig);
|
||||
8830
storefront/package-lock.json
generated
Normal file
55
storefront/package.json
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "storefront",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@radix-ui/react-accordion": "^1.2.12",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.14",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-radio-group": "^1.3.8",
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@tanstack/react-query": "^5.90.12",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"lucide-react": "^0.561.0",
|
||||
"next": "16.0.10",
|
||||
"next-intl": "^4.6.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "19.2.1",
|
||||
"react-dom": "19.2.1",
|
||||
"react-hook-form": "^7.68.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"zod": "^4.2.0",
|
||||
"zustand": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.0.10",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
7
storefront/postcss.config.mjs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
1
storefront/public/file.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
1
storefront/public/globe.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1 KiB |
1
storefront/public/next.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
6
storefront/public/placeholder.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">
|
||||
<rect width="400" height="400" fill="#f3f4f6"/>
|
||||
<rect x="120" y="120" width="160" height="160" fill="#e5e7eb" rx="8"/>
|
||||
<path d="M160 200 L200 240 L240 180" stroke="#9ca3af" stroke-width="8" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="180" cy="160" r="16" fill="#9ca3af"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 404 B |
1
storefront/public/vercel.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
1
storefront/public/window.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
147
storefront/src/app/[locale]/account/orders/page.tsx
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { Package, Eye, ArrowLeft } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useAuthStore } from "@/stores";
|
||||
import { ordersApi } from "@/lib/api/endpoints";
|
||||
import { formatPrice, formatDate } from "@/lib/utils";
|
||||
import type { Order } from "@/lib/api/types";
|
||||
|
||||
export default function OrdersPage() {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const { isAuthenticated } = useAuthStore();
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
router.push("/login?redirect=/account/orders");
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchOrders = async () => {
|
||||
try {
|
||||
const response = await ordersApi.getAll();
|
||||
setOrders(response.results || []);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch orders:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchOrders();
|
||||
}, [isAuthenticated, router]);
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const statusConfig: Record<string, { variant: "default" | "secondary" | "destructive" | "outline"; label: string }> = {
|
||||
pending: { variant: "outline", label: t("account.orders.statuses.pending") },
|
||||
processing: { variant: "secondary", label: t("account.orders.statuses.processing") },
|
||||
shipped: { variant: "default", label: t("account.orders.statuses.shipped") },
|
||||
delivered: { variant: "default", label: t("account.orders.statuses.delivered") },
|
||||
cancelled: { variant: "destructive", label: t("account.orders.statuses.cancelled") },
|
||||
refunded: { variant: "destructive", label: t("account.orders.statuses.refunded") },
|
||||
};
|
||||
|
||||
const config = statusConfig[status] || { variant: "outline" as const, label: status };
|
||||
return <Badge variant={config.variant}>{config.label}</Badge>;
|
||||
};
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<div className="mb-8">
|
||||
<Button variant="ghost" asChild className="mb-4">
|
||||
<Link href="/account">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{t("account.title")}
|
||||
</Link>
|
||||
</Button>
|
||||
<h1 className="text-3xl font-bold">{t("account.orders.title")}</h1>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
<Skeleton className="h-9 w-24" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : orders.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<Package className="h-16 w-16 text-muted-foreground" />
|
||||
<h2 className="mt-4 text-xl font-semibold">
|
||||
{t("account.orders.empty")}
|
||||
</h2>
|
||||
<Button asChild className="mt-6">
|
||||
<Link href="/catalog">{t("common.continueShopping")}</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{orders.map((order) => (
|
||||
<Card key={order.id}>
|
||||
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
|
||||
<div>
|
||||
<CardTitle className="text-base">
|
||||
{t("account.orders.orderNumber", {
|
||||
number: order.order_number,
|
||||
})}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{formatDate(order.created_at)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{getStatusBadge(order.status)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{order.items?.length || 0} items
|
||||
</p>
|
||||
<p className="font-medium">{formatPrice(order.total)}</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href={`/account/orders/${order.id}`}>
|
||||
<Eye className="mr-2 h-4 w-4" />
|
||||
{t("account.orders.viewDetails")}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
142
storefront/src/app/[locale]/account/page.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import {
|
||||
User,
|
||||
Package,
|
||||
MapPin,
|
||||
Heart,
|
||||
Settings,
|
||||
LogOut,
|
||||
ChevronRight,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { useAuthStore } from "@/stores";
|
||||
|
||||
export default function AccountPage() {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const { user, isAuthenticated, logout, fetchProfile } = useAuthStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
router.push("/login?redirect=/account");
|
||||
} else {
|
||||
fetchProfile();
|
||||
}
|
||||
}, [isAuthenticated, router, fetchProfile]);
|
||||
|
||||
if (!isAuthenticated || !user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const menuItems = [
|
||||
{
|
||||
icon: User,
|
||||
label: t("account.profile.title"),
|
||||
description: t("account.profile.personalInfo"),
|
||||
href: "/account/profile",
|
||||
},
|
||||
{
|
||||
icon: Package,
|
||||
label: t("account.orders.title"),
|
||||
description: t("account.orders.empty"),
|
||||
href: "/account/orders",
|
||||
},
|
||||
{
|
||||
icon: MapPin,
|
||||
label: t("account.addresses.title"),
|
||||
description: t("account.addresses.empty"),
|
||||
href: "/account/addresses",
|
||||
},
|
||||
{
|
||||
icon: Heart,
|
||||
label: t("account.wishlist.title"),
|
||||
description: t("account.wishlist.emptyMessage"),
|
||||
href: "/wishlist",
|
||||
},
|
||||
];
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
router.push("/");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<h1 className="mb-8 text-3xl font-bold">{t("account.title")}</h1>
|
||||
|
||||
<div className="grid gap-8 md:grid-cols-3">
|
||||
{/* Profile card */}
|
||||
<Card className="md:col-span-1">
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<Avatar className="h-20 w-20">
|
||||
<AvatarImage src={user.avatar} alt={user.first_name} />
|
||||
<AvatarFallback className="text-xl">
|
||||
{user.first_name?.charAt(0)}
|
||||
{user.last_name?.charAt(0)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<h2 className="mt-4 text-xl font-semibold">
|
||||
{user.first_name} {user.last_name}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground">{user.email}</p>
|
||||
|
||||
<div className="mt-6 w-full space-y-2">
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<Link href="/account/profile">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
{t("account.profile.updateProfile")}
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full text-destructive hover:text-destructive"
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
{t("nav.logout")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Menu items */}
|
||||
<div className="space-y-4 md:col-span-2">
|
||||
{menuItems.map((item) => (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<Card className="transition-colors hover:bg-accent">
|
||||
<CardContent className="flex items-center gap-4 p-4">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
|
||||
<item.icon className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="font-medium">{item.label}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{item.description}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-muted-foreground" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
99
storefront/src/app/[locale]/blog/page.tsx
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import type { Metadata } from "next";
|
||||
import Image from "next/image";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { serverBlogApi } from "@/lib/api/endpoints";
|
||||
import { getImageUrl, formatDate } from "@/lib/utils";
|
||||
import type { BlogPost } from "@/lib/api/types";
|
||||
|
||||
interface BlogPageProps {
|
||||
params: Promise<{ locale: string }>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: BlogPageProps): Promise<Metadata> {
|
||||
const { locale } = await params;
|
||||
return {
|
||||
title: locale === "ru" ? "Блог" : "Blog",
|
||||
description:
|
||||
locale === "ru" ? "Наши последние статьи и новости" : "Our latest articles and news",
|
||||
};
|
||||
}
|
||||
|
||||
export default async function BlogPage({ params }: BlogPageProps) {
|
||||
const { locale } = await params;
|
||||
setRequestLocale(locale);
|
||||
|
||||
const t = await getTranslations();
|
||||
|
||||
let posts: BlogPost[] = [];
|
||||
try {
|
||||
const response = await serverBlogApi.getPosts(locale);
|
||||
posts = response.results || [];
|
||||
} catch {
|
||||
// Continue with empty posts
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold">{t("nav.blog")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{locale === "ru"
|
||||
? "Наши последние статьи и новости"
|
||||
: "Our latest articles and news"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{posts.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{locale === "ru" ? "Статьи скоро появятся" : "Posts coming soon"}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{posts.map((post) => (
|
||||
<Link key={post.id} href={`/blog/${post.slug}`}>
|
||||
<Card className="h-full overflow-hidden transition-all hover:shadow-lg">
|
||||
{post.featured_image && (
|
||||
<div className="relative aspect-video">
|
||||
<Image
|
||||
src={getImageUrl(post.featured_image)}
|
||||
alt={post.title}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<CardHeader>
|
||||
<div className="flex flex-wrap gap-2 mb-2">
|
||||
{post.tags?.map((tag) => (
|
||||
<Badge key={tag.id} variant="secondary">
|
||||
{tag.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
<CardTitle className="line-clamp-2">{post.title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{post.excerpt && (
|
||||
<p className="line-clamp-3 text-muted-foreground">
|
||||
{post.excerpt}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-4 text-sm text-muted-foreground">
|
||||
{formatDate(post.published_at || post.created_at, locale)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
225
storefront/src/app/[locale]/cart/page.tsx
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import Image from "next/image";
|
||||
import { Minus, Plus, Trash2, ShoppingBag, ArrowRight } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useCartStore } from "@/stores";
|
||||
import { formatPrice, getImageUrl } from "@/lib/utils";
|
||||
|
||||
export default function CartPage() {
|
||||
const t = useTranslations();
|
||||
const { items, removeItem, updateQuantity, clearCart, getSubtotal } =
|
||||
useCartStore();
|
||||
|
||||
const subtotal = getSubtotal();
|
||||
const shipping = 0; // Free shipping or calculate based on location
|
||||
const total = subtotal + shipping;
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="container py-16">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<ShoppingBag className="mx-auto h-16 w-16 text-muted-foreground" />
|
||||
<h1 className="mt-6 text-2xl font-bold">{t("cart.empty")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">{t("cart.emptyMessage")}</p>
|
||||
<Button asChild className="mt-6">
|
||||
<Link href="/catalog">
|
||||
{t("common.continueShopping")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<h1 className="mb-8 text-3xl font-bold">{t("cart.title")}</h1>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
{/* Cart items */}
|
||||
<div className="lg:col-span-2">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle>
|
||||
{items.length} {items.length === 1 ? t("cart.item", { count: 1 }) : t("cart.items", { count: items.length })}
|
||||
</CardTitle>
|
||||
<Button variant="ghost" size="sm" onClick={clearCart}>
|
||||
{t("cart.clear")}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{items.map((item) => {
|
||||
const price = item.product.sale_price
|
||||
? parseFloat(item.product.sale_price)
|
||||
: parseFloat(item.product.price);
|
||||
const primaryImage =
|
||||
item.product.images?.find((img) => img.is_primary) ||
|
||||
item.product.images?.[0];
|
||||
|
||||
return (
|
||||
<div key={item.product.id}>
|
||||
<div className="flex gap-4">
|
||||
{/* Image */}
|
||||
<div className="relative h-24 w-24 flex-shrink-0 overflow-hidden rounded-md border">
|
||||
{primaryImage ? (
|
||||
<Image
|
||||
src={getImageUrl(primaryImage.image)}
|
||||
alt={primaryImage.alt_text || item.product.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center bg-muted">
|
||||
<ShoppingBag className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Details */}
|
||||
<div className="flex flex-1 flex-col">
|
||||
<div className="flex justify-between">
|
||||
<div>
|
||||
<Link
|
||||
href={`/product/${item.product.slug}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{item.product.name}
|
||||
</Link>
|
||||
{item.product.brand && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{item.product.brand.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => removeItem(item.product.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-auto flex items-center justify-between">
|
||||
{/* Quantity */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() =>
|
||||
updateQuantity(
|
||||
item.product.id,
|
||||
item.quantity - 1
|
||||
)
|
||||
}
|
||||
disabled={item.quantity <= 1}
|
||||
>
|
||||
<Minus className="h-3 w-3" />
|
||||
</Button>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={item.quantity}
|
||||
onChange={(e) =>
|
||||
updateQuantity(
|
||||
item.product.id,
|
||||
parseInt(e.target.value) || 1
|
||||
)
|
||||
}
|
||||
className="h-8 w-14 text-center"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() =>
|
||||
updateQuantity(
|
||||
item.product.id,
|
||||
item.quantity + 1
|
||||
)
|
||||
}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="text-right">
|
||||
<p className="font-medium">
|
||||
{formatPrice(price * item.quantity)}
|
||||
</p>
|
||||
{item.quantity > 1 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{formatPrice(price)} each
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Separator className="mt-4" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Order summary */}
|
||||
<div>
|
||||
<Card className="sticky top-20">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("cart.orderSummary")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Promo code */}
|
||||
<div className="flex gap-2">
|
||||
<Input placeholder={t("common.enterPromoCode")} />
|
||||
<Button variant="outline">{t("common.apply")}</Button>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Totals */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">{t("common.subtotal")}</span>
|
||||
<span>{formatPrice(subtotal)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">{t("common.shipping")}</span>
|
||||
<span>{shipping === 0 ? t("common.free") : formatPrice(shipping)}</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-medium">
|
||||
<span>{t("cart.estimatedTotal")}</span>
|
||||
<span>{formatPrice(total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-2">
|
||||
<Button asChild className="w-full" size="lg">
|
||||
<Link href="/checkout">
|
||||
{t("cart.checkout")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<Link href="/catalog">{t("common.continueShopping")}</Link>
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
123
storefront/src/app/[locale]/catalog/[slug]/page.tsx
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { CatalogContent } from "../catalog-content";
|
||||
import {
|
||||
serverProductsApi,
|
||||
serverCategoriesApi,
|
||||
serverBrandsApi,
|
||||
} from "@/lib/api/endpoints";
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
|
||||
interface CategoryPageProps {
|
||||
params: Promise<{ locale: string; slug: string }>;
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: CategoryPageProps): Promise<Metadata> {
|
||||
const { locale, slug } = await params;
|
||||
|
||||
try {
|
||||
const category = await serverCategoriesApi.getBySlug(locale, slug);
|
||||
return {
|
||||
title: category.name,
|
||||
description: category.description || `${category.name} - browse our collection`,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
title: locale === "ru" ? "Категория" : "Category",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default async function CategoryPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: CategoryPageProps) {
|
||||
const { locale, slug } = await params;
|
||||
const search = await searchParams;
|
||||
setRequestLocale(locale);
|
||||
|
||||
const t = await getTranslations();
|
||||
|
||||
let category;
|
||||
try {
|
||||
category = await serverCategoriesApi.getBySlug(locale, slug);
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Parse search params
|
||||
const filters = {
|
||||
category: slug,
|
||||
search: search.search as string | undefined,
|
||||
brand: search.brand as string | undefined,
|
||||
min_price: search.min_price ? Number(search.min_price) : undefined,
|
||||
max_price: search.max_price ? Number(search.max_price) : undefined,
|
||||
is_on_sale: search.is_on_sale === "true",
|
||||
is_new: search.is_new === "true",
|
||||
ordering: (search.ordering as string) || "-created_at",
|
||||
page: search.page ? Number(search.page) : 1,
|
||||
page_size: 12,
|
||||
};
|
||||
|
||||
// Fetch data in parallel
|
||||
const [productsData, categoriesData, brandsData] = await Promise.all([
|
||||
serverProductsApi.getAll(locale, filters).catch(() => ({ results: [], count: 0 })),
|
||||
serverCategoriesApi.getAll(locale).catch(() => ({ results: [] })),
|
||||
serverBrandsApi.getAll(locale).catch(() => ({ results: [] })),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
{/* Breadcrumb */}
|
||||
<Breadcrumb className="mb-6">
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href="/">{t("nav.home")}</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href="/catalog">{t("nav.catalog")}</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbPage>{category.name}</BreadcrumbPage>
|
||||
</BreadcrumbItem>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold">{category.name}</h1>
|
||||
{category.description && (
|
||||
<p className="mt-2 text-muted-foreground">{category.description}</p>
|
||||
)}
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{t("catalog.showingResults", { count: productsData.count || 0 })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CatalogContent
|
||||
initialProducts={productsData.results || []}
|
||||
totalCount={productsData.count || 0}
|
||||
categories={categoriesData.results || []}
|
||||
brands={brandsData.results || []}
|
||||
initialFilters={filters}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
485
storefront/src/app/[locale]/catalog/catalog-content.tsx
Normal file
|
|
@ -0,0 +1,485 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { usePathname } from "@/i18n/navigation";
|
||||
import { Filter, SlidersHorizontal, X, ChevronDown } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/ui/sheet";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ProductGrid } from "@/components/products";
|
||||
import { productsApi } from "@/lib/api/endpoints";
|
||||
import type { Product, Category, Brand, ProductFilters } from "@/lib/api/types";
|
||||
import { cn, debounce } from "@/lib/utils";
|
||||
|
||||
interface CatalogContentProps {
|
||||
initialProducts: Product[];
|
||||
totalCount: number;
|
||||
categories: Category[];
|
||||
brands: Brand[];
|
||||
initialFilters: ProductFilters;
|
||||
}
|
||||
|
||||
export function CatalogContent({
|
||||
initialProducts,
|
||||
totalCount,
|
||||
categories,
|
||||
brands,
|
||||
initialFilters,
|
||||
}: CatalogContentProps) {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [products, setProducts] = useState<Product[]>(initialProducts);
|
||||
const [count, setCount] = useState(totalCount);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [filters, setFilters] = useState<ProductFilters>(initialFilters);
|
||||
const [isFilterOpen, setIsFilterOpen] = useState(false);
|
||||
|
||||
const sortOptions = [
|
||||
{ value: "-created_at", label: t("catalog.sortOptions.newest") },
|
||||
{ value: "created_at", label: t("catalog.sortOptions.oldest") },
|
||||
{ value: "price", label: t("catalog.sortOptions.priceAsc") },
|
||||
{ value: "-price", label: t("catalog.sortOptions.priceDesc") },
|
||||
{ value: "name", label: t("catalog.sortOptions.nameAsc") },
|
||||
{ value: "-name", label: t("catalog.sortOptions.nameDesc") },
|
||||
];
|
||||
|
||||
const updateUrl = useCallback(
|
||||
(newFilters: ProductFilters) => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
Object.entries(newFilters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== "" && value !== false) {
|
||||
if (key === "page" && value === 1) return;
|
||||
if (key === "page_size") return;
|
||||
params.set(key, String(value));
|
||||
}
|
||||
});
|
||||
|
||||
const queryString = params.toString();
|
||||
router.push(`${pathname}${queryString ? `?${queryString}` : ""}`, {
|
||||
scroll: false,
|
||||
});
|
||||
},
|
||||
[pathname, router]
|
||||
);
|
||||
|
||||
const fetchProducts = useCallback(
|
||||
async (newFilters: ProductFilters) => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await productsApi.getAll(newFilters);
|
||||
setProducts(response.results || []);
|
||||
setCount(response.count || 0);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch products:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const debouncedFetch = useCallback(
|
||||
debounce((newFilters: ProductFilters) => {
|
||||
fetchProducts(newFilters);
|
||||
updateUrl(newFilters);
|
||||
}, 300),
|
||||
[fetchProducts, updateUrl]
|
||||
);
|
||||
|
||||
const handleFilterChange = (key: keyof ProductFilters, value: unknown) => {
|
||||
const newFilters = { ...filters, [key]: value, page: 1 };
|
||||
setFilters(newFilters);
|
||||
debouncedFetch(newFilters);
|
||||
};
|
||||
|
||||
const handleSortChange = (value: string) => {
|
||||
const newFilters = { ...filters, ordering: value, page: 1 };
|
||||
setFilters(newFilters);
|
||||
fetchProducts(newFilters);
|
||||
updateUrl(newFilters);
|
||||
};
|
||||
|
||||
const clearFilters = () => {
|
||||
const newFilters: ProductFilters = {
|
||||
ordering: "-created_at",
|
||||
page: 1,
|
||||
page_size: 12,
|
||||
};
|
||||
setFilters(newFilters);
|
||||
fetchProducts(newFilters);
|
||||
updateUrl(newFilters);
|
||||
};
|
||||
|
||||
const loadMore = () => {
|
||||
const nextPage = (filters.page || 1) + 1;
|
||||
const newFilters = { ...filters, page: nextPage };
|
||||
setFilters(newFilters);
|
||||
|
||||
setIsLoading(true);
|
||||
productsApi
|
||||
.getAll(newFilters)
|
||||
.then((response) => {
|
||||
setProducts((prev) => [...prev, ...(response.results || [])]);
|
||||
})
|
||||
.catch(console.error)
|
||||
.finally(() => setIsLoading(false));
|
||||
|
||||
updateUrl(newFilters);
|
||||
};
|
||||
|
||||
const activeFilterCount = [
|
||||
filters.category,
|
||||
filters.brand,
|
||||
filters.min_price,
|
||||
filters.max_price,
|
||||
filters.is_on_sale,
|
||||
filters.is_new,
|
||||
filters.search,
|
||||
].filter(Boolean).length;
|
||||
|
||||
const hasMoreProducts = products.length < count;
|
||||
|
||||
const FilterContent = () => (
|
||||
<div className="space-y-6">
|
||||
{/* Search */}
|
||||
<div className="space-y-2">
|
||||
<Label>{t("common.search")}</Label>
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={t("common.searchPlaceholder")}
|
||||
value={filters.search || ""}
|
||||
onChange={(e) => handleFilterChange("search", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Categories */}
|
||||
{categories.length > 0 && (
|
||||
<Accordion type="single" collapsible defaultValue="categories">
|
||||
<AccordionItem value="categories">
|
||||
<AccordionTrigger>{t("nav.categories")}</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-2">
|
||||
{categories.map((category) => (
|
||||
<div key={category.id} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`category-${category.id}`}
|
||||
checked={filters.category === category.slug}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFilterChange(
|
||||
"category",
|
||||
checked ? category.slug : undefined
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`category-${category.id}`}
|
||||
className="text-sm cursor-pointer flex-1"
|
||||
>
|
||||
{category.name}
|
||||
{category.products_count !== undefined && (
|
||||
<span className="text-muted-foreground ml-1">
|
||||
({category.products_count})
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
)}
|
||||
|
||||
{/* Brands */}
|
||||
{brands.length > 0 && (
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="brands">
|
||||
<AccordionTrigger>{t("nav.brands")}</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-2">
|
||||
{brands.map((brand) => (
|
||||
<div key={brand.id} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id={`brand-${brand.id}`}
|
||||
checked={filters.brand === brand.slug}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFilterChange(
|
||||
"brand",
|
||||
checked ? brand.slug : undefined
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`brand-${brand.id}`}
|
||||
className="text-sm cursor-pointer"
|
||||
>
|
||||
{brand.name}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
)}
|
||||
|
||||
{/* Price Range */}
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="price">
|
||||
<AccordionTrigger>{t("catalog.priceRange")}</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
placeholder={t("catalog.minPrice")}
|
||||
value={filters.min_price || ""}
|
||||
onChange={(e) =>
|
||||
handleFilterChange(
|
||||
"min_price",
|
||||
e.target.value ? Number(e.target.value) : undefined
|
||||
)
|
||||
}
|
||||
className="w-full"
|
||||
/>
|
||||
<span className="text-muted-foreground">-</span>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder={t("catalog.maxPrice")}
|
||||
value={filters.max_price || ""}
|
||||
onChange={(e) =>
|
||||
handleFilterChange(
|
||||
"max_price",
|
||||
e.target.value ? Number(e.target.value) : undefined
|
||||
)
|
||||
}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Other filters */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="is_on_sale"
|
||||
checked={filters.is_on_sale || false}
|
||||
onCheckedChange={(checked) =>
|
||||
handleFilterChange("is_on_sale", checked)
|
||||
}
|
||||
/>
|
||||
<label htmlFor="is_on_sale" className="text-sm cursor-pointer">
|
||||
{t("nav.sale")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="is_new"
|
||||
checked={filters.is_new || false}
|
||||
onCheckedChange={(checked) => handleFilterChange("is_new", checked)}
|
||||
/>
|
||||
<label htmlFor="is_new" className="text-sm cursor-pointer">
|
||||
{t("nav.new")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Clear filters */}
|
||||
{activeFilterCount > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={clearFilters}
|
||||
>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
{t("catalog.clearFilters")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 lg:flex-row">
|
||||
{/* Desktop Filters Sidebar */}
|
||||
<aside className="hidden w-64 flex-shrink-0 lg:block">
|
||||
<div className="sticky top-20 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-semibold">{t("catalog.filters")}</h2>
|
||||
{activeFilterCount > 0 && (
|
||||
<Badge variant="secondary">{activeFilterCount}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<FilterContent />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="flex-1">
|
||||
{/* Toolbar */}
|
||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-4">
|
||||
{/* Mobile filter button */}
|
||||
<Sheet open={isFilterOpen} onOpenChange={setIsFilterOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="outline" className="lg:hidden">
|
||||
<SlidersHorizontal className="mr-2 h-4 w-4" />
|
||||
{t("catalog.filters")}
|
||||
{activeFilterCount > 0 && (
|
||||
<Badge variant="secondary" className="ml-2">
|
||||
{activeFilterCount}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="w-80">
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t("catalog.filters")}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="mt-6">
|
||||
<FilterContent />
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Active filters */}
|
||||
<div className="hidden flex-wrap gap-2 lg:flex">
|
||||
{filters.category && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
{categories.find((c) => c.slug === filters.category)?.name}
|
||||
<X
|
||||
className="h-3 w-3 cursor-pointer"
|
||||
onClick={() => handleFilterChange("category", undefined)}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
{filters.brand && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
{brands.find((b) => b.slug === filters.brand)?.name}
|
||||
<X
|
||||
className="h-3 w-3 cursor-pointer"
|
||||
onClick={() => handleFilterChange("brand", undefined)}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
{filters.is_on_sale && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
{t("nav.sale")}
|
||||
<X
|
||||
className="h-3 w-3 cursor-pointer"
|
||||
onClick={() => handleFilterChange("is_on_sale", false)}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
{filters.is_new && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
{t("nav.new")}
|
||||
<X
|
||||
className="h-3 w-3 cursor-pointer"
|
||||
onClick={() => handleFilterChange("is_new", false)}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sort */}
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("catalog.sortBy")}:
|
||||
</span>
|
||||
<Select
|
||||
value={filters.ordering || "-created_at"}
|
||||
onValueChange={handleSortChange}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sortOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Products */}
|
||||
{isLoading && products.length === 0 ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="space-y-3">
|
||||
<Skeleton className="aspect-square w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : products.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Filter className="h-12 w-12 text-muted-foreground" />
|
||||
<h3 className="mt-4 text-lg font-medium">
|
||||
{t("catalog.noProducts")}
|
||||
</h3>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{t("common.noResults")}
|
||||
</p>
|
||||
<Button variant="outline" className="mt-4" onClick={clearFilters}>
|
||||
{t("catalog.clearFilters")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ProductGrid products={products} columns={3} />
|
||||
|
||||
{/* Load more */}
|
||||
{hasMoreProducts && (
|
||||
<div className="mt-8 flex justify-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={loadMore}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? t("common.loading") : t("catalog.loadMore")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
73
storefront/src/app/[locale]/catalog/page.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import type { Metadata } from "next";
|
||||
import { CatalogContent } from "./catalog-content";
|
||||
import { serverProductsApi, serverCategoriesApi, serverBrandsApi } from "@/lib/api/endpoints";
|
||||
|
||||
interface CatalogPageProps {
|
||||
params: Promise<{ locale: string }>;
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: CatalogPageProps): Promise<Metadata> {
|
||||
const { locale } = await params;
|
||||
return {
|
||||
title: locale === "ru" ? "Каталог" : "Catalog",
|
||||
description:
|
||||
locale === "ru"
|
||||
? "Просмотрите наш полный каталог товаров"
|
||||
: "Browse our full product catalog",
|
||||
};
|
||||
}
|
||||
|
||||
export default async function CatalogPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: CatalogPageProps) {
|
||||
const { locale } = await params;
|
||||
const search = await searchParams;
|
||||
setRequestLocale(locale);
|
||||
|
||||
const t = await getTranslations();
|
||||
|
||||
// Parse search params
|
||||
const filters = {
|
||||
search: search.search as string | undefined,
|
||||
category: search.category as string | undefined,
|
||||
brand: search.brand as string | undefined,
|
||||
min_price: search.min_price ? Number(search.min_price) : undefined,
|
||||
max_price: search.max_price ? Number(search.max_price) : undefined,
|
||||
is_on_sale: search.is_on_sale === "true",
|
||||
is_new: search.is_new === "true",
|
||||
ordering: (search.ordering as string) || "-created_at",
|
||||
page: search.page ? Number(search.page) : 1,
|
||||
page_size: 12,
|
||||
};
|
||||
|
||||
// Fetch data in parallel
|
||||
const [productsData, categoriesData, brandsData] = await Promise.all([
|
||||
serverProductsApi.getAll(locale, filters).catch(() => ({ results: [], count: 0 })),
|
||||
serverCategoriesApi.getAll(locale).catch(() => ({ results: [] })),
|
||||
serverBrandsApi.getAll(locale).catch(() => ({ results: [] })),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold">{t("catalog.title")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{t("catalog.showingResults", { count: productsData.count || 0 })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CatalogContent
|
||||
initialProducts={productsData.results || []}
|
||||
totalCount={productsData.count || 0}
|
||||
categories={categoriesData.results || []}
|
||||
brands={brandsData.results || []}
|
||||
initialFilters={filters}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
631
storefront/src/app/[locale]/checkout/page.tsx
Normal file
|
|
@ -0,0 +1,631 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import Image from "next/image";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
ChevronLeft,
|
||||
CreditCard,
|
||||
Truck,
|
||||
CheckCircle,
|
||||
ShoppingBag,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { useCartStore, useAuthStore } from "@/stores";
|
||||
import { formatPrice, getImageUrl, generateOrderNumber } from "@/lib/utils";
|
||||
import { ordersApi } from "@/lib/api/endpoints";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const checkoutSchema = z.object({
|
||||
email: z.string().email(),
|
||||
firstName: z.string().min(1),
|
||||
lastName: z.string().min(1),
|
||||
phone: z.string().min(1),
|
||||
address: z.string().min(1),
|
||||
address2: z.string().optional(),
|
||||
city: z.string().min(1),
|
||||
state: z.string().optional(),
|
||||
postalCode: z.string().min(1),
|
||||
country: z.string().min(1),
|
||||
shippingMethod: z.string(),
|
||||
paymentMethod: z.string(),
|
||||
saveInfo: z.boolean().optional(),
|
||||
});
|
||||
|
||||
type CheckoutFormData = z.infer<typeof checkoutSchema>;
|
||||
|
||||
export default function CheckoutPage() {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const { items, getSubtotal, clearCart } = useCartStore();
|
||||
const { user, isAuthenticated } = useAuthStore();
|
||||
const [step, setStep] = useState(1);
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [orderNumber, setOrderNumber] = useState<string | null>(null);
|
||||
|
||||
const form = useForm<CheckoutFormData>({
|
||||
resolver: zodResolver(checkoutSchema),
|
||||
defaultValues: {
|
||||
email: user?.email || "",
|
||||
firstName: user?.first_name || "",
|
||||
lastName: user?.last_name || "",
|
||||
phone: user?.phone || "",
|
||||
address: "",
|
||||
address2: "",
|
||||
city: "",
|
||||
state: "",
|
||||
postalCode: "",
|
||||
country: "Russia",
|
||||
shippingMethod: "standard",
|
||||
paymentMethod: "card",
|
||||
saveInfo: true,
|
||||
},
|
||||
});
|
||||
|
||||
const subtotal = getSubtotal();
|
||||
const shippingCost = form.watch("shippingMethod") === "express" ? 500 : 0;
|
||||
const total = subtotal + shippingCost;
|
||||
|
||||
const shippingMethods = [
|
||||
{
|
||||
id: "standard",
|
||||
name: t("common.free"),
|
||||
description:
|
||||
form.getValues("country") === "Russia"
|
||||
? "5-7 рабочих дней"
|
||||
: "5-7 business days",
|
||||
price: 0,
|
||||
},
|
||||
{
|
||||
id: "express",
|
||||
name: "Express",
|
||||
description:
|
||||
form.getValues("country") === "Russia"
|
||||
? "2-3 рабочих дня"
|
||||
: "2-3 business days",
|
||||
price: 500,
|
||||
},
|
||||
];
|
||||
|
||||
const paymentMethods = [
|
||||
{
|
||||
id: "card",
|
||||
name: form.getValues("country") === "Russia" ? "Банковская карта" : "Credit Card",
|
||||
icon: CreditCard,
|
||||
},
|
||||
];
|
||||
|
||||
const onSubmit = async (data: CheckoutFormData) => {
|
||||
if (step < 3) {
|
||||
setStep(step + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsProcessing(true);
|
||||
|
||||
try {
|
||||
// Create order
|
||||
const newOrderNumber = generateOrderNumber();
|
||||
|
||||
// In a real app, you would call the API here
|
||||
// await ordersApi.create({
|
||||
// items: items.map(item => ({
|
||||
// product: item.product.id,
|
||||
// quantity: item.quantity,
|
||||
// })),
|
||||
// shipping_address: {
|
||||
// ...data,
|
||||
// },
|
||||
// shipping_method: data.shippingMethod,
|
||||
// payment_method: data.paymentMethod,
|
||||
// });
|
||||
|
||||
// Simulate API call
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
setOrderNumber(newOrderNumber);
|
||||
setStep(4);
|
||||
clearCart();
|
||||
toast.success(t("checkout.orderPlaced"));
|
||||
} catch (error) {
|
||||
toast.error(t("common.error"));
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (items.length === 0 && step !== 4) {
|
||||
return (
|
||||
<div className="container py-16">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<ShoppingBag className="mx-auto h-16 w-16 text-muted-foreground" />
|
||||
<h1 className="mt-6 text-2xl font-bold">{t("cart.empty")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">{t("cart.emptyMessage")}</p>
|
||||
<Button asChild className="mt-6">
|
||||
<Link href="/catalog">{t("common.continueShopping")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Order confirmation
|
||||
if (step === 4) {
|
||||
return (
|
||||
<div className="container py-16">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<CheckCircle className="mx-auto h-16 w-16 text-green-500" />
|
||||
<h1 className="mt-6 text-2xl font-bold">{t("checkout.orderPlaced")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{t("checkout.orderNumber")}: <strong>{orderNumber}</strong>
|
||||
</p>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{t("checkout.orderConfirmation")}
|
||||
</p>
|
||||
<div className="mt-8 flex flex-col gap-2">
|
||||
{isAuthenticated && (
|
||||
<Button asChild>
|
||||
<Link href="/account/orders">{t("nav.orders")}</Link>
|
||||
</Button>
|
||||
)}
|
||||
<Button asChild variant="outline">
|
||||
<Link href="/catalog">{t("common.continueShopping")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
{/* Back button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="mb-6"
|
||||
onClick={() => (step > 1 ? setStep(step - 1) : router.push("/cart"))}
|
||||
>
|
||||
<ChevronLeft className="mr-2 h-4 w-4" />
|
||||
{step > 1 ? t("common.backToShopping") : t("cart.title")}
|
||||
</Button>
|
||||
|
||||
<h1 className="mb-8 text-3xl font-bold">{t("checkout.title")}</h1>
|
||||
|
||||
{/* Steps indicator */}
|
||||
<div className="mb-8 flex items-center justify-center gap-4">
|
||||
{[1, 2, 3].map((s) => (
|
||||
<div key={s} className="flex items-center">
|
||||
<div
|
||||
className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
|
||||
s <= step
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{s}
|
||||
</div>
|
||||
<span className="ml-2 hidden text-sm sm:inline">
|
||||
{s === 1 && t("checkout.steps.shipping")}
|
||||
{s === 2 && t("checkout.steps.payment")}
|
||||
{s === 3 && t("checkout.steps.review")}
|
||||
</span>
|
||||
{s < 3 && (
|
||||
<div
|
||||
className={`mx-4 h-0.5 w-8 ${
|
||||
s < step ? "bg-primary" : "bg-muted"
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
{/* Form section */}
|
||||
<div className="lg:col-span-2">
|
||||
{/* Step 1: Shipping */}
|
||||
{step === 1 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Truck className="h-5 w-5" />
|
||||
{t("checkout.shippingAddress")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="firstName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.firstName")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="lastName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.lastName")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.email")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="email" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="phone"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.phone")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="tel" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="address"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.address")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="address2"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.address2")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="city"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.city")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="state"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.state")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="postalCode"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.postalCode")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator className="my-6" />
|
||||
|
||||
<div>
|
||||
<h3 className="mb-4 font-medium">
|
||||
{t("checkout.shippingMethod")}
|
||||
</h3>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="shippingMethod"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<RadioGroup
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value}
|
||||
className="space-y-2"
|
||||
>
|
||||
{shippingMethods.map((method) => (
|
||||
<div
|
||||
key={method.id}
|
||||
className="flex items-center justify-between rounded-lg border p-4"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<RadioGroupItem
|
||||
value={method.id}
|
||||
id={method.id}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={method.id}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<span className="font-medium">
|
||||
{method.name}
|
||||
</span>
|
||||
<span className="ml-2 text-sm text-muted-foreground">
|
||||
{method.description}
|
||||
</span>
|
||||
</Label>
|
||||
</div>
|
||||
<span className="font-medium">
|
||||
{method.price === 0
|
||||
? t("common.free")
|
||||
: formatPrice(method.price)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Step 2: Payment */}
|
||||
{step === 2 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CreditCard className="h-5 w-5" />
|
||||
{t("checkout.paymentMethod")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="paymentMethod"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<RadioGroup
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value}
|
||||
className="space-y-2"
|
||||
>
|
||||
{paymentMethods.map((method) => (
|
||||
<div
|
||||
key={method.id}
|
||||
className="flex items-center gap-3 rounded-lg border p-4"
|
||||
>
|
||||
<RadioGroupItem
|
||||
value={method.id}
|
||||
id={method.id}
|
||||
/>
|
||||
<method.icon className="h-5 w-5" />
|
||||
<Label
|
||||
htmlFor={method.id}
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{method.name}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<p className="mt-4 text-sm text-muted-foreground">
|
||||
{form.getValues("country") === "Russia"
|
||||
? "Оплата будет произведена после размещения заказа"
|
||||
: "Payment will be processed after placing the order"}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Step 3: Review */}
|
||||
{step === 3 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("checkout.orderReview")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Shipping info */}
|
||||
<div>
|
||||
<h3 className="mb-2 font-medium">
|
||||
{t("checkout.shippingAddress")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{form.getValues("firstName")} {form.getValues("lastName")}
|
||||
<br />
|
||||
{form.getValues("address")}
|
||||
{form.getValues("address2") &&
|
||||
`, ${form.getValues("address2")}`}
|
||||
<br />
|
||||
{form.getValues("city")}, {form.getValues("state")}{" "}
|
||||
{form.getValues("postalCode")}
|
||||
<br />
|
||||
{form.getValues("phone")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Items */}
|
||||
<div>
|
||||
<h3 className="mb-4 font-medium">{t("cart.title")}</h3>
|
||||
<div className="space-y-4">
|
||||
{items.map((item) => {
|
||||
const price = item.product.sale_price
|
||||
? parseFloat(item.product.sale_price)
|
||||
: parseFloat(item.product.price);
|
||||
const primaryImage =
|
||||
item.product.images?.find((img) => img.is_primary) ||
|
||||
item.product.images?.[0];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.product.id}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="relative h-16 w-16 overflow-hidden rounded-md border">
|
||||
{primaryImage ? (
|
||||
<Image
|
||||
src={getImageUrl(primaryImage.image)}
|
||||
alt={item.product.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center bg-muted">
|
||||
<ShoppingBag className="h-6 w-6 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">{item.product.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("common.quantity")}: {item.quantity}
|
||||
</p>
|
||||
</div>
|
||||
<p className="font-medium">
|
||||
{formatPrice(price * item.quantity)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Order summary */}
|
||||
<div>
|
||||
<Card className="sticky top-20">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("cart.orderSummary")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{t("common.subtotal")}
|
||||
</span>
|
||||
<span>{formatPrice(subtotal)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{t("common.shipping")}
|
||||
</span>
|
||||
<span>
|
||||
{shippingCost === 0
|
||||
? t("common.free")
|
||||
: formatPrice(shippingCost)}
|
||||
</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-medium">
|
||||
<span>{t("common.total")}</span>
|
||||
<span>{formatPrice(total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
size="lg"
|
||||
disabled={isProcessing}
|
||||
>
|
||||
{isProcessing
|
||||
? t("checkout.processing")
|
||||
: step === 3
|
||||
? t("checkout.placeOrder")
|
||||
: step === 2
|
||||
? t("checkout.steps.review")
|
||||
: t("checkout.steps.payment")}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
222
storefront/src/app/[locale]/contact/page.tsx
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { Mail, Phone, MapPin, Send } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { siteApi } from "@/lib/api/endpoints";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const contactSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
subject: z.string().min(1),
|
||||
message: z.string().min(10),
|
||||
});
|
||||
|
||||
type ContactFormData = z.infer<typeof contactSchema>;
|
||||
|
||||
export default function ContactPage() {
|
||||
const t = useTranslations();
|
||||
|
||||
const form = useForm<ContactFormData>({
|
||||
resolver: zodResolver(contactSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
email: "",
|
||||
subject: "",
|
||||
message: "",
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: ContactFormData) => {
|
||||
try {
|
||||
await siteApi.contactUs(data);
|
||||
toast.success(t("common.save"));
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
toast.error(t("common.error"));
|
||||
}
|
||||
};
|
||||
|
||||
const contactInfo = [
|
||||
{
|
||||
icon: Mail,
|
||||
label: "Email",
|
||||
value: "support@itoption.ru",
|
||||
href: "mailto:support@itoption.ru",
|
||||
},
|
||||
{
|
||||
icon: Phone,
|
||||
label: t("checkout.form.phone"),
|
||||
value: "+7 (999) 999-99-99",
|
||||
href: "tel:+79999999999",
|
||||
},
|
||||
{
|
||||
icon: MapPin,
|
||||
label: t("checkout.form.address"),
|
||||
value: "Moscow, Russia",
|
||||
href: null,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<div className="mx-auto max-w-4xl">
|
||||
<div className="mb-8 text-center">
|
||||
<h1 className="text-3xl font-bold">{t("footer.customerService.contactUs")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{t("footer.about.description")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-8 md:grid-cols-2">
|
||||
{/* Contact form */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("footer.customerService.contactUs")}</CardTitle>
|
||||
<CardDescription>
|
||||
Fill out the form and we'll get back to you
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.firstName")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("checkout.form.email")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="email" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="subject"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Subject</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="message"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Message</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea rows={5} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
Send Message
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Contact info */}
|
||||
<div className="space-y-6">
|
||||
{contactInfo.map((item, index) => (
|
||||
<Card key={index}>
|
||||
<CardContent className="flex items-center gap-4 p-4">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
|
||||
<item.icon className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">{item.label}</p>
|
||||
{item.href ? (
|
||||
<a
|
||||
href={item.href}
|
||||
className="font-medium hover:text-primary"
|
||||
>
|
||||
{item.value}
|
||||
</a>
|
||||
) : (
|
||||
<p className="font-medium">{item.value}</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{/* Map or additional info */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<h3 className="mb-4 font-semibold">Working Hours</h3>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Monday - Friday</span>
|
||||
<span>9:00 - 18:00</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Saturday</span>
|
||||
<span>10:00 - 16:00</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Sunday</span>
|
||||
<span>Closed</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
94
storefront/src/app/[locale]/layout.tsx
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import type { Metadata } from "next";
|
||||
import { NextIntlClientProvider } from "next-intl";
|
||||
import { getMessages, setRequestLocale } from "next-intl/server";
|
||||
import { notFound } from "next/navigation";
|
||||
import { routing } from "@/i18n/routing";
|
||||
import { Providers } from "@/components/providers";
|
||||
import { Header } from "@/components/layout/header";
|
||||
import { Footer } from "@/components/layout/footer";
|
||||
import { serverCategoriesApi, serverSiteApi } from "@/lib/api/endpoints";
|
||||
import "../globals.css";
|
||||
|
||||
export function generateStaticParams() {
|
||||
return routing.locales.map((locale) => ({ locale }));
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ locale: string }>;
|
||||
}): Promise<Metadata> {
|
||||
const { locale } = await params;
|
||||
const projectName = process.env.NEXT_PUBLIC_PROJECT_NAME || "eVibes";
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000";
|
||||
|
||||
return {
|
||||
title: {
|
||||
default: projectName,
|
||||
template: `%s | ${projectName}`,
|
||||
},
|
||||
description:
|
||||
locale === "ru"
|
||||
? "Интернет-магазин качественных товаров"
|
||||
: "Online store for quality products",
|
||||
metadataBase: new URL(baseUrl),
|
||||
openGraph: {
|
||||
type: "website",
|
||||
locale: locale === "ru" ? "ru_RU" : "en_US",
|
||||
siteName: projectName,
|
||||
},
|
||||
robots: {
|
||||
index: true,
|
||||
follow: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default async function LocaleLayout({
|
||||
children,
|
||||
params,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
params: Promise<{ locale: string }>;
|
||||
}) {
|
||||
const { locale } = await params;
|
||||
|
||||
if (!routing.locales.includes(locale as "en" | "ru")) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
setRequestLocale(locale);
|
||||
|
||||
const messages = await getMessages();
|
||||
|
||||
// Fetch data for layout
|
||||
let categories: { id: string; name: string; slug: string }[] = [];
|
||||
let siteParams = undefined;
|
||||
|
||||
try {
|
||||
const [categoriesData, siteParamsData] = await Promise.all([
|
||||
serverCategoriesApi.getAll(locale).catch(() => ({ results: [] })),
|
||||
serverSiteApi.getParameters(locale).catch(() => undefined),
|
||||
]);
|
||||
categories = categoriesData.results || [];
|
||||
siteParams = siteParamsData;
|
||||
} catch {
|
||||
// Continue with empty data if API fails
|
||||
}
|
||||
|
||||
return (
|
||||
<html lang={locale} suppressHydrationWarning>
|
||||
<body className="min-h-screen bg-background font-sans antialiased">
|
||||
<NextIntlClientProvider messages={messages}>
|
||||
<Providers>
|
||||
<div className="relative flex min-h-screen flex-col">
|
||||
<Header categories={categories} />
|
||||
<main className="flex-1">{children}</main>
|
||||
<Footer siteParams={siteParams} />
|
||||
</div>
|
||||
</Providers>
|
||||
</NextIntlClientProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
196
storefront/src/app/[locale]/login/page.tsx
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
"use client";
|
||||
|
||||
import { Suspense, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { Eye, EyeOff, LogIn } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { useAuthStore } from "@/stores";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
rememberMe: z.boolean().optional(),
|
||||
});
|
||||
|
||||
type LoginFormData = z.infer<typeof loginSchema>;
|
||||
|
||||
function LoginForm() {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const { login, isLoading, error, clearError } = useAuthStore();
|
||||
|
||||
const redirectTo = searchParams.get("redirect") || "/";
|
||||
|
||||
const form = useForm<LoginFormData>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
defaultValues: {
|
||||
email: "",
|
||||
password: "",
|
||||
rememberMe: false,
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: LoginFormData) => {
|
||||
clearError();
|
||||
const success = await login({ email: data.email, password: data.password });
|
||||
|
||||
if (success) {
|
||||
toast.success(t("auth.login.title"));
|
||||
router.push(redirectTo);
|
||||
} else {
|
||||
toast.error(t("auth.login.error"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container flex min-h-[calc(100vh-200px)] items-center justify-center py-8">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">{t("auth.login.title")}</CardTitle>
|
||||
<CardDescription>{t("auth.login.subtitle")}</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<CardContent className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.login.email")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="email@example.com"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.login.password")}</FormLabel>
|
||||
<FormControl>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showPassword ? "text" : "password"}
|
||||
{...field}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="rememberMe"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="cursor-pointer text-sm font-normal">
|
||||
{t("auth.login.rememberMe")}
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Link
|
||||
href="/forgot-password"
|
||||
className="text-sm text-primary hover:underline"
|
||||
>
|
||||
{t("auth.login.forgotPassword")}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex flex-col gap-4">
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
t("common.loading")
|
||||
) : (
|
||||
<>
|
||||
<LogIn className="mr-2 h-4 w-4" />
|
||||
{t("auth.login.submit")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
{t("auth.login.noAccount")}{" "}
|
||||
<Link href="/register" className="text-primary hover:underline">
|
||||
{t("auth.login.createAccount")}
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="container flex min-h-[calc(100vh-200px)] items-center justify-center py-8">Loading...</div>}>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
33
storefront/src/app/[locale]/not-found.tsx
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { FileQuestion, Home, ArrowLeft } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function NotFound() {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<div className="container flex min-h-[calc(100vh-200px)] items-center justify-center py-16">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<FileQuestion className="mx-auto h-24 w-24 text-muted-foreground" />
|
||||
<h1 className="mt-6 text-4xl font-bold">404</h1>
|
||||
<h2 className="mt-2 text-xl font-semibold">{t("errors.404.title")}</h2>
|
||||
<p className="mt-2 text-muted-foreground">{t("errors.404.message")}</p>
|
||||
<div className="mt-8 flex flex-col gap-2 sm:flex-row sm:justify-center">
|
||||
<Button asChild>
|
||||
<Link href="/">
|
||||
<Home className="mr-2 h-4 w-4" />
|
||||
{t("errors.404.backHome")}
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/catalog">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{t("nav.catalog")}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
284
storefront/src/app/[locale]/page.tsx
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import Image from "next/image";
|
||||
import { ArrowRight, Truck, Shield, Headphones, RefreshCw } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { ProductCarousel } from "@/components/products";
|
||||
import { serverProductsApi, serverCategoriesApi, serverPromotionsApi } from "@/lib/api/endpoints";
|
||||
import { getImageUrl } from "@/lib/utils";
|
||||
|
||||
interface HomePageProps {
|
||||
params: Promise<{ locale: string }>;
|
||||
}
|
||||
|
||||
export default async function HomePage({ params }: HomePageProps) {
|
||||
const { locale } = await params;
|
||||
setRequestLocale(locale);
|
||||
|
||||
const t = await getTranslations();
|
||||
const projectName = process.env.NEXT_PUBLIC_PROJECT_NAME || "eVibes";
|
||||
|
||||
// Fetch data in parallel
|
||||
const [featuredProducts, newProducts, categories, promotions] = await Promise.all([
|
||||
serverProductsApi.getFeatured(locale).catch(() => ({ results: [] })),
|
||||
serverProductsApi.getNew(locale).catch(() => ({ results: [] })),
|
||||
serverCategoriesApi.getAll(locale).catch(() => ({ results: [] })),
|
||||
serverPromotionsApi.getActive(locale).catch(() => ({ results: [] })),
|
||||
]);
|
||||
|
||||
const features = [
|
||||
{
|
||||
icon: Truck,
|
||||
title: locale === "ru" ? "Быстрая доставка" : "Fast Delivery",
|
||||
description: locale === "ru" ? "Доставка по всей России" : "Delivery across the country",
|
||||
},
|
||||
{
|
||||
icon: Shield,
|
||||
title: locale === "ru" ? "Безопасная оплата" : "Secure Payment",
|
||||
description: locale === "ru" ? "100% защита платежей" : "100% payment protection",
|
||||
},
|
||||
{
|
||||
icon: Headphones,
|
||||
title: locale === "ru" ? "Поддержка 24/7" : "24/7 Support",
|
||||
description: locale === "ru" ? "Всегда готовы помочь" : "Always ready to help",
|
||||
},
|
||||
{
|
||||
icon: RefreshCw,
|
||||
title: locale === "ru" ? "Легкий возврат" : "Easy Returns",
|
||||
description: locale === "ru" ? "30 дней на возврат" : "30-day return policy",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{/* Hero Section */}
|
||||
<section className="relative bg-gradient-to-br from-primary/10 via-background to-secondary/10">
|
||||
<div className="container py-16 md:py-24 lg:py-32">
|
||||
<div className="mx-auto max-w-3xl text-center">
|
||||
<h1 className="text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl">
|
||||
{t("home.hero.title", { storeName: projectName })}
|
||||
</h1>
|
||||
<p className="mt-6 text-lg text-muted-foreground md:text-xl">
|
||||
{t("home.hero.subtitle")}
|
||||
</p>
|
||||
<div className="mt-8 flex flex-col items-center justify-center gap-4 sm:flex-row">
|
||||
<Button asChild size="lg">
|
||||
<Link href="/catalog">
|
||||
{t("home.hero.cta")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild variant="outline" size="lg">
|
||||
<Link href="/catalog?is_on_sale=true">
|
||||
{t("home.promotions.title")}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Features */}
|
||||
<section className="border-y bg-muted/30">
|
||||
<div className="container py-8">
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{features.map((feature, index) => (
|
||||
<div key={index} className="flex items-center gap-4">
|
||||
<div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-lg bg-primary/10">
|
||||
<feature.icon className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-medium">{feature.title}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{feature.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Categories */}
|
||||
{categories.results && categories.results.length > 0 && (
|
||||
<section className="container py-12 md:py-16">
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold md:text-3xl">
|
||||
{t("home.categories.title")}
|
||||
</h2>
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
{t("home.categories.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild variant="ghost">
|
||||
<Link href="/catalog">
|
||||
{t("common.viewAll")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
|
||||
{categories.results.slice(0, 8).map((category) => (
|
||||
<Link
|
||||
key={category.id}
|
||||
href={`/catalog/${category.slug}`}
|
||||
className="group"
|
||||
>
|
||||
<Card className="overflow-hidden transition-all hover:shadow-lg">
|
||||
<div className="relative aspect-[4/3] bg-muted">
|
||||
{category.image ? (
|
||||
<Image
|
||||
src={getImageUrl(category.image)}
|
||||
alt={category.name}
|
||||
fill
|
||||
className="object-cover transition-transform group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center bg-gradient-to-br from-primary/20 to-secondary/20">
|
||||
<span className="text-4xl font-bold text-primary/30">
|
||||
{category.name.charAt(0)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
|
||||
<div className="absolute bottom-0 left-0 right-0 p-4">
|
||||
<h3 className="text-lg font-semibold text-white">
|
||||
{category.name}
|
||||
</h3>
|
||||
{category.products_count !== undefined && (
|
||||
<p className="text-sm text-white/80">
|
||||
{category.products_count}{" "}
|
||||
{locale === "ru" ? "товаров" : "products"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Featured Products */}
|
||||
{featuredProducts.results && featuredProducts.results.length > 0 && (
|
||||
<section className="bg-muted/30">
|
||||
<div className="container py-12 md:py-16">
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold md:text-3xl">
|
||||
{t("home.featured.title")}
|
||||
</h2>
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
{t("home.featured.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild variant="ghost">
|
||||
<Link href="/catalog?is_featured=true">
|
||||
{t("common.viewAll")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<ProductCarousel products={featuredProducts.results} />
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Promotions Banner */}
|
||||
{promotions.results && promotions.results.length > 0 && (
|
||||
<section className="container py-12 md:py-16">
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{promotions.results.slice(0, 2).map((promotion) => (
|
||||
<Link
|
||||
key={promotion.id}
|
||||
href={`/catalog?promotion=${promotion.slug}`}
|
||||
className="group"
|
||||
>
|
||||
<Card className="overflow-hidden">
|
||||
<div className="relative aspect-[2/1] bg-gradient-to-br from-primary to-primary/60">
|
||||
{promotion.banner_image ? (
|
||||
<Image
|
||||
src={getImageUrl(promotion.banner_image)}
|
||||
alt={promotion.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center p-6">
|
||||
<div className="text-center text-white">
|
||||
<h3 className="text-2xl font-bold md:text-3xl">
|
||||
{promotion.name}
|
||||
</h3>
|
||||
{promotion.discount_percentage && (
|
||||
<p className="mt-2 text-4xl font-bold">
|
||||
-{promotion.discount_percentage}%
|
||||
</p>
|
||||
)}
|
||||
{promotion.description && (
|
||||
<p className="mt-2 text-white/80">
|
||||
{promotion.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* New Arrivals */}
|
||||
{newProducts.results && newProducts.results.length > 0 && (
|
||||
<section className="container py-12 md:py-16">
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold md:text-3xl">
|
||||
{t("home.newArrivals.title")}
|
||||
</h2>
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
{t("home.newArrivals.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild variant="ghost">
|
||||
<Link href="/catalog?is_new=true">
|
||||
{t("common.viewAll")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<ProductCarousel products={newProducts.results} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Newsletter */}
|
||||
<section className="bg-primary text-primary-foreground">
|
||||
<div className="container py-12 md:py-16">
|
||||
<div className="mx-auto max-w-2xl text-center">
|
||||
<h2 className="text-2xl font-bold md:text-3xl">
|
||||
{t("footer.newsletter.title")}
|
||||
</h2>
|
||||
<p className="mt-2 text-primary-foreground/80">
|
||||
{t("footer.newsletter.description")}
|
||||
</p>
|
||||
<form className="mt-6 flex gap-2">
|
||||
<input
|
||||
type="email"
|
||||
placeholder={t("footer.newsletter.placeholder")}
|
||||
className="flex-1 rounded-md border-0 bg-primary-foreground/10 px-4 py-2 text-primary-foreground placeholder:text-primary-foreground/60 focus:outline-none focus:ring-2 focus:ring-primary-foreground/50"
|
||||
/>
|
||||
<Button variant="secondary">
|
||||
{t("footer.newsletter.subscribe")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
328
storefront/src/app/[locale]/product/[slug]/page.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { serverProductsApi } from "@/lib/api/endpoints";
|
||||
import { getImageUrl, formatPrice, getDiscountPercentage } from "@/lib/utils";
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { ProductCarousel } from "@/components/products";
|
||||
import { ProductActions } from "./product-actions";
|
||||
import { ProductGallery } from "./product-gallery";
|
||||
|
||||
interface ProductPageProps {
|
||||
params: Promise<{ locale: string; slug: string }>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: ProductPageProps): Promise<Metadata> {
|
||||
const { locale, slug } = await params;
|
||||
|
||||
try {
|
||||
const product = await serverProductsApi.getBySlug(locale, slug);
|
||||
const primaryImage = product.images?.find((img) => img.is_primary) || product.images?.[0];
|
||||
|
||||
return {
|
||||
title: product.name,
|
||||
description: product.short_description || product.description?.slice(0, 160),
|
||||
openGraph: {
|
||||
title: product.name,
|
||||
description: product.short_description || product.description?.slice(0, 160),
|
||||
images: primaryImage ? [getImageUrl(primaryImage.image)] : [],
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
title: locale === "ru" ? "Товар" : "Product",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default async function ProductPage({ params }: ProductPageProps) {
|
||||
const { locale, slug } = await params;
|
||||
setRequestLocale(locale);
|
||||
|
||||
const t = await getTranslations();
|
||||
|
||||
let product;
|
||||
try {
|
||||
product = await serverProductsApi.getBySlug(locale, slug);
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const hasDiscount = product.sale_price && product.is_on_sale;
|
||||
const discountPercentage = hasDiscount
|
||||
? getDiscountPercentage(product.price, product.sale_price!)
|
||||
: 0;
|
||||
|
||||
// Fetch related products (would need to implement this endpoint or use similar products)
|
||||
let relatedProducts: typeof product[] = [];
|
||||
try {
|
||||
if (product.category) {
|
||||
const related = await serverProductsApi.getAll(locale, {
|
||||
category: product.category.slug,
|
||||
page_size: 8,
|
||||
});
|
||||
relatedProducts = related.results?.filter((p) => p.id !== product.id).slice(0, 4) || [];
|
||||
}
|
||||
} catch {
|
||||
// Continue without related products
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
{/* Breadcrumb */}
|
||||
<Breadcrumb className="mb-6">
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href="/">{t("nav.home")}</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href="/catalog">{t("nav.catalog")}</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
{product.category && (
|
||||
<>
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbLink asChild>
|
||||
<Link href={`/catalog/${product.category.slug}`}>
|
||||
{product.category.name}
|
||||
</Link>
|
||||
</BreadcrumbLink>
|
||||
</BreadcrumbItem>
|
||||
</>
|
||||
)}
|
||||
<BreadcrumbSeparator />
|
||||
<BreadcrumbItem>
|
||||
<BreadcrumbPage>{product.name}</BreadcrumbPage>
|
||||
</BreadcrumbItem>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
|
||||
{/* Product main section */}
|
||||
<div className="grid gap-8 lg:grid-cols-2">
|
||||
{/* Gallery */}
|
||||
<ProductGallery images={product.images || []} productName={product.name} />
|
||||
|
||||
{/* Info */}
|
||||
<div className="space-y-6">
|
||||
{/* Badges */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{hasDiscount && (
|
||||
<Badge variant="destructive">-{discountPercentage}%</Badge>
|
||||
)}
|
||||
{product.is_new && <Badge variant="secondary">{t("nav.new")}</Badge>}
|
||||
{product.stock_quantity <= 0 && (
|
||||
<Badge variant="outline">{t("common.outOfStock")}</Badge>
|
||||
)}
|
||||
{product.stock_quantity > 0 && product.stock_quantity <= 5 && (
|
||||
<Badge variant="outline" className="border-yellow-500 text-yellow-600">
|
||||
{locale === "ru" ? `Осталось ${product.stock_quantity} шт.` : `Only ${product.stock_quantity} left`}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Brand */}
|
||||
{product.brand && (
|
||||
<Link
|
||||
href={`/catalog?brand=${product.brand.slug}`}
|
||||
className="text-sm text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{product.brand.name}
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{/* Title */}
|
||||
<h1 className="text-2xl font-bold md:text-3xl">{product.name}</h1>
|
||||
|
||||
{/* Rating */}
|
||||
{product.average_rating > 0 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<svg
|
||||
key={i}
|
||||
className={`h-5 w-5 ${
|
||||
i < Math.round(product.average_rating)
|
||||
? "fill-yellow-400 text-yellow-400"
|
||||
: "fill-muted text-muted"
|
||||
}`}
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{product.average_rating.toFixed(1)} ({product.reviews_count}{" "}
|
||||
{t("product.reviews")})
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Price */}
|
||||
<div className="flex items-baseline gap-3">
|
||||
{hasDiscount ? (
|
||||
<>
|
||||
<span className="text-3xl font-bold text-destructive">
|
||||
{formatPrice(product.sale_price!)}
|
||||
</span>
|
||||
<span className="text-xl text-muted-foreground line-through">
|
||||
{formatPrice(product.price)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-3xl font-bold">
|
||||
{formatPrice(product.price)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Short description */}
|
||||
{product.short_description && (
|
||||
<p className="text-muted-foreground">{product.short_description}</p>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Actions */}
|
||||
<ProductActions product={product} />
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Meta info */}
|
||||
<div className="space-y-2 text-sm">
|
||||
{product.sku && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t("product.sku")}:</span>
|
||||
<span>{product.sku}</span>
|
||||
</div>
|
||||
)}
|
||||
{product.category && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t("product.category")}:</span>
|
||||
<Link
|
||||
href={`/catalog/${product.category.slug}`}
|
||||
className="hover:text-primary"
|
||||
>
|
||||
{product.category.name}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
{product.brand && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t("product.brand")}:</span>
|
||||
<Link
|
||||
href={`/catalog?brand=${product.brand.slug}`}
|
||||
className="hover:text-primary"
|
||||
>
|
||||
{product.brand.name}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t("product.availability")}:</span>
|
||||
<span
|
||||
className={
|
||||
product.stock_quantity > 0 ? "text-green-600" : "text-destructive"
|
||||
}
|
||||
>
|
||||
{product.stock_quantity > 0
|
||||
? t("common.inStock")
|
||||
: t("common.outOfStock")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tags */}
|
||||
{product.tags && product.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{product.tags.map((tag) => (
|
||||
<Link key={tag.id} href={`/catalog?tag=${tag.slug}`}>
|
||||
<Badge variant="outline" className="cursor-pointer hover:bg-accent">
|
||||
{tag.name}
|
||||
</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs section */}
|
||||
<div className="mt-12">
|
||||
<Tabs defaultValue="description">
|
||||
<TabsList className="w-full justify-start">
|
||||
<TabsTrigger value="description">{t("product.description")}</TabsTrigger>
|
||||
{product.attributes && product.attributes.length > 0 && (
|
||||
<TabsTrigger value="specifications">
|
||||
{t("product.specifications")}
|
||||
</TabsTrigger>
|
||||
)}
|
||||
<TabsTrigger value="reviews">
|
||||
{t("product.reviews")} ({product.reviews_count})
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="description" className="mt-6">
|
||||
<div
|
||||
className="prose max-w-none dark:prose-invert"
|
||||
dangerouslySetInnerHTML={{ __html: product.description || "" }}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{product.attributes && product.attributes.length > 0 && (
|
||||
<TabsContent value="specifications" className="mt-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{product.attributes.map((attr) => (
|
||||
<div
|
||||
key={attr.id}
|
||||
className="flex justify-between border-b pb-2"
|
||||
>
|
||||
<span className="text-muted-foreground">{attr.name}</span>
|
||||
<span className="font-medium">{attr.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
<TabsContent value="reviews" className="mt-6">
|
||||
{product.reviews_count === 0 ? (
|
||||
<p className="text-muted-foreground">{t("product.noReviews")}</p>
|
||||
) : (
|
||||
<p className="text-muted-foreground">
|
||||
{t("product.reviewsCount", { count: product.reviews_count })}
|
||||
</p>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* Related products */}
|
||||
{relatedProducts.length > 0 && (
|
||||
<section className="mt-16">
|
||||
<h2 className="mb-6 text-2xl font-bold">{t("product.relatedProducts")}</h2>
|
||||
<ProductCarousel products={relatedProducts} />
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
141
storefront/src/app/[locale]/product/[slug]/product-actions.tsx
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Heart, ShoppingCart, Minus, Plus, Share2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useCartStore, useWishlistStore } from "@/stores";
|
||||
import { toast } from "sonner";
|
||||
import type { Product } from "@/lib/api/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ProductActionsProps {
|
||||
product: Product;
|
||||
}
|
||||
|
||||
export function ProductActions({ product }: ProductActionsProps) {
|
||||
const t = useTranslations();
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
|
||||
const addToCart = useCartStore((state) => state.addItem);
|
||||
const openCart = useCartStore((state) => state.openCart);
|
||||
const { toggleItem, isInWishlist } = useWishlistStore();
|
||||
|
||||
const isWishlisted = isInWishlist(product.id);
|
||||
const isOutOfStock = product.stock_quantity <= 0;
|
||||
const maxQuantity = Math.min(product.stock_quantity, 99);
|
||||
|
||||
const handleQuantityChange = (value: number) => {
|
||||
if (value >= 1 && value <= maxQuantity) {
|
||||
setQuantity(value);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddToCart = () => {
|
||||
addToCart(product, quantity);
|
||||
openCart();
|
||||
toast.success(t("common.addedToCart"));
|
||||
};
|
||||
|
||||
const handleToggleWishlist = () => {
|
||||
toggleItem(product);
|
||||
toast.success(
|
||||
isWishlisted ? t("common.removeFromWishlist") : t("common.addToWishlist")
|
||||
);
|
||||
};
|
||||
|
||||
const handleShare = async () => {
|
||||
const url = window.location.href;
|
||||
|
||||
if (navigator.share) {
|
||||
try {
|
||||
await navigator.share({
|
||||
title: product.name,
|
||||
text: product.short_description || product.name,
|
||||
url,
|
||||
});
|
||||
} catch {
|
||||
// User cancelled or share failed
|
||||
}
|
||||
} else {
|
||||
await navigator.clipboard.writeText(url);
|
||||
toast.success("Link copied to clipboard");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Quantity selector */}
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-sm font-medium">{t("common.quantity")}:</span>
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-10 w-10 rounded-r-none"
|
||||
onClick={() => handleQuantityChange(quantity - 1)}
|
||||
disabled={quantity <= 1 || isOutOfStock}
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</Button>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={maxQuantity}
|
||||
value={quantity}
|
||||
onChange={(e) => handleQuantityChange(parseInt(e.target.value) || 1)}
|
||||
className="h-10 w-16 rounded-none border-x-0 text-center [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
|
||||
disabled={isOutOfStock}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-10 w-10 rounded-l-none"
|
||||
onClick={() => handleQuantityChange(quantity + 1)}
|
||||
disabled={quantity >= maxQuantity || isOutOfStock}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Button
|
||||
size="lg"
|
||||
className="flex-1"
|
||||
disabled={isOutOfStock}
|
||||
onClick={handleAddToCart}
|
||||
>
|
||||
<ShoppingCart className="mr-2 h-5 w-5" />
|
||||
{isOutOfStock ? t("common.outOfStock") : t("common.addToCart")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="lg"
|
||||
variant="outline"
|
||||
onClick={handleToggleWishlist}
|
||||
>
|
||||
<Heart
|
||||
className={cn(
|
||||
"mr-2 h-5 w-5",
|
||||
isWishlisted && "fill-destructive text-destructive"
|
||||
)}
|
||||
/>
|
||||
{isWishlisted
|
||||
? t("common.removeFromWishlist")
|
||||
: t("common.addToWishlist")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Secondary actions */}
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={handleShare}>
|
||||
<Share2 className="mr-2 h-4 w-4" />
|
||||
{t("product.shareProduct")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
136
storefront/src/app/[locale]/product/[slug]/product-gallery.tsx
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Image from "next/image";
|
||||
import { ChevronLeft, ChevronRight, ZoomIn } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { getImageUrl, cn } from "@/lib/utils";
|
||||
import type { ProductImage } from "@/lib/api/types";
|
||||
|
||||
interface ProductGalleryProps {
|
||||
images: ProductImage[];
|
||||
productName: string;
|
||||
}
|
||||
|
||||
export function ProductGallery({ images, productName }: ProductGalleryProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
|
||||
const sortedImages = [...images].sort((a, b) => {
|
||||
if (a.is_primary) return -1;
|
||||
if (b.is_primary) return 1;
|
||||
return a.order - b.order;
|
||||
});
|
||||
|
||||
const selectedImage = sortedImages[selectedIndex];
|
||||
|
||||
const goToPrevious = () => {
|
||||
setSelectedIndex((prev) =>
|
||||
prev === 0 ? sortedImages.length - 1 : prev - 1
|
||||
);
|
||||
};
|
||||
|
||||
const goToNext = () => {
|
||||
setSelectedIndex((prev) =>
|
||||
prev === sortedImages.length - 1 ? 0 : prev + 1
|
||||
);
|
||||
};
|
||||
|
||||
if (sortedImages.length === 0) {
|
||||
return (
|
||||
<div className="aspect-square w-full rounded-lg bg-muted flex items-center justify-center">
|
||||
<span className="text-4xl font-bold text-muted-foreground/30">
|
||||
{productName.charAt(0)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Main image */}
|
||||
<div className="relative aspect-square overflow-hidden rounded-lg bg-muted">
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<button className="group relative h-full w-full">
|
||||
<Image
|
||||
src={getImageUrl(selectedImage.image)}
|
||||
alt={selectedImage.alt_text || productName}
|
||||
fill
|
||||
className="object-contain transition-transform group-hover:scale-105"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
priority
|
||||
/>
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-all group-hover:bg-black/10 group-hover:opacity-100">
|
||||
<ZoomIn className="h-8 w-8 text-white" />
|
||||
</div>
|
||||
</button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-4xl p-0">
|
||||
<div className="relative aspect-square">
|
||||
<Image
|
||||
src={getImageUrl(selectedImage.image)}
|
||||
alt={selectedImage.alt_text || productName}
|
||||
fill
|
||||
className="object-contain"
|
||||
sizes="90vw"
|
||||
/>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Navigation arrows */}
|
||||
{sortedImages.length > 1 && (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="absolute left-2 top-1/2 -translate-y-1/2 h-8 w-8 rounded-full opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-100 md:opacity-70"
|
||||
onClick={goToPrevious}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 rounded-full opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-100 md:opacity-70"
|
||||
onClick={goToNext}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Thumbnails */}
|
||||
{sortedImages.length > 1 && (
|
||||
<div className="flex gap-2 overflow-x-auto pb-2">
|
||||
{sortedImages.map((image, index) => (
|
||||
<button
|
||||
key={image.id}
|
||||
onClick={() => setSelectedIndex(index)}
|
||||
className={cn(
|
||||
"relative h-20 w-20 flex-shrink-0 overflow-hidden rounded-md border-2 transition-all",
|
||||
selectedIndex === index
|
||||
? "border-primary"
|
||||
: "border-transparent hover:border-muted-foreground/30"
|
||||
)}
|
||||
>
|
||||
<Image
|
||||
src={getImageUrl(image.image)}
|
||||
alt={image.alt_text || `${productName} ${index + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="80px"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
257
storefront/src/app/[locale]/register/page.tsx
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { Eye, EyeOff, UserPlus } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { useAuthStore } from "@/stores";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const registerSchema = z
|
||||
.object({
|
||||
firstName: z.string().min(1),
|
||||
lastName: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
confirmPassword: z.string().min(8),
|
||||
acceptTerms: z.boolean().refine((val) => val === true, {
|
||||
message: "You must accept the terms and conditions",
|
||||
}),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
message: "Passwords don't match",
|
||||
path: ["confirmPassword"],
|
||||
});
|
||||
|
||||
type RegisterFormData = z.infer<typeof registerSchema>;
|
||||
|
||||
export default function RegisterPage() {
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const { register, isLoading, error, clearError } = useAuthStore();
|
||||
|
||||
const form = useForm<RegisterFormData>({
|
||||
resolver: zodResolver(registerSchema),
|
||||
defaultValues: {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
password: "",
|
||||
confirmPassword: "",
|
||||
acceptTerms: false,
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: RegisterFormData) => {
|
||||
clearError();
|
||||
const success = await register({
|
||||
first_name: data.firstName,
|
||||
last_name: data.lastName,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
});
|
||||
|
||||
if (success) {
|
||||
toast.success(t("auth.register.success"));
|
||||
router.push("/");
|
||||
} else {
|
||||
toast.error(t("auth.register.error"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container flex min-h-[calc(100vh-200px)] items-center justify-center py-8">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">{t("auth.register.title")}</CardTitle>
|
||||
<CardDescription>{t("auth.register.subtitle")}</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="firstName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.register.firstName")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="lastName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.register.lastName")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.register.email")}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="email@example.com"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.register.password")}</FormLabel>
|
||||
<FormControl>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showPassword ? "text" : "password"}
|
||||
{...field}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="confirmPassword"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("auth.register.confirmPassword")}</FormLabel>
|
||||
<FormControl>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
{...field}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
|
||||
onClick={() =>
|
||||
setShowConfirmPassword(!showConfirmPassword)
|
||||
}
|
||||
>
|
||||
{showConfirmPassword ? (
|
||||
<EyeOff className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="acceptTerms"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-start space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="cursor-pointer text-sm font-normal leading-tight">
|
||||
{t("auth.register.acceptTerms")}
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex flex-col gap-4">
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
t("common.loading")
|
||||
) : (
|
||||
<>
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
{t("auth.register.submit")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
{t("auth.register.hasAccount")}{" "}
|
||||
<Link href="/login" className="text-primary hover:underline">
|
||||
{t("auth.register.signIn")}
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
80
storefront/src/app/[locale]/wishlist/page.tsx
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { Heart, ArrowRight, ShoppingCart, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useWishlistStore, useCartStore } from "@/stores";
|
||||
import { ProductGrid } from "@/components/products";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function WishlistPage() {
|
||||
const t = useTranslations();
|
||||
const { items, removeItem, clearWishlist } = useWishlistStore();
|
||||
const addToCart = useCartStore((state) => state.addItem);
|
||||
const openCart = useCartStore((state) => state.openCart);
|
||||
|
||||
const handleMoveToCart = (productId: string) => {
|
||||
const product = items.find((item) => item.id === productId);
|
||||
if (product) {
|
||||
addToCart(product);
|
||||
removeItem(productId);
|
||||
openCart();
|
||||
toast.success(t("common.addedToCart"));
|
||||
}
|
||||
};
|
||||
|
||||
const handleMoveAllToCart = () => {
|
||||
items.forEach((product) => {
|
||||
addToCart(product);
|
||||
});
|
||||
clearWishlist();
|
||||
openCart();
|
||||
toast.success(t("common.addedToCart"));
|
||||
};
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="container py-16">
|
||||
<div className="mx-auto max-w-md text-center">
|
||||
<Heart className="mx-auto h-16 w-16 text-muted-foreground" />
|
||||
<h1 className="mt-6 text-2xl font-bold">{t("account.wishlist.empty")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{t("account.wishlist.emptyMessage")}
|
||||
</p>
|
||||
<Button asChild className="mt-6">
|
||||
<Link href="/catalog">
|
||||
{t("common.continueShopping")}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container py-8">
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">{t("account.wishlist.title")}</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{items.length} {items.length === 1 ? "item" : "items"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={clearWishlist}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
{t("cart.clear")}
|
||||
</Button>
|
||||
<Button onClick={handleMoveAllToCart}>
|
||||
<ShoppingCart className="mr-2 h-4 w-4" />
|
||||
{t("account.wishlist.moveToCart")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProductGrid products={items} columns={4} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
storefront/src/app/favicon.ico
Normal file
|
After Width: | Height: | Size: 25 KiB |
125
storefront/src/app/globals.css
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
14
storefront/src/app/layout.tsx
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import type { Metadata } from "next";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "eVibes",
|
||||
description: "E-commerce storefront",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return children;
|
||||
}
|
||||
5
storefront/src/app/page.tsx
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function RootPage() {
|
||||
redirect("/ru");
|
||||
}
|
||||
176
storefront/src/components/cart/cart-sheet.tsx
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import Image from "next/image";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
SheetFooter,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Minus, Plus, Trash2, ShoppingBag } from "lucide-react";
|
||||
import { useCartStore } from "@/stores";
|
||||
import { formatPrice } from "@/lib/utils";
|
||||
|
||||
interface CartSheetProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function CartSheet({ children }: CartSheetProps) {
|
||||
const t = useTranslations();
|
||||
const { items, removeItem, updateQuantity, getSubtotal, isOpen, toggleCart, closeCart } =
|
||||
useCartStore();
|
||||
|
||||
const subtotal = getSubtotal();
|
||||
|
||||
return (
|
||||
<Sheet open={isOpen} onOpenChange={toggleCart}>
|
||||
<SheetTrigger asChild>{children}</SheetTrigger>
|
||||
<SheetContent className="flex w-full flex-col sm:max-w-lg">
|
||||
<SheetHeader>
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
<ShoppingBag className="h-5 w-5" />
|
||||
{t("cart.title")} ({items.length})
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center">
|
||||
<ShoppingBag className="h-16 w-16 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-lg font-medium">{t("cart.empty")}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("cart.emptyMessage")}
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild onClick={closeCart}>
|
||||
<Link href="/catalog">{t("common.continueShopping")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ScrollArea className="flex-1 -mx-6 px-6">
|
||||
<div className="space-y-4">
|
||||
{items.map((item) => {
|
||||
const price = item.product.sale_price
|
||||
? parseFloat(item.product.sale_price)
|
||||
: parseFloat(item.product.price);
|
||||
const primaryImage = item.product.images?.find(
|
||||
(img) => img.is_primary
|
||||
) || item.product.images?.[0];
|
||||
|
||||
return (
|
||||
<div key={item.product.id} className="flex gap-4">
|
||||
<div className="relative h-20 w-20 flex-shrink-0 overflow-hidden rounded-md border">
|
||||
{primaryImage ? (
|
||||
<Image
|
||||
src={primaryImage.image}
|
||||
alt={primaryImage.alt_text || item.product.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center bg-muted">
|
||||
<ShoppingBag className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col">
|
||||
<div className="flex justify-between">
|
||||
<Link
|
||||
href={`/product/${item.product.slug}`}
|
||||
className="font-medium hover:underline line-clamp-2"
|
||||
onClick={closeCart}
|
||||
>
|
||||
{item.product.name}
|
||||
</Link>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => removeItem(item.product.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-auto flex items-center justify-between">
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() =>
|
||||
updateQuantity(
|
||||
item.product.id,
|
||||
item.quantity - 1
|
||||
)
|
||||
}
|
||||
disabled={item.quantity <= 1}
|
||||
>
|
||||
<Minus className="h-3 w-3" />
|
||||
</Button>
|
||||
<span className="w-8 text-center text-sm">
|
||||
{item.quantity}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() =>
|
||||
updateQuantity(
|
||||
item.product.id,
|
||||
item.quantity + 1
|
||||
)
|
||||
}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="font-medium">
|
||||
{formatPrice(price * item.quantity)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div className="space-y-4 pt-4">
|
||||
<Separator />
|
||||
<div className="flex items-center justify-between text-base font-medium">
|
||||
<span>{t("common.subtotal")}</span>
|
||||
<span>{formatPrice(subtotal)}</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("common.shipping")} & {t("common.tax")} calculated at checkout
|
||||
</p>
|
||||
<SheetFooter className="flex-col gap-2 sm:flex-col">
|
||||
<Button asChild className="w-full" onClick={closeCart}>
|
||||
<Link href="/checkout">{t("cart.checkout")}</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
asChild
|
||||
className="w-full"
|
||||
onClick={closeCart}
|
||||
>
|
||||
<Link href="/cart">{t("cart.title")}</Link>
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
1
storefront/src/components/cart/index.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export { CartSheet } from "./cart-sheet";
|
||||
224
storefront/src/components/layout/footer.tsx
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Facebook,
|
||||
Instagram,
|
||||
Twitter,
|
||||
Youtube,
|
||||
Send,
|
||||
Mail,
|
||||
Phone,
|
||||
MapPin,
|
||||
} from "lucide-react";
|
||||
|
||||
interface FooterProps {
|
||||
siteParams?: {
|
||||
contact_email?: string;
|
||||
contact_phone?: string;
|
||||
address?: string;
|
||||
social_links?: {
|
||||
facebook?: string;
|
||||
instagram?: string;
|
||||
twitter?: string;
|
||||
telegram?: string;
|
||||
youtube?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export function Footer({ siteParams }: FooterProps) {
|
||||
const t = useTranslations();
|
||||
const projectName = process.env.NEXT_PUBLIC_PROJECT_NAME || "eVibes";
|
||||
const currentYear = new Date().getFullYear();
|
||||
|
||||
const socialLinks = siteParams?.social_links || {};
|
||||
|
||||
return (
|
||||
<footer className="border-t bg-muted/30">
|
||||
<div className="container py-12">
|
||||
<div className="grid gap-8 md:grid-cols-2 lg:grid-cols-4">
|
||||
{/* About */}
|
||||
<div className="space-y-4">
|
||||
<Link href="/" className="inline-block">
|
||||
<h3 className="text-xl font-bold">{projectName}</h3>
|
||||
</Link>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("footer.about.description")}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
{socialLinks.facebook && (
|
||||
<a
|
||||
href={socialLinks.facebook}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
<Facebook className="h-5 w-5" />
|
||||
</a>
|
||||
)}
|
||||
{socialLinks.instagram && (
|
||||
<a
|
||||
href={socialLinks.instagram}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
<Instagram className="h-5 w-5" />
|
||||
</a>
|
||||
)}
|
||||
{socialLinks.twitter && (
|
||||
<a
|
||||
href={socialLinks.twitter}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
<Twitter className="h-5 w-5" />
|
||||
</a>
|
||||
)}
|
||||
{socialLinks.youtube && (
|
||||
<a
|
||||
href={socialLinks.youtube}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
<Youtube className="h-5 w-5" />
|
||||
</a>
|
||||
)}
|
||||
{socialLinks.telegram && (
|
||||
<a
|
||||
href={socialLinks.telegram}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
<Send className="h-5 w-5" />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Customer Service */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-semibold">{t("footer.customerService.title")}</h3>
|
||||
<nav className="flex flex-col gap-2 text-sm">
|
||||
<Link
|
||||
href="/contact"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.customerService.contactUs")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/shipping"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.customerService.shippingInfo")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/returns"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.customerService.returns")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/faq"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.customerService.faq")}
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Legal */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-semibold">{t("footer.legal.title")}</h3>
|
||||
<nav className="flex flex-col gap-2 text-sm">
|
||||
<Link
|
||||
href="/privacy"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.legal.privacy")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/terms"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.legal.terms")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/cookies"
|
||||
className="text-muted-foreground hover:text-primary"
|
||||
>
|
||||
{t("footer.legal.cookies")}
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Contact & Newsletter */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-semibold">{t("footer.newsletter.title")}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("footer.newsletter.description")}
|
||||
</p>
|
||||
<form className="flex gap-2">
|
||||
<Input
|
||||
type="email"
|
||||
placeholder={t("footer.newsletter.placeholder")}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button type="submit" size="icon">
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Contact info */}
|
||||
<div className="space-y-2 pt-4 text-sm text-muted-foreground">
|
||||
{siteParams?.contact_email && (
|
||||
<a
|
||||
href={`mailto:${siteParams.contact_email}`}
|
||||
className="flex items-center gap-2 hover:text-primary"
|
||||
>
|
||||
<Mail className="h-4 w-4" />
|
||||
{siteParams.contact_email}
|
||||
</a>
|
||||
)}
|
||||
{siteParams?.contact_phone && (
|
||||
<a
|
||||
href={`tel:${siteParams.contact_phone}`}
|
||||
className="flex items-center gap-2 hover:text-primary"
|
||||
>
|
||||
<Phone className="h-4 w-4" />
|
||||
{siteParams.contact_phone}
|
||||
</a>
|
||||
)}
|
||||
{siteParams?.address && (
|
||||
<div className="flex items-start gap-2">
|
||||
<MapPin className="h-4 w-4 mt-0.5" />
|
||||
<span>{siteParams.address}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator className="my-8" />
|
||||
|
||||
{/* Copyright */}
|
||||
<div className="flex flex-col items-center justify-between gap-4 text-center text-sm text-muted-foreground md:flex-row">
|
||||
<p>
|
||||
© {currentYear} {projectName}. {t("footer.copyright")}
|
||||
</p>
|
||||
<div className="flex items-center gap-4">
|
||||
<span>Powered by eVibes</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
330
storefront/src/components/layout/header.tsx
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import {
|
||||
Search,
|
||||
ShoppingCart,
|
||||
Heart,
|
||||
User,
|
||||
Menu,
|
||||
X,
|
||||
ChevronDown,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useCartStore, useWishlistStore, useAuthStore } from "@/stores";
|
||||
import { CartSheet } from "@/components/cart/cart-sheet";
|
||||
import { LanguageSwitcher } from "@/components/layout/language-switcher";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface HeaderProps {
|
||||
categories?: { id: string; name: string; slug: string }[];
|
||||
}
|
||||
|
||||
export function Header({ categories = [] }: HeaderProps) {
|
||||
const t = useTranslations();
|
||||
const [isSearchOpen, setIsSearchOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
|
||||
const cartItemCount = useCartStore((state) => state.getItemCount());
|
||||
const wishlistItemCount = useWishlistStore((state) => state.getItemCount());
|
||||
const { isAuthenticated, user, logout } = useAuthStore();
|
||||
|
||||
const projectName = process.env.NEXT_PUBLIC_PROJECT_NAME || "eVibes";
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (searchQuery.trim()) {
|
||||
window.location.href = `/catalog?search=${encodeURIComponent(searchQuery)}`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
{/* Top bar */}
|
||||
<div className="hidden border-b md:block">
|
||||
<div className="container flex h-9 items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-muted-foreground">
|
||||
{t("footer.about.description")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<LanguageSwitcher />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main header */}
|
||||
<div className="container">
|
||||
<div className="flex h-16 items-center justify-between gap-4">
|
||||
{/* Mobile menu trigger */}
|
||||
<Sheet open={isMobileMenuOpen} onOpenChange={setIsMobileMenuOpen}>
|
||||
<SheetTrigger asChild className="md:hidden">
|
||||
<Button variant="ghost" size="icon">
|
||||
<Menu className="h-5 w-5" />
|
||||
<span className="sr-only">Toggle menu</span>
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="w-[300px] sm:w-[400px]">
|
||||
<nav className="flex flex-col gap-4">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-2xl font-bold"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
{projectName}
|
||||
</Link>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-lg hover:text-primary"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
{t("nav.home")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/catalog"
|
||||
className="text-lg hover:text-primary"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
{t("nav.catalog")}
|
||||
</Link>
|
||||
{categories.slice(0, 6).map((category) => (
|
||||
<Link
|
||||
key={category.id}
|
||||
href={`/catalog/${category.slug}`}
|
||||
className="pl-4 text-muted-foreground hover:text-primary"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
{category.name}
|
||||
</Link>
|
||||
))}
|
||||
<Link
|
||||
href="/blog"
|
||||
className="text-lg hover:text-primary"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
{t("nav.blog")}
|
||||
</Link>
|
||||
<Link
|
||||
href="/contact"
|
||||
className="text-lg hover:text-primary"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
>
|
||||
{t("nav.contact")}
|
||||
</Link>
|
||||
</div>
|
||||
<div className="mt-4 border-t pt-4">
|
||||
<LanguageSwitcher />
|
||||
</div>
|
||||
</nav>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Logo */}
|
||||
<Link href="/" className="flex items-center gap-2">
|
||||
<span className="text-xl font-bold">{projectName}</span>
|
||||
</Link>
|
||||
|
||||
{/* Desktop navigation */}
|
||||
<nav className="hidden items-center gap-6 md:flex">
|
||||
<Link href="/" className="text-sm font-medium hover:text-primary">
|
||||
{t("nav.home")}
|
||||
</Link>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="flex items-center gap-1 px-0"
|
||||
>
|
||||
{t("nav.catalog")}
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-56">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/catalog">{t("common.viewAll")}</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
{categories.slice(0, 8).map((category) => (
|
||||
<DropdownMenuItem key={category.id} asChild>
|
||||
<Link href={`/catalog/${category.slug}`}>
|
||||
{category.name}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Link
|
||||
href="/blog"
|
||||
className="text-sm font-medium hover:text-primary"
|
||||
>
|
||||
{t("nav.blog")}
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
href="/contact"
|
||||
className="text-sm font-medium hover:text-primary"
|
||||
>
|
||||
{t("nav.contact")}
|
||||
</Link>
|
||||
</nav>
|
||||
|
||||
{/* Search bar - Desktop */}
|
||||
<div className="hidden flex-1 items-center justify-center px-4 lg:flex">
|
||||
<form onSubmit={handleSearch} className="w-full max-w-md">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={t("common.searchPlaceholder")}
|
||||
className="w-full pl-10"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Mobile search toggle */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="lg:hidden"
|
||||
onClick={() => setIsSearchOpen(!isSearchOpen)}
|
||||
>
|
||||
{isSearchOpen ? (
|
||||
<X className="h-5 w-5" />
|
||||
) : (
|
||||
<Search className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Wishlist */}
|
||||
<Link href="/wishlist">
|
||||
<Button variant="ghost" size="icon" className="relative">
|
||||
<Heart className="h-5 w-5" />
|
||||
{wishlistItemCount > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-1 -top-1 h-5 w-5 rounded-full p-0 text-xs"
|
||||
>
|
||||
{wishlistItemCount}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</Link>
|
||||
|
||||
{/* Cart */}
|
||||
<CartSheet>
|
||||
<Button variant="ghost" size="icon" className="relative">
|
||||
<ShoppingCart className="h-5 w-5" />
|
||||
{cartItemCount > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-1 -top-1 h-5 w-5 rounded-full p-0 text-xs"
|
||||
>
|
||||
{cartItemCount}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</CartSheet>
|
||||
|
||||
{/* User menu */}
|
||||
{isAuthenticated ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<User className="h-5 w-5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<div className="px-2 py-1.5">
|
||||
<p className="text-sm font-medium">
|
||||
{user?.first_name} {user?.last_name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{user?.email}
|
||||
</p>
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/account">{t("nav.account")}</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/account/orders">{t("nav.orders")}</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/wishlist">{t("nav.wishlist")}</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={logout}>
|
||||
{t("nav.logout")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<div className="hidden items-center gap-2 sm:flex">
|
||||
<Link href="/login">
|
||||
<Button variant="ghost" size="sm">
|
||||
{t("nav.login")}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/register">
|
||||
<Button size="sm">{t("nav.register")}</Button>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile user icon when not authenticated */}
|
||||
{!isAuthenticated && (
|
||||
<Link href="/login" className="sm:hidden">
|
||||
<Button variant="ghost" size="icon">
|
||||
<User className="h-5 w-5" />
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mobile search bar */}
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden transition-all duration-300 lg:hidden",
|
||||
isSearchOpen ? "h-14 pb-3" : "h-0"
|
||||
)}
|
||||
>
|
||||
<form onSubmit={handleSearch}>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder={t("common.searchPlaceholder")}
|
||||
className="w-full pl-10"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
3
storefront/src/components/layout/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export { Header } from "./header";
|
||||
export { Footer } from "./footer";
|
||||
export { LanguageSwitcher } from "./language-switcher";
|
||||
53
storefront/src/components/layout/language-switcher.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"use client";
|
||||
|
||||
import { useLocale } from "next-intl";
|
||||
import { usePathname, useRouter } from "@/i18n/navigation";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Globe } from "lucide-react";
|
||||
|
||||
const languages = [
|
||||
{ code: "en", name: "English", flag: "🇬🇧" },
|
||||
{ code: "ru", name: "Русский", flag: "🇷🇺" },
|
||||
];
|
||||
|
||||
export function LanguageSwitcher() {
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
const currentLanguage = languages.find((lang) => lang.code === locale);
|
||||
|
||||
const handleLanguageChange = (langCode: string) => {
|
||||
router.replace(pathname, { locale: langCode });
|
||||
};
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="gap-2">
|
||||
<Globe className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">{currentLanguage?.name}</span>
|
||||
<span className="sm:hidden">{currentLanguage?.flag}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{languages.map((lang) => (
|
||||
<DropdownMenuItem
|
||||
key={lang.code}
|
||||
onClick={() => handleLanguageChange(lang.code)}
|
||||
className={locale === lang.code ? "bg-accent" : ""}
|
||||
>
|
||||
<span className="mr-2">{lang.flag}</span>
|
||||
{lang.name}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
3
storefront/src/components/products/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export { ProductCard } from "./product-card";
|
||||
export { ProductGrid } from "./product-grid";
|
||||
export { ProductCarousel } from "./product-carousel";
|
||||
190
storefront/src/components/products/product-card.tsx
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { Heart, ShoppingCart, Eye } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useCartStore, useWishlistStore } from "@/stores";
|
||||
import { formatPrice, getDiscountPercentage, getImageUrl } from "@/lib/utils";
|
||||
import type { Product } from "@/lib/api/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ProductCardProps {
|
||||
product: Product;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ProductCard({ product, className }: ProductCardProps) {
|
||||
const t = useTranslations();
|
||||
const addToCart = useCartStore((state) => state.addItem);
|
||||
const openCart = useCartStore((state) => state.openCart);
|
||||
const { toggleItem, isInWishlist } = useWishlistStore();
|
||||
|
||||
const primaryImage =
|
||||
product.images?.find((img) => img.is_primary) || product.images?.[0];
|
||||
const hasDiscount = product.sale_price && product.is_on_sale;
|
||||
const discountPercentage = hasDiscount
|
||||
? getDiscountPercentage(product.price, product.sale_price!)
|
||||
: 0;
|
||||
const isWishlisted = isInWishlist(product.id);
|
||||
const isOutOfStock = product.stock_quantity <= 0;
|
||||
|
||||
const handleAddToCart = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!isOutOfStock) {
|
||||
addToCart(product);
|
||||
openCart();
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleWishlist = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
toggleItem(product);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={cn(
|
||||
"group relative overflow-hidden transition-all hover:shadow-lg",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Link href={`/product/${product.slug}`} className="block">
|
||||
{/* Image container */}
|
||||
<div className="relative aspect-square overflow-hidden bg-muted">
|
||||
{primaryImage ? (
|
||||
<Image
|
||||
src={getImageUrl(primaryImage.image)}
|
||||
alt={primaryImage.alt_text || product.name}
|
||||
fill
|
||||
className="object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<ShoppingCart className="h-12 w-12 text-muted-foreground/50" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Badges */}
|
||||
<div className="absolute left-2 top-2 flex flex-col gap-1">
|
||||
{hasDiscount && (
|
||||
<Badge variant="destructive">-{discountPercentage}%</Badge>
|
||||
)}
|
||||
{product.is_new && (
|
||||
<Badge variant="secondary">{t("nav.new")}</Badge>
|
||||
)}
|
||||
{isOutOfStock && (
|
||||
<Badge variant="outline" className="bg-background/80">
|
||||
{t("common.outOfStock")}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Quick actions */}
|
||||
<div className="absolute right-2 top-2 flex flex-col gap-1 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="h-8 w-8 rounded-full"
|
||||
onClick={handleToggleWishlist}
|
||||
>
|
||||
<Heart
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
isWishlisted && "fill-destructive text-destructive"
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="h-8 w-8 rounded-full"
|
||||
asChild
|
||||
>
|
||||
<Link href={`/product/${product.slug}`}>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Add to cart button */}
|
||||
<div className="absolute bottom-0 left-0 right-0 translate-y-full bg-background/95 p-2 transition-transform group-hover:translate-y-0">
|
||||
<Button
|
||||
className="w-full"
|
||||
size="sm"
|
||||
disabled={isOutOfStock}
|
||||
onClick={handleAddToCart}
|
||||
>
|
||||
<ShoppingCart className="mr-2 h-4 w-4" />
|
||||
{isOutOfStock ? t("common.outOfStock") : t("common.addToCart")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<CardContent className="p-4">
|
||||
{/* Category */}
|
||||
{product.category && (
|
||||
<p className="mb-1 text-xs text-muted-foreground">
|
||||
{product.category.name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Name */}
|
||||
<h3 className="line-clamp-2 font-medium leading-tight group-hover:text-primary">
|
||||
{product.name}
|
||||
</h3>
|
||||
|
||||
{/* Price */}
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
{hasDiscount ? (
|
||||
<>
|
||||
<span className="text-lg font-bold text-destructive">
|
||||
{formatPrice(product.sale_price!)}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground line-through">
|
||||
{formatPrice(product.price)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-lg font-bold">
|
||||
{formatPrice(product.price)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Rating */}
|
||||
{product.average_rating > 0 && (
|
||||
<div className="mt-2 flex items-center gap-1">
|
||||
<div className="flex">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<svg
|
||||
key={i}
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
i < Math.round(product.average_rating)
|
||||
? "fill-yellow-400 text-yellow-400"
|
||||
: "fill-muted text-muted"
|
||||
)}
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
({product.reviews_count})
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Link>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
57
storefront/src/components/products/product-carousel.tsx
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
"use client";
|
||||
|
||||
import { ProductCard } from "./product-card";
|
||||
import type { Product } from "@/lib/api/types";
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselNext,
|
||||
CarouselPrevious,
|
||||
} from "@/components/ui/carousel";
|
||||
|
||||
interface ProductCarouselProps {
|
||||
products: Product[];
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
}
|
||||
|
||||
export function ProductCarousel({
|
||||
products,
|
||||
title,
|
||||
subtitle,
|
||||
}: ProductCarouselProps) {
|
||||
if (products.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{(title || subtitle) && (
|
||||
<div className="space-y-1">
|
||||
{title && <h2 className="text-2xl font-bold">{title}</h2>}
|
||||
{subtitle && <p className="text-muted-foreground">{subtitle}</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Carousel
|
||||
opts={{
|
||||
align: "start",
|
||||
loop: products.length > 4,
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
<CarouselContent className="-ml-2 md:-ml-4">
|
||||
{products.map((product) => (
|
||||
<CarouselItem
|
||||
key={product.id}
|
||||
className="pl-2 md:pl-4 basis-1/2 md:basis-1/3 lg:basis-1/4"
|
||||
>
|
||||
<ProductCard product={product} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
<CarouselPrevious className="hidden md:flex -left-12" />
|
||||
<CarouselNext className="hidden md:flex -right-12" />
|
||||
</Carousel>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
30
storefront/src/components/products/product-grid.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { ProductCard } from "./product-card";
|
||||
import type { Product } from "@/lib/api/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ProductGridProps {
|
||||
products: Product[];
|
||||
className?: string;
|
||||
columns?: 2 | 3 | 4 | 5;
|
||||
}
|
||||
|
||||
export function ProductGrid({
|
||||
products,
|
||||
className,
|
||||
columns = 4,
|
||||
}: ProductGridProps) {
|
||||
const gridCols = {
|
||||
2: "grid-cols-1 sm:grid-cols-2",
|
||||
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
|
||||
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",
|
||||
5: "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5",
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("grid gap-4 md:gap-6", gridCols[columns], className)}>
|
||||
{products.map((product) => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
storefront/src/components/providers/index.tsx
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { useState } from "react";
|
||||
|
||||
interface ProvidersProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Providers({ children }: ProvidersProps) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
{children}
|
||||
<Toaster position="top-right" richColors />
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
66
storefront/src/components/ui/accordion.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Accordion({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
||||
}
|
||||
|
||||
function AccordionItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
className={cn("border-b last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
)
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||
53
storefront/src/components/ui/avatar.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback }
|
||||
46
storefront/src/components/ui/badge.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
109
storefront/src/components/ui/breadcrumb.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
||||
}
|
||||
|
||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
className={cn(
|
||||
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-item"
|
||||
className={cn("inline-flex items-center gap-1.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
asChild,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="breadcrumb-link"
|
||||
className={cn("hover:text-foreground transition-colors", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-page"
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("text-foreground font-normal", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-separator"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:size-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-ellipsis"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
62
storefront/src/components/ui/button.tsx
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
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:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input 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",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"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 : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
92
storefront/src/components/ui/card.tsx
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
241
storefront/src/components/ui/carousel.tsx
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function Carousel({
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) return
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) return
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
data-slot="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={carouselRef}
|
||||
className="overflow-hidden"
|
||||
data-slot="carousel-content"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
data-slot="carousel-item"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselPrevious({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-previous"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -left-12 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeft />
|
||||
<span className="sr-only">Previous slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselNext({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-next"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -right-12 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRight />
|
||||
<span className="sr-only">Next slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
32
storefront/src/components/ui/checkbox.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
184
storefront/src/components/ui/command.tsx
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
"use client"
|
||||
|
||||
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(
|
||||
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[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(
|
||||
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden 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(
|
||||
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("bg-border -mx-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground 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 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
143
storefront/src/components/ui/dialog.tsx
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
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(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
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(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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 p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_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, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
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-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
257
storefront/src/components/ui/dropdown-menu.tsx
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
167
storefront/src/components/ui/form.tsx
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import type * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
21
storefront/src/components/ui/input.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
24
storefront/src/components/ui/label.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
168
storefront/src/components/ui/navigation-menu.tsx
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import * as React from "react"
|
||||
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function NavigationMenu({
|
||||
className,
|
||||
children,
|
||||
viewport = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
|
||||
viewport?: boolean
|
||||
}) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Root
|
||||
data-slot="navigation-menu"
|
||||
data-viewport={viewport}
|
||||
className={cn(
|
||||
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{viewport && <NavigationMenuViewport />}
|
||||
</NavigationMenuPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.List
|
||||
data-slot="navigation-menu-list"
|
||||
className={cn(
|
||||
"group flex flex-1 list-none items-center justify-center gap-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Item
|
||||
data-slot="navigation-menu-item"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
)
|
||||
|
||||
function NavigationMenuTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Trigger
|
||||
data-slot="navigation-menu-trigger"
|
||||
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}{" "}
|
||||
<ChevronDownIcon
|
||||
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</NavigationMenuPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Content
|
||||
data-slot="navigation-menu-content"
|
||||
className={cn(
|
||||
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
|
||||
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuViewport({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute top-full left-0 isolate z-50 flex justify-center"
|
||||
)}
|
||||
>
|
||||
<NavigationMenuPrimitive.Viewport
|
||||
data-slot="navigation-menu-viewport"
|
||||
className={cn(
|
||||
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuLink({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Link
|
||||
data-slot="navigation-menu-link"
|
||||
className={cn(
|
||||
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuIndicator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Indicator
|
||||
data-slot="navigation-menu-indicator"
|
||||
className={cn(
|
||||
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
|
||||
</NavigationMenuPrimitive.Indicator>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuContent,
|
||||
NavigationMenuTrigger,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuIndicator,
|
||||
NavigationMenuViewport,
|
||||
navigationMenuTriggerStyle,
|
||||
}
|
||||
48
storefront/src/components/ui/popover.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
45
storefront/src/components/ui/radio-group.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
|
||||
import { CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function RadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Root
|
||||
data-slot="radio-group"
|
||||
className={cn("grid gap-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function RadioGroupItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<RadioGroupPrimitive.Indicator
|
||||
data-slot="radio-group-indicator"
|
||||
className="relative flex items-center justify-center"
|
||||
>
|
||||
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
|
||||
</RadioGroupPrimitive.Indicator>
|
||||
</RadioGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { RadioGroup, RadioGroupItem }
|
||||
58
storefront/src/components/ui/scroll-area.tsx
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
190
storefront/src/components/ui/select.tsx
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "item-aligned",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
data-slot="select-item-indicator"
|
||||
className="absolute right-2 flex size-3.5 items-center justify-center"
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
28
storefront/src/components/ui/separator.tsx
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
139
storefront/src/components/ui/sheet.tsx
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
13
storefront/src/components/ui/skeleton.tsx
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
40
storefront/src/components/ui/sonner.tsx
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"use client"
|
||||
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
66
storefront/src/components/ui/tabs.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
18
storefront/src/components/ui/textarea.tsx
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
5
storefront/src/i18n/navigation.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { createNavigation } from "next-intl/navigation";
|
||||
import { routing } from "./routing";
|
||||
|
||||
export const { Link, redirect, usePathname, useRouter, getPathname } =
|
||||
createNavigation(routing);
|
||||
15
storefront/src/i18n/request.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { getRequestConfig } from "next-intl/server";
|
||||
import { routing } from "./routing";
|
||||
|
||||
export default getRequestConfig(async ({ requestLocale }) => {
|
||||
let locale = await requestLocale;
|
||||
|
||||
if (!locale || !routing.locales.includes(locale as "en" | "ru")) {
|
||||
locale = routing.defaultLocale;
|
||||
}
|
||||
|
||||
return {
|
||||
locale,
|
||||
messages: (await import(`../../messages/${locale}.json`)).default,
|
||||
};
|
||||
});
|
||||
7
storefront/src/i18n/routing.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { defineRouting } from "next-intl/routing";
|
||||
|
||||
export const routing = defineRouting({
|
||||
locales: ["en", "ru"],
|
||||
defaultLocale: "ru",
|
||||
localePrefix: "as-needed",
|
||||
});
|
||||
189
storefront/src/lib/api/client.ts
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
const API_URL = process.env.NEXT_PUBLIC_API_URL || "https://api.itoption.ru";
|
||||
|
||||
export interface ApiError {
|
||||
message: string;
|
||||
status: number;
|
||||
details?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
count: number;
|
||||
next: string | null;
|
||||
previous: string | null;
|
||||
results: T[];
|
||||
}
|
||||
|
||||
class ApiClient {
|
||||
private baseUrl: string;
|
||||
private defaultHeaders: HeadersInit;
|
||||
|
||||
constructor(baseUrl: string) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.defaultHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
private getAuthHeader(): HeadersInit {
|
||||
if (typeof window === "undefined") return {};
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (token) {
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private async handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
let errorData;
|
||||
try {
|
||||
errorData = await response.json();
|
||||
} catch {
|
||||
errorData = { message: response.statusText };
|
||||
}
|
||||
|
||||
const error: ApiError = {
|
||||
message: errorData.detail || errorData.message || "An error occurred",
|
||||
status: response.status,
|
||||
details: errorData,
|
||||
};
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async get<T>(
|
||||
endpoint: string,
|
||||
params?: Record<string, string | number | boolean | undefined>,
|
||||
options?: { cache?: RequestCache; revalidate?: number; tags?: string[] }
|
||||
): Promise<T> {
|
||||
const url = new URL(`${this.baseUrl}${endpoint}`);
|
||||
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== "") {
|
||||
url.searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
method: "GET",
|
||||
headers: {
|
||||
...this.defaultHeaders,
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
cache: options?.cache,
|
||||
next: options?.revalidate
|
||||
? { revalidate: options.revalidate, tags: options.tags }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
return this.handleResponse<T>(response);
|
||||
}
|
||||
|
||||
async post<T>(endpoint: string, data?: unknown): Promise<T> {
|
||||
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...this.defaultHeaders,
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
|
||||
return this.handleResponse<T>(response);
|
||||
}
|
||||
|
||||
async put<T>(endpoint: string, data: unknown): Promise<T> {
|
||||
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
...this.defaultHeaders,
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
return this.handleResponse<T>(response);
|
||||
}
|
||||
|
||||
async patch<T>(endpoint: string, data: unknown): Promise<T> {
|
||||
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
...this.defaultHeaders,
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
return this.handleResponse<T>(response);
|
||||
}
|
||||
|
||||
async delete<T>(endpoint: string): Promise<T> {
|
||||
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
...this.defaultHeaders,
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
});
|
||||
|
||||
return this.handleResponse<T>(response);
|
||||
}
|
||||
}
|
||||
|
||||
export const apiClient = new ApiClient(API_URL);
|
||||
|
||||
export function getServerApiClient(locale?: string) {
|
||||
const headers: HeadersInit = {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
};
|
||||
|
||||
if (locale) {
|
||||
headers["Accept-Language"] = locale;
|
||||
}
|
||||
|
||||
return {
|
||||
async get<T>(
|
||||
endpoint: string,
|
||||
params?: Record<string, string | number | boolean | undefined>,
|
||||
options?: { cache?: RequestCache; revalidate?: number; tags?: string[] }
|
||||
): Promise<T> {
|
||||
const url = new URL(`${API_URL}${endpoint}`);
|
||||
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== "") {
|
||||
url.searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
method: "GET",
|
||||
headers,
|
||||
cache: options?.cache,
|
||||
next: options?.revalidate
|
||||
? { revalidate: options.revalidate, tags: options.tags }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API Error: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
};
|
||||
}
|
||||
374
storefront/src/lib/api/endpoints.ts
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
import { apiClient, getServerApiClient, PaginatedResponse } from "./client";
|
||||
import type {
|
||||
Product,
|
||||
Category,
|
||||
Brand,
|
||||
ProductTag,
|
||||
Order,
|
||||
Address,
|
||||
Wishlist,
|
||||
Feedback,
|
||||
PromoCode,
|
||||
Promotion,
|
||||
BlogPost,
|
||||
SiteParameters,
|
||||
AuthTokens,
|
||||
LoginCredentials,
|
||||
RegisterData,
|
||||
User,
|
||||
ProductFilters,
|
||||
SearchResult,
|
||||
} from "./types";
|
||||
|
||||
// Products
|
||||
export const productsApi = {
|
||||
getAll: (filters?: ProductFilters) =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", filters as Record<string, string | number | boolean | undefined>),
|
||||
|
||||
getBySlug: (slug: string) =>
|
||||
apiClient.get<Product>(`/core/products/${slug}/`),
|
||||
|
||||
getById: (id: string) =>
|
||||
apiClient.get<Product>(`/core/products/${id}/`),
|
||||
|
||||
getFeatured: () =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", {
|
||||
is_featured: true,
|
||||
page_size: 8,
|
||||
}),
|
||||
|
||||
getNew: () =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", {
|
||||
is_new: true,
|
||||
page_size: 8,
|
||||
}),
|
||||
|
||||
getOnSale: () =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", {
|
||||
is_on_sale: true,
|
||||
page_size: 8,
|
||||
}),
|
||||
|
||||
getByCategory: (categorySlug: string, filters?: ProductFilters) =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", {
|
||||
...filters,
|
||||
category: categorySlug,
|
||||
} as Record<string, string | number | boolean | undefined>),
|
||||
|
||||
getByBrand: (brandSlug: string, filters?: ProductFilters) =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", {
|
||||
...filters,
|
||||
brand: brandSlug,
|
||||
} as Record<string, string | number | boolean | undefined>),
|
||||
|
||||
search: (query: string, filters?: ProductFilters) =>
|
||||
apiClient.get<PaginatedResponse<Product>>("/core/products/", {
|
||||
...filters,
|
||||
search: query,
|
||||
} as Record<string, string | number | boolean | undefined>),
|
||||
|
||||
getRelated: (productId: string) =>
|
||||
apiClient.get<Product[]>(`/core/products/${productId}/related/`),
|
||||
};
|
||||
|
||||
// Server-side products API
|
||||
export const serverProductsApi = {
|
||||
getAll: (locale: string, filters?: ProductFilters) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<Product>>(
|
||||
"/core/products/",
|
||||
filters as Record<string, string | number | boolean | undefined>,
|
||||
{ revalidate: 60, tags: ["products"] }
|
||||
);
|
||||
},
|
||||
|
||||
getBySlug: (locale: string, slug: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<Product>(
|
||||
`/core/products/${slug}/`,
|
||||
undefined,
|
||||
{ revalidate: 60, tags: ["product", slug] }
|
||||
);
|
||||
},
|
||||
|
||||
getFeatured: (locale: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<Product>>(
|
||||
"/core/products/",
|
||||
{ is_featured: true, page_size: 8 },
|
||||
{ revalidate: 300, tags: ["featured-products"] }
|
||||
);
|
||||
},
|
||||
|
||||
getNew: (locale: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<Product>>(
|
||||
"/core/products/",
|
||||
{ is_new: true, page_size: 8 },
|
||||
{ revalidate: 300, tags: ["new-products"] }
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Categories
|
||||
export const categoriesApi = {
|
||||
getAll: () =>
|
||||
apiClient.get<PaginatedResponse<Category>>("/core/categories/"),
|
||||
|
||||
getBySlug: (slug: string) =>
|
||||
apiClient.get<Category>(`/core/categories/${slug}/`),
|
||||
|
||||
getTree: () =>
|
||||
apiClient.get<Category[]>("/core/categories/tree/"),
|
||||
};
|
||||
|
||||
export const serverCategoriesApi = {
|
||||
getAll: (locale: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<Category>>(
|
||||
"/core/categories/",
|
||||
undefined,
|
||||
{ revalidate: 600, tags: ["categories"] }
|
||||
);
|
||||
},
|
||||
|
||||
getBySlug: (locale: string, slug: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<Category>(
|
||||
`/core/categories/${slug}/`,
|
||||
undefined,
|
||||
{ revalidate: 300, tags: ["category", slug] }
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Brands
|
||||
export const brandsApi = {
|
||||
getAll: () =>
|
||||
apiClient.get<PaginatedResponse<Brand>>("/core/brands/"),
|
||||
|
||||
getBySlug: (slug: string) =>
|
||||
apiClient.get<Brand>(`/core/brands/${slug}/`),
|
||||
};
|
||||
|
||||
export const serverBrandsApi = {
|
||||
getAll: (locale: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<Brand>>(
|
||||
"/core/brands/",
|
||||
undefined,
|
||||
{ revalidate: 600, tags: ["brands"] }
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Tags
|
||||
export const tagsApi = {
|
||||
getAll: () =>
|
||||
apiClient.get<PaginatedResponse<ProductTag>>("/core/product_tags/"),
|
||||
};
|
||||
|
||||
// Orders
|
||||
export const ordersApi = {
|
||||
getAll: () =>
|
||||
apiClient.get<PaginatedResponse<Order>>("/core/orders/"),
|
||||
|
||||
getById: (id: string) =>
|
||||
apiClient.get<Order>(`/core/orders/${id}/`),
|
||||
|
||||
create: (data: Partial<Order>) =>
|
||||
apiClient.post<Order>("/core/orders/", data),
|
||||
|
||||
update: (id: string, data: Partial<Order>) =>
|
||||
apiClient.patch<Order>(`/core/orders/${id}/`, data),
|
||||
|
||||
cancel: (id: string) =>
|
||||
apiClient.post<Order>(`/core/orders/${id}/cancel/`),
|
||||
};
|
||||
|
||||
// Order Products (Cart Items in Order)
|
||||
export const orderProductsApi = {
|
||||
add: (orderId: string, productId: string, quantity: number) =>
|
||||
apiClient.post("/core/order_products/", {
|
||||
order: orderId,
|
||||
product: productId,
|
||||
quantity,
|
||||
}),
|
||||
|
||||
update: (id: string, quantity: number) =>
|
||||
apiClient.patch(`/core/order_products/${id}/`, { quantity }),
|
||||
|
||||
remove: (id: string) =>
|
||||
apiClient.delete(`/core/order_products/${id}/`),
|
||||
};
|
||||
|
||||
// Addresses
|
||||
export const addressesApi = {
|
||||
getAll: () =>
|
||||
apiClient.get<PaginatedResponse<Address>>("/core/addresses/"),
|
||||
|
||||
getById: (id: string) =>
|
||||
apiClient.get<Address>(`/core/addresses/${id}/`),
|
||||
|
||||
create: (data: Omit<Address, "id" | "uuid">) =>
|
||||
apiClient.post<Address>("/core/addresses/", data),
|
||||
|
||||
update: (id: string, data: Partial<Address>) =>
|
||||
apiClient.patch<Address>(`/core/addresses/${id}/`, data),
|
||||
|
||||
delete: (id: string) =>
|
||||
apiClient.delete(`/core/addresses/${id}/`),
|
||||
|
||||
setDefault: (id: string) =>
|
||||
apiClient.post(`/core/addresses/${id}/set_default/`),
|
||||
};
|
||||
|
||||
// Wishlist
|
||||
export const wishlistApi = {
|
||||
get: () =>
|
||||
apiClient.get<Wishlist>("/core/wishlists/"),
|
||||
|
||||
addProduct: (productId: string) =>
|
||||
apiClient.post("/core/wishlists/add_product/", { product: productId }),
|
||||
|
||||
removeProduct: (productId: string) =>
|
||||
apiClient.post("/core/wishlists/remove_product/", { product: productId }),
|
||||
|
||||
clear: () =>
|
||||
apiClient.post("/core/wishlists/clear/"),
|
||||
};
|
||||
|
||||
// Feedbacks (Reviews)
|
||||
export const feedbacksApi = {
|
||||
getByProduct: (productId: string) =>
|
||||
apiClient.get<PaginatedResponse<Feedback>>("/core/feedbacks/", {
|
||||
product: productId,
|
||||
}),
|
||||
|
||||
create: (data: { product: string; rating: number; title?: string; comment: string }) =>
|
||||
apiClient.post<Feedback>("/core/feedbacks/", data),
|
||||
};
|
||||
|
||||
// Promo Codes
|
||||
export const promoCodesApi = {
|
||||
validate: (code: string) =>
|
||||
apiClient.post<PromoCode>("/core/promo_codes/validate/", { code }),
|
||||
};
|
||||
|
||||
// Promotions
|
||||
export const promotionsApi = {
|
||||
getAll: () =>
|
||||
apiClient.get<PaginatedResponse<Promotion>>("/core/promotions/"),
|
||||
|
||||
getActive: () =>
|
||||
apiClient.get<PaginatedResponse<Promotion>>("/core/promotions/", {
|
||||
is_active: true,
|
||||
}),
|
||||
|
||||
getBySlug: (slug: string) =>
|
||||
apiClient.get<Promotion>(`/core/promotions/${slug}/`),
|
||||
};
|
||||
|
||||
export const serverPromotionsApi = {
|
||||
getActive: (locale: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<Promotion>>(
|
||||
"/core/promotions/",
|
||||
{ is_active: true },
|
||||
{ revalidate: 300, tags: ["promotions"] }
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Blog
|
||||
export const blogApi = {
|
||||
getPosts: (page?: number, pageSize?: number) =>
|
||||
apiClient.get<PaginatedResponse<BlogPost>>("/blog/posts/", {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}),
|
||||
|
||||
getPostBySlug: (slug: string) =>
|
||||
apiClient.get<BlogPost>(`/blog/posts/${slug}/`),
|
||||
};
|
||||
|
||||
export const serverBlogApi = {
|
||||
getPosts: (locale: string, page?: number) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<PaginatedResponse<BlogPost>>(
|
||||
"/blog/posts/",
|
||||
{ page },
|
||||
{ revalidate: 300, tags: ["blog-posts"] }
|
||||
);
|
||||
},
|
||||
|
||||
getPostBySlug: (locale: string, slug: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<BlogPost>(
|
||||
`/blog/posts/${slug}/`,
|
||||
undefined,
|
||||
{ revalidate: 300, tags: ["blog-post", slug] }
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Auth
|
||||
export const authApi = {
|
||||
login: (credentials: LoginCredentials) =>
|
||||
apiClient.post<AuthTokens>("/authv/obtain/", credentials),
|
||||
|
||||
register: (data: RegisterData) =>
|
||||
apiClient.post<User>("/authv/users/", data),
|
||||
|
||||
refresh: (refreshToken: string) =>
|
||||
apiClient.post<{ access: string }>("/authv/refresh/", {
|
||||
refresh: refreshToken,
|
||||
}),
|
||||
|
||||
verify: (token: string) =>
|
||||
apiClient.post("/authv/verify/", { token }),
|
||||
|
||||
getProfile: () =>
|
||||
apiClient.get<User>("/authv/users/me/"),
|
||||
|
||||
updateProfile: (data: Partial<User>) =>
|
||||
apiClient.patch<User>("/authv/users/me/", data),
|
||||
|
||||
changePassword: (currentPassword: string, newPassword: string) =>
|
||||
apiClient.post("/authv/users/change_password/", {
|
||||
current_password: currentPassword,
|
||||
new_password: newPassword,
|
||||
}),
|
||||
};
|
||||
|
||||
// Site Settings
|
||||
export const siteApi = {
|
||||
getParameters: () =>
|
||||
apiClient.get<SiteParameters>("/app/parameters/"),
|
||||
|
||||
getLanguages: () =>
|
||||
apiClient.get<{ code: string; name: string }[]>("/app/languages/"),
|
||||
|
||||
contactUs: (data: { name: string; email: string; subject: string; message: string }) =>
|
||||
apiClient.post("/app/contact_us/", data),
|
||||
};
|
||||
|
||||
export const serverSiteApi = {
|
||||
getParameters: (locale: string) => {
|
||||
const client = getServerApiClient(locale);
|
||||
return client.get<SiteParameters>(
|
||||
"/app/parameters/",
|
||||
undefined,
|
||||
{ revalidate: 3600, tags: ["site-parameters"] }
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Search
|
||||
export const searchApi = {
|
||||
search: (query: string) =>
|
||||
apiClient.post<SearchResult>("/search/", { query }),
|
||||
|
||||
quickSearch: (query: string) =>
|
||||
apiClient.get<SearchResult>("/search/", { q: query }),
|
||||
};
|
||||
3
storefront/src/lib/api/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export * from "./client";
|
||||
export * from "./types";
|
||||
export * from "./endpoints";
|
||||
277
storefront/src/lib/api/types.ts
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
export interface Product {
|
||||
id: string;
|
||||
uuid: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
short_description?: string;
|
||||
price: string;
|
||||
sale_price?: string;
|
||||
sku: string;
|
||||
stock_quantity: number;
|
||||
is_active: boolean;
|
||||
is_featured: boolean;
|
||||
is_new: boolean;
|
||||
is_on_sale: boolean;
|
||||
images: ProductImage[];
|
||||
category: Category | null;
|
||||
brand: Brand | null;
|
||||
tags: ProductTag[];
|
||||
attributes: ProductAttribute[];
|
||||
average_rating: number;
|
||||
reviews_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ProductImage {
|
||||
id: string;
|
||||
image: string;
|
||||
alt_text: string;
|
||||
is_primary: boolean;
|
||||
order: number;
|
||||
}
|
||||
|
||||
export interface ProductAttribute {
|
||||
id: string;
|
||||
name: string;
|
||||
value: string;
|
||||
group?: AttributeGroup;
|
||||
}
|
||||
|
||||
export interface AttributeGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
export interface Category {
|
||||
id: string;
|
||||
uuid: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description?: string;
|
||||
image?: string;
|
||||
parent?: Category | null;
|
||||
children?: Category[];
|
||||
products_count?: number;
|
||||
level: number;
|
||||
}
|
||||
|
||||
export interface Brand {
|
||||
id: string;
|
||||
uuid: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description?: string;
|
||||
logo?: string;
|
||||
website?: string;
|
||||
}
|
||||
|
||||
export interface ProductTag {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
uuid: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone?: string;
|
||||
avatar?: string;
|
||||
is_active: boolean;
|
||||
date_joined: string;
|
||||
}
|
||||
|
||||
export interface Address {
|
||||
id: string;
|
||||
uuid: string;
|
||||
user: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone?: string;
|
||||
address_line_1: string;
|
||||
address_line_2?: string;
|
||||
city: string;
|
||||
state?: string;
|
||||
postal_code: string;
|
||||
country: string;
|
||||
is_default: boolean;
|
||||
}
|
||||
|
||||
export interface Order {
|
||||
id: string;
|
||||
uuid: string;
|
||||
order_number: string;
|
||||
user?: User;
|
||||
status: OrderStatus;
|
||||
items: OrderItem[];
|
||||
shipping_address: Address;
|
||||
billing_address?: Address;
|
||||
subtotal: string;
|
||||
shipping_cost: string;
|
||||
tax: string;
|
||||
discount: string;
|
||||
total: string;
|
||||
promo_code?: string;
|
||||
notes?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export type OrderStatus =
|
||||
| "pending"
|
||||
| "processing"
|
||||
| "shipped"
|
||||
| "delivered"
|
||||
| "cancelled"
|
||||
| "refunded";
|
||||
|
||||
export interface OrderItem {
|
||||
id: string;
|
||||
uuid: string;
|
||||
product: Product;
|
||||
quantity: number;
|
||||
price: string;
|
||||
total: string;
|
||||
}
|
||||
|
||||
export interface CartItem {
|
||||
id: string;
|
||||
product: Product;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export interface Wishlist {
|
||||
id: string;
|
||||
uuid: string;
|
||||
user: string;
|
||||
products: Product[];
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface WishlistItem {
|
||||
id: string;
|
||||
product: Product;
|
||||
added_at: string;
|
||||
}
|
||||
|
||||
export interface Feedback {
|
||||
id: string;
|
||||
uuid: string;
|
||||
user: User;
|
||||
product: string;
|
||||
rating: number;
|
||||
title?: string;
|
||||
comment: string;
|
||||
is_approved: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface PromoCode {
|
||||
id: string;
|
||||
code: string;
|
||||
discount_type: "percentage" | "fixed";
|
||||
discount_value: string;
|
||||
min_order_amount?: string;
|
||||
max_discount?: string;
|
||||
is_active: boolean;
|
||||
valid_from: string;
|
||||
valid_until: string;
|
||||
}
|
||||
|
||||
export interface Promotion {
|
||||
id: string;
|
||||
uuid: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description?: string;
|
||||
banner_image?: string;
|
||||
discount_percentage?: number;
|
||||
is_active: boolean;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
products?: Product[];
|
||||
}
|
||||
|
||||
export interface BlogPost {
|
||||
id: string;
|
||||
uuid: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
excerpt?: string;
|
||||
content: string;
|
||||
featured_image?: string;
|
||||
author: User;
|
||||
tags: BlogTag[];
|
||||
is_published: boolean;
|
||||
published_at?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface BlogTag {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
export interface SiteParameters {
|
||||
site_name: string;
|
||||
site_description?: string;
|
||||
contact_email?: string;
|
||||
contact_phone?: string;
|
||||
address?: string;
|
||||
social_links?: {
|
||||
facebook?: string;
|
||||
instagram?: string;
|
||||
twitter?: string;
|
||||
telegram?: string;
|
||||
youtube?: string;
|
||||
};
|
||||
currency: string;
|
||||
currency_symbol: string;
|
||||
}
|
||||
|
||||
export interface AuthTokens {
|
||||
access: string;
|
||||
refresh: string;
|
||||
}
|
||||
|
||||
export interface LoginCredentials {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterData {
|
||||
email: string;
|
||||
password: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
products: Product[];
|
||||
categories: Category[];
|
||||
brands: Brand[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ProductFilters {
|
||||
category?: string;
|
||||
brand?: string;
|
||||
min_price?: number;
|
||||
max_price?: number;
|
||||
tag?: string;
|
||||
is_on_sale?: boolean;
|
||||
is_new?: boolean;
|
||||
is_featured?: boolean;
|
||||
search?: string;
|
||||
ordering?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
90
storefront/src/lib/utils.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function formatPrice(
|
||||
price: number | string,
|
||||
currency: string = "RUB",
|
||||
locale: string = "ru-RU"
|
||||
): string {
|
||||
const numPrice = typeof price === "string" ? parseFloat(price) : price;
|
||||
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "currency",
|
||||
currency,
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(numPrice);
|
||||
}
|
||||
|
||||
export function formatDate(
|
||||
date: string | Date,
|
||||
locale: string = "ru-RU",
|
||||
options?: Intl.DateTimeFormatOptions
|
||||
): string {
|
||||
const dateObj = typeof date === "string" ? new Date(date) : date;
|
||||
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
...options,
|
||||
}).format(dateObj);
|
||||
}
|
||||
|
||||
export function truncate(str: string, length: number): string {
|
||||
if (str.length <= length) return str;
|
||||
return str.slice(0, length) + "...";
|
||||
}
|
||||
|
||||
export function slugify(str: string): string {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^\w\s-]/g, "")
|
||||
.replace(/[\s_-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
export function getDiscountPercentage(
|
||||
originalPrice: number | string,
|
||||
salePrice: number | string
|
||||
): number {
|
||||
const original =
|
||||
typeof originalPrice === "string"
|
||||
? parseFloat(originalPrice)
|
||||
: originalPrice;
|
||||
const sale =
|
||||
typeof salePrice === "string" ? parseFloat(salePrice) : salePrice;
|
||||
|
||||
if (original <= 0) return 0;
|
||||
return Math.round(((original - sale) / original) * 100);
|
||||
}
|
||||
|
||||
export function getImageUrl(path: string | undefined | null): string {
|
||||
if (!path) return "/placeholder.svg";
|
||||
if (path.startsWith("http")) return path;
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "https://api.itoption.ru";
|
||||
return `${apiUrl}${path}`;
|
||||
}
|
||||
|
||||
export function debounce<T extends (...args: Parameters<T>) => void>(
|
||||
func: T,
|
||||
wait: number
|
||||
): (...args: Parameters<T>) => void {
|
||||
let timeout: NodeJS.Timeout | null = null;
|
||||
|
||||
return (...args: Parameters<T>) => {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
timeout = setTimeout(() => func(...args), wait);
|
||||
};
|
||||
}
|
||||
|
||||
export function generateOrderNumber(): string {
|
||||
const timestamp = Date.now().toString(36);
|
||||
const randomPart = Math.random().toString(36).substring(2, 7);
|
||||
return `ORD-${timestamp}-${randomPart}`.toUpperCase();
|
||||
}
|
||||
12
storefront/src/middleware.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import createMiddleware from "next-intl/middleware";
|
||||
import { routing } from "./i18n/routing";
|
||||
|
||||
export default createMiddleware(routing);
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
"/",
|
||||
"/(ru|en)/:path*",
|
||||
"/((?!api|_next|_vercel|.*\\..*).*)",
|
||||
],
|
||||
};
|
||||
167
storefront/src/stores/auth-store.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import { create } from "zustand";
|
||||
import { persist, createJSONStorage } from "zustand/middleware";
|
||||
import type { User, AuthTokens, LoginCredentials, RegisterData } from "@/lib/api/types";
|
||||
import { authApi } from "@/lib/api/endpoints";
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
accessToken: string | null;
|
||||
refreshToken: string | null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
|
||||
// Actions
|
||||
login: (credentials: LoginCredentials) => Promise<boolean>;
|
||||
register: (data: RegisterData) => Promise<boolean>;
|
||||
logout: () => void;
|
||||
refreshAccessToken: () => Promise<boolean>;
|
||||
fetchProfile: () => Promise<void>;
|
||||
updateProfile: (data: Partial<User>) => Promise<boolean>;
|
||||
setTokens: (tokens: AuthTokens) => void;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
user: null,
|
||||
accessToken: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
|
||||
login: async (credentials) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const tokens = await authApi.login(credentials);
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("access_token", tokens.access);
|
||||
localStorage.setItem("refresh_token", tokens.refresh);
|
||||
}
|
||||
|
||||
set({
|
||||
accessToken: tokens.access,
|
||||
refreshToken: tokens.refresh,
|
||||
isAuthenticated: true,
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
// Fetch user profile after login
|
||||
await get().fetchProfile();
|
||||
return true;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Login failed";
|
||||
set({ error: message, isLoading: false });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
register: async (data) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
await authApi.register(data);
|
||||
// Auto-login after registration
|
||||
return await get().login({ email: data.email, password: data.password });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Registration failed";
|
||||
set({ error: message, isLoading: false });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
}
|
||||
|
||||
set({
|
||||
user: null,
|
||||
accessToken: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
error: null,
|
||||
});
|
||||
},
|
||||
|
||||
refreshAccessToken: async () => {
|
||||
const { refreshToken } = get();
|
||||
if (!refreshToken) return false;
|
||||
|
||||
try {
|
||||
const response = await authApi.refresh(refreshToken);
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("access_token", response.access);
|
||||
}
|
||||
|
||||
set({ accessToken: response.access });
|
||||
return true;
|
||||
} catch {
|
||||
get().logout();
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
fetchProfile: async () => {
|
||||
try {
|
||||
const user = await authApi.getProfile();
|
||||
set({ user });
|
||||
} catch {
|
||||
// Token might be invalid, try refreshing
|
||||
const refreshed = await get().refreshAccessToken();
|
||||
if (refreshed) {
|
||||
try {
|
||||
const user = await authApi.getProfile();
|
||||
set({ user });
|
||||
} catch {
|
||||
get().logout();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
updateProfile: async (data) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const user = await authApi.updateProfile(data);
|
||||
set({ user, isLoading: false });
|
||||
return true;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Update failed";
|
||||
set({ error: message, isLoading: false });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
setTokens: (tokens) => {
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("access_token", tokens.access);
|
||||
localStorage.setItem("refresh_token", tokens.refresh);
|
||||
}
|
||||
|
||||
set({
|
||||
accessToken: tokens.access,
|
||||
refreshToken: tokens.refresh,
|
||||
isAuthenticated: true,
|
||||
});
|
||||
},
|
||||
|
||||
clearError: () => {
|
||||
set({ error: null });
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "auth-storage",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({
|
||||
accessToken: state.accessToken,
|
||||
refreshToken: state.refreshToken,
|
||||
isAuthenticated: state.isAuthenticated,
|
||||
}),
|
||||
}
|
||||
)
|
||||
);
|
||||
115
storefront/src/stores/cart-store.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import { create } from "zustand";
|
||||
import { persist, createJSONStorage } from "zustand/middleware";
|
||||
import type { Product } from "@/lib/api/types";
|
||||
|
||||
export interface CartItem {
|
||||
product: Product;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface CartState {
|
||||
items: CartItem[];
|
||||
isOpen: boolean;
|
||||
|
||||
// Actions
|
||||
addItem: (product: Product, quantity?: number) => void;
|
||||
removeItem: (productId: string) => void;
|
||||
updateQuantity: (productId: string, quantity: number) => void;
|
||||
clearCart: () => void;
|
||||
toggleCart: () => void;
|
||||
openCart: () => void;
|
||||
closeCart: () => void;
|
||||
|
||||
// Computed
|
||||
getItemCount: () => number;
|
||||
getSubtotal: () => number;
|
||||
getItem: (productId: string) => CartItem | undefined;
|
||||
}
|
||||
|
||||
export const useCartStore = create<CartState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
items: [],
|
||||
isOpen: false,
|
||||
|
||||
addItem: (product, quantity = 1) => {
|
||||
set((state) => {
|
||||
const existingItem = state.items.find(
|
||||
(item) => item.product.id === product.id
|
||||
);
|
||||
|
||||
if (existingItem) {
|
||||
return {
|
||||
items: state.items.map((item) =>
|
||||
item.product.id === product.id
|
||||
? { ...item, quantity: item.quantity + quantity }
|
||||
: item
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
items: [...state.items, { product, quantity }],
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
removeItem: (productId) => {
|
||||
set((state) => ({
|
||||
items: state.items.filter((item) => item.product.id !== productId),
|
||||
}));
|
||||
},
|
||||
|
||||
updateQuantity: (productId, quantity) => {
|
||||
if (quantity <= 0) {
|
||||
get().removeItem(productId);
|
||||
return;
|
||||
}
|
||||
|
||||
set((state) => ({
|
||||
items: state.items.map((item) =>
|
||||
item.product.id === productId ? { ...item, quantity } : item
|
||||
),
|
||||
}));
|
||||
},
|
||||
|
||||
clearCart: () => {
|
||||
set({ items: [] });
|
||||
},
|
||||
|
||||
toggleCart: () => {
|
||||
set((state) => ({ isOpen: !state.isOpen }));
|
||||
},
|
||||
|
||||
openCart: () => {
|
||||
set({ isOpen: true });
|
||||
},
|
||||
|
||||
closeCart: () => {
|
||||
set({ isOpen: false });
|
||||
},
|
||||
|
||||
getItemCount: () => {
|
||||
return get().items.reduce((total, item) => total + item.quantity, 0);
|
||||
},
|
||||
|
||||
getSubtotal: () => {
|
||||
return get().items.reduce((total, item) => {
|
||||
const price = item.product.sale_price
|
||||
? parseFloat(item.product.sale_price)
|
||||
: parseFloat(item.product.price);
|
||||
return total + price * item.quantity;
|
||||
}, 0);
|
||||
},
|
||||
|
||||
getItem: (productId) => {
|
||||
return get().items.find((item) => item.product.id === productId);
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "cart-storage",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({ items: state.items }),
|
||||
}
|
||||
)
|
||||
);
|
||||
6
storefront/src/stores/index.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export { useCartStore } from "./cart-store";
|
||||
export type { CartItem } from "./cart-store";
|
||||
|
||||
export { useAuthStore } from "./auth-store";
|
||||
|
||||
export { useWishlistStore } from "./wishlist-store";
|
||||
82
storefront/src/stores/wishlist-store.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { create } from "zustand";
|
||||
import { persist, createJSONStorage } from "zustand/middleware";
|
||||
import type { Product } from "@/lib/api/types";
|
||||
|
||||
interface WishlistState {
|
||||
items: Product[];
|
||||
isOpen: boolean;
|
||||
|
||||
// Actions
|
||||
addItem: (product: Product) => void;
|
||||
removeItem: (productId: string) => void;
|
||||
toggleItem: (product: Product) => void;
|
||||
clearWishlist: () => void;
|
||||
toggleWishlist: () => void;
|
||||
openWishlist: () => void;
|
||||
closeWishlist: () => void;
|
||||
|
||||
// Computed
|
||||
isInWishlist: (productId: string) => boolean;
|
||||
getItemCount: () => number;
|
||||
}
|
||||
|
||||
export const useWishlistStore = create<WishlistState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
items: [],
|
||||
isOpen: false,
|
||||
|
||||
addItem: (product) => {
|
||||
set((state) => {
|
||||
const exists = state.items.some((item) => item.id === product.id);
|
||||
if (exists) return state;
|
||||
return { items: [...state.items, product] };
|
||||
});
|
||||
},
|
||||
|
||||
removeItem: (productId) => {
|
||||
set((state) => ({
|
||||
items: state.items.filter((item) => item.id !== productId),
|
||||
}));
|
||||
},
|
||||
|
||||
toggleItem: (product) => {
|
||||
const { isInWishlist, addItem, removeItem } = get();
|
||||
if (isInWishlist(product.id)) {
|
||||
removeItem(product.id);
|
||||
} else {
|
||||
addItem(product);
|
||||
}
|
||||
},
|
||||
|
||||
clearWishlist: () => {
|
||||
set({ items: [] });
|
||||
},
|
||||
|
||||
toggleWishlist: () => {
|
||||
set((state) => ({ isOpen: !state.isOpen }));
|
||||
},
|
||||
|
||||
openWishlist: () => {
|
||||
set({ isOpen: true });
|
||||
},
|
||||
|
||||
closeWishlist: () => {
|
||||
set({ isOpen: false });
|
||||
},
|
||||
|
||||
isInWishlist: (productId) => {
|
||||
return get().items.some((item) => item.id === productId);
|
||||
},
|
||||
|
||||
getItemCount: () => {
|
||||
return get().items.length;
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "wishlist-storage",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({ items: state.items }),
|
||||
}
|
||||
)
|
||||
);
|
||||
34
storefront/tsconfig.json
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||