Merge pull request #4 from kodamera/chore/restructure-storefront

Chore/restructure storefront
This commit is contained in:
Henrik Larsson 2023-08-08 17:10:27 +02:00 committed by GitHub
commit 4b1a5bed29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 2107 additions and 1492 deletions

View File

@ -41,7 +41,7 @@ export default async function Page({ params }: { params: { slug: string[]; local
return (
<div className="flex flex-col">
<Header localeData={localeData} />
<Header />
<main className="flex-1">
<article>
{isEnabled ? (
@ -65,7 +65,7 @@ export default async function Page({ params }: { params: { slug: string[]; local
)}
</article>
</main>
<Footer />
<Footer localeData={localeData} />
</div>
);
}

View File

@ -0,0 +1,19 @@
import ProductView from 'components/product/product-view';
import { notFound } from 'next/navigation';
interface ProductPageProps {
data: object | any;
}
// This is a Client Component. It receives data as props and
// has access to state and effects just like Page components
// in the `pages` directory.
export default function ProductPage({ data }: ProductPageProps) {
if (!data) {
return notFound();
}
const { product } = data;
return <ProductView product={product} relatedProducts={[]} />;
}

View File

@ -16,8 +16,19 @@ VERCEL_GIT_COMMIT_AUTHOR_LOGIN=""
VERCEL_GIT_COMMIT_AUTHOR_NAME=""
VERCEL_GIT_PULL_REQUEST_ID=""
# Sanity
NEXT_PUBLIC_SANITY_PROJECT_ID=""
NEXT_PUBLIC_SANITY_DATASET=""
NEXT_PUBLIC_SANITY_API_VERSION=""
# Preview
SANITY_API_READ_TOKEN=""
SANITY_WEBHOOK_SECRET=""
# Site
TWITTER_CREATOR="@kodamera"
TWITTER_SITE="https://kodamera.se"
SITE_NAME="KM Storefront"
SITE_DESCRIPTION="High-performance ecommerce store built with Next.js, Vercel, Sanity and Storm."
SHOPIFY_STOREFRONT_ACCESS_TOKEN=
SHOPIFY_STORE_DOMAIN=

View File

@ -0,0 +1,77 @@
import DynamicContentManager from 'components/layout/dynamic-content-manager';
import { pageQuery } from 'lib/sanity/queries';
import { clientFetch } from 'lib/sanity/sanity.client';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
export const runtime = 'edge';
export const revalidate = 43200; // 12 hours in seconds
export async function generateMetadata({
params
}: {
params: { locale: string; slug: string[] };
}): Promise<Metadata> {
let queryParams = {
locale: params.locale,
slug: ''
};
if (params.slug.length > 1) {
queryParams = {
locale: params.locale,
slug: `${params.slug.join('/')}`
};
} else {
queryParams = {
locale: params.locale,
slug: `${params.slug}`
};
}
const page = await clientFetch(pageQuery, queryParams);
if (!page) return notFound();
return {
title: page.seo?.title || page.title,
description: page.seo?.description || page.bodySummary,
openGraph: {
publishedTime: page.createdAt,
modifiedTime: page.updatedAt,
type: 'article'
}
};
}
interface PageParams {
params: {
locale: string;
slug: string[];
};
}
export default async function Page({ params }: PageParams) {
let queryParams = {
locale: params.locale,
slug: ''
};
if (params.slug.length > 1) {
queryParams = {
locale: params.locale,
slug: `${params.slug.join('/')}`
};
} else {
queryParams = {
locale: params.locale,
slug: `${params.slug}`
};
}
const page = await clientFetch(pageQuery, queryParams);
if (!page) return notFound();
return <DynamicContentManager content={page?.content} />;
}

View File

@ -1,21 +0,0 @@
import ProductView from "components/product/product-view";
import { notFound } from "next/navigation";
interface ProductPageProps {
data: object | any
}
// This is a Client Component. It receives data as props and
// has access to state and effects just like Page components
// in the `pages` directory.
export default function ProductPage({data }: ProductPageProps) {
if (!data) {
return notFound();
}
const { product } = data;
return (
<ProductView product={product} relatedProducts={[]} />
)
}

View File

@ -0,0 +1,41 @@
import Text from 'components/ui/text/text';
import { categoryQuery } from 'lib/sanity/queries';
import { clientFetch } from 'lib/sanity/sanity.client';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
export async function generateMetadata({
params
}: {
params: { slug: string; locale: string };
}): Promise<Metadata> {
const category = await clientFetch(categoryQuery, params);
if (!category) return notFound();
return {
title: category.seo.title || category.title,
description: category.seo.description || category.description
};
}
interface CategoryPageParams {
params: {
locale: string;
slug: string;
};
}
export default async function ProductPage({ params }: CategoryPageParams) {
const category = await clientFetch(categoryQuery, params);
if (!category) return notFound();
const { title } = category;
return (
<div className="mb-8 flex w-full flex-col px-4 lg:my-16 lg:px-8 2xl:px-16">
<Text variant={'pageHeading'}>{title}</Text>
</div>
);
}

View File

@ -2,9 +2,76 @@
@tailwind components;
@tailwind utilities;
@supports (font: -apple-system-body) and (-webkit-appearance: none) {
img[loading='lazy'] {
clip-path: inset(0.6px);
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--radius: 0.5rem;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
@ -28,7 +95,7 @@
html,
body {
@apply font-sans h-full bg-white text-high-contrast;
@apply h-full bg-white font-sans text-high-contrast;
box-sizing: border-box;
touch-action: manipulation;
@ -74,11 +141,11 @@ body {
}
.glider-dots {
@apply flex !space-x-[2px] !mt-8;
@apply !mt-8 flex !space-x-[2px];
}
.glider-dot {
@apply !m-0 !rounded-none !w-12 !h-4 !bg-transparent after:content-[''] after:block after:w-12 after:h-[3px] after:bg-ui-border 2xl:!w-16 2xl:after:w-16;
@apply !m-0 !h-4 !w-12 !rounded-none !bg-transparent after:block after:h-[3px] after:w-12 after:bg-ui-border after:content-[''] 2xl:!w-16 2xl:after:w-16;
}
.glider-dot.active {
@ -86,17 +153,17 @@ body {
}
.glider-prev {
@apply text-high-contrast !right-12 !-top-10 !left-auto lg:!right-16 lg:!-top-12 2xl:!-top-16 2xl:!right-[100px] !transition-transform !duration-100 hover:!text-high-contrast hover:scale-110;
@apply !-top-10 !left-auto !right-12 text-high-contrast !transition-transform !duration-100 hover:scale-110 hover:!text-high-contrast lg:!-top-10 lg:!right-16 2xl:!-top-12 2xl:!right-[100px];
}
.glider-next {
@apply text-high-contrast !right-4 !-top-10 lg:!right-8 lg:!-top-12 2xl:!-top-16 2xl:!right-16 !transition-transform !duration-100 hover:!text-high-contrast hover:scale-110;
@apply !-top-10 !right-4 text-high-contrast !transition-transform !duration-100 hover:scale-110 hover:!text-high-contrast lg:!-top-10 lg:!right-8 2xl:!-top-12 2xl:!right-16;
}
.pdp .glider-prev {
@apply text-high-contrast absolute !left-4 !top-1/2 !transition-transform !duration-100 hover:!text-high-contrast hover:scale-100 lg:hidden;
@apply absolute !left-4 !top-1/2 text-high-contrast !transition-transform !duration-100 hover:scale-100 hover:!text-high-contrast lg:hidden;
}
.pdp .glider-next {
@apply text-high-contrast absolute !right-4 !top-1/2 !transition-transform !duration-100 hover:!text-high-contrast hover:scale-100 lg:hidden;
}
@apply absolute !right-4 !top-1/2 text-high-contrast !transition-transform !duration-100 hover:scale-100 hover:!text-high-contrast lg:hidden;
}

View File

@ -1,30 +1,28 @@
import Footer from 'components/layout/footer/footer';
import Header from 'components/layout/header/header';
import { NextIntlClientProvider } from 'next-intl';
import { Inter } from 'next/font/google';
import { notFound } from 'next/navigation';
import { ReactNode } from 'react';
import { supportedLanguages } from '../../i18n-config';
import './globals.css';
const SITE_NAME = 'KM Storefront';
const SITE_DESCRIPTION = 'Webb och digitalbyrå från Göteborg';
const TWITTER_CREATOR = '@kodamera.se';
const TWITTER_SITE = 'https://kodamera.se';
export const metadata = {
title: {
default: SITE_NAME,
template: `%s | ${SITE_NAME}`
default: process.env.SITE_NAME,
template: `%s | ${process.env.SITE_NAME}`
},
description: SITE_DESCRIPTION,
description: process.env.SITE_DESCRIPTION,
robots: {
follow: true,
index: true
},
...(TWITTER_CREATOR &&
TWITTER_SITE && {
...(process.env.TWITTER_CREATOR &&
process.env.TWITTER_SITE && {
twitter: {
card: 'summary_large_image',
creator: TWITTER_CREATOR,
site: TWITTER_SITE
creator: process.env.TWITTER_CREATOR,
site: process.env.TWITTER_SITE
}
})
};
@ -36,7 +34,7 @@ const inter = Inter({
});
export function generateStaticParams() {
return [{ locale: 'sv' }, { locale: 'en' }];
return supportedLanguages.locales.map((locale) => ({ locale: locale.id }));
}
interface LocaleLayoutProps {
@ -59,7 +57,10 @@ export default async function LocaleLayout({ children, params: { locale } }: Loc
<html lang={locale} className={inter.variable}>
<body className="flex min-h-screen flex-col">
<NextIntlClientProvider locale={locale} messages={messages}>
{children}
<Header locale={locale} />
<main className="flex-1">{children}</main>
{/* @ts-expect-error Server Component (https://github.com/vercel/next.js/issues/42292) */}
<Footer locale={locale} />
</NextIntlClientProvider>
</body>
</html>

27
app/[locale]/page.tsx Normal file
View File

@ -0,0 +1,27 @@
import DynamicContentManager from 'components/layout/dynamic-content-manager/dynamic-content-manager';
import { homePageQuery } from 'lib/sanity/queries';
import { clientFetch } from 'lib/sanity/sanity.client';
export const runtime = 'edge';
export const metadata = {
description: 'High-performance ecommerce store built with Next.js, Vercel, Sanity and Storm.',
openGraph: {
type: 'website'
}
};
interface HomePageParams {
params: {
locale: string;
};
}
export default async function HomePage({ params }: HomePageParams) {
const data = await clientFetch(homePageQuery, params);
return (
<>
<DynamicContentManager content={data?.content} />
</>
);
}

View File

@ -0,0 +1,89 @@
import ProductView from 'components/product/product-view';
import { productQuery } from 'lib/sanity/queries';
import { clientFetch } from 'lib/sanity/sanity.client';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
interface ProductPageParams {
params: {
locale: string;
slug: string;
};
}
export async function generateMetadata({
params
}: {
params: { slug: string; locale: string };
}): Promise<Metadata> {
const product = await clientFetch(productQuery, params);
if (!product) return notFound();
const { alt } = product.images[0] || '';
const { url } = product.images[0].asset || {};
const { width, height } = product.images[0].asset.metadata.dimensions;
// const indexable = !product.tags.includes(HIDDEN_PRODUCT_TAG);
return {
title: product.seo.title || product.title,
description: product.seo.description || product.description,
// @TODO ROBOTS SETTINGS???
// robots: {
// index: indexable,
// follow: indexable,
// googleBot: {
// index: indexable,
// follow: indexable
// }
// },
openGraph: url
? {
images: [
{
url,
width,
height,
alt
}
]
}
: null
};
}
export default async function ProductPage({ params }: ProductPageParams) {
const product = await clientFetch(productQuery, params);
if (!product) return notFound();
const productJsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
description: product.description,
// @TODO UPDATE TO STORM URL???
image: product.images[0].asset.url
// offers: {
// '@type': 'AggregateOffer',
// availability: product.availableForSale
// ? 'https://schema.org/InStock'
// : 'https://schema.org/OutOfStock',
// priceCurrency: product.priceRange.minVariantPrice.currencyCode,
// highPrice: product.priceRange.maxVariantPrice.amount,
// lowPrice: product.priceRange.minVariantPrice.amount
// }
};
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(productJsonLd)
}}
/>
<ProductView product={product} relatedProducts={[]} />;
</>
);
}

View File

@ -83,7 +83,7 @@ draftMode().enable();
return new Response(null, {
status: 307,
headers: {
Location: `/${product.locale}/${product.slug}`,
Location: `/${product.locale}/product/${product.slug}`,
},
})
}
@ -92,7 +92,7 @@ draftMode().enable();
return new Response(null, {
status: 307,
headers: {
Location: `/${category.locale}/${category.slug}`,
Location: `/${category.locale}/category/${category.slug}`,
},
})
}

16
components.json Normal file
View File

@ -0,0 +1,16 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
}
}

View File

@ -0,0 +1,69 @@
'use server';
import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify';
import { cookies } from 'next/headers';
export const addItem = async (variantId: string | undefined): Promise<String | undefined> => {
let cartId = cookies().get('cartId')?.value;
let cart;
if (cartId) {
cart = await getCart(cartId);
}
if (!cartId || !cart) {
cart = await createCart();
cartId = cart.id;
cookies().set('cartId', cartId);
}
if (!variantId) {
return 'Missing product variant ID';
}
try {
await addToCart(cartId, [{ merchandiseId: variantId, quantity: 1 }]);
} catch (e) {
return 'Error adding item to cart';
}
};
export const removeItem = async (lineId: string): Promise<String | undefined> => {
const cartId = cookies().get('cartId')?.value;
if (!cartId) {
return 'Missing cart ID';
}
try {
await removeFromCart(cartId, [lineId]);
} catch (e) {
return 'Error removing item from cart';
}
};
export const updateItemQuantity = async ({
lineId,
variantId,
quantity
}: {
lineId: string;
variantId: string;
quantity: number;
}): Promise<String | undefined> => {
const cartId = cookies().get('cartId')?.value;
if (!cartId) {
return 'Missing cart ID';
}
try {
await updateCart(cartId, [
{
id: lineId,
merchandiseId: variantId,
quantity
}
]);
} catch (e) {
return 'Error updating item quantity';
}
};

View File

@ -0,0 +1,68 @@
'use client';
import { PlusIcon } from '@radix-ui/react-icons';
import clsx from 'clsx';
import { addItem } from 'components/cart/actions';
import LoadingDots from 'components/loading-dots';
import { ProductVariant } from 'lib/shopify/types';
import { useRouter, useSearchParams } from 'next/navigation';
import { useTransition } from 'react';
export function AddToCart({
variants,
availableForSale
}: {
variants: ProductVariant[];
availableForSale: boolean;
}) {
const router = useRouter();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const defaultVariantId = variants.length === 1 ? variants[0]?.id : undefined;
const variant = variants.find((variant: ProductVariant) =>
variant.selectedOptions.every(
(option) => option.value === searchParams.get(option.name.toLowerCase())
)
);
const selectedVariantId = variant?.id || defaultVariantId;
const title = !availableForSale
? 'Out of stock'
: !selectedVariantId
? 'Please select options'
: undefined;
return (
<button
aria-label="Add item to cart"
disabled={isPending || !availableForSale || !selectedVariantId}
title={title}
onClick={() => {
// Safeguard in case someone messes with `disabled` in devtools.
if (!availableForSale || !selectedVariantId) return;
// @ts-ignore
startTransition(async () => {
const error = await addItem(selectedVariantId);
if (error) {
// Trigger the error boundary in the root error.js
throw new Error(error.toString());
}
router.refresh();
});
}}
className={clsx(
'bg-blue-600 relative flex w-full items-center justify-center rounded-full p-4 tracking-wide text-white hover:opacity-90',
{
'cursor-not-allowed opacity-60 hover:opacity-60': !availableForSale || !selectedVariantId,
'cursor-not-allowed': isPending
}
)}
>
<div className="absolute left-0 ml-4">
{!isPending ? <PlusIcon className="h-5" /> : <LoadingDots className="mb-3 bg-white" />}
</div>
<span>{availableForSale ? 'Add To Cart' : 'Out Of Stock'}</span>
</button>
);
}

View File

@ -1,64 +0,0 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useCookies } from 'react-cookie';
import CartIcon from 'components/icons/cart';
import CartModal from './modal';
import type { Cart } from 'lib/shopify/types';
export default function CartButton({
cart,
cartIdUpdated
}: {
cart: Cart;
cartIdUpdated: boolean;
}) {
const [, setCookie] = useCookies(['cartId']);
const [cartIsOpen, setCartIsOpen] = useState(false);
const quantityRef = useRef(cart.totalQuantity);
// Temporary hack to update the `cartId` cookie when it changes since we cannot update it
// on the server-side (yet).
useEffect(() => {
if (cartIdUpdated) {
setCookie('cartId', cart.id, {
path: '/',
sameSite: 'strict',
secure: process.env.NODE_ENV === 'production'
});
}
return;
}, [setCookie, cartIdUpdated, cart.id]);
useEffect(() => {
// Open cart modal when when quantity changes.
if (cart.totalQuantity !== quantityRef.current) {
// But only if it's not already open (quantity also changes when editing items in cart).
if (!cartIsOpen) {
setCartIsOpen(true);
}
// Always update the quantity reference
quantityRef.current = cart.totalQuantity;
}
}, [cartIsOpen, cart.totalQuantity, quantityRef]);
return (
<>
<CartModal isOpen={cartIsOpen} onClose={() => setCartIsOpen(false)} cart={cart} />
<button
aria-label="Open cart"
onClick={() => {
setCartIsOpen(true);
}}
className="relative right-0 top-0"
data-testid="open-cart"
>
<CartIcon quantity={cart.totalQuantity} />
</button>
</>
);
}

View File

@ -0,0 +1,10 @@
import clsx from 'clsx';
import CloseIcon from 'components/icons/close';
export default function CloseCart({ className }: { className?: string }) {
return (
<div className="relative flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors dark:border-neutral-700 dark:text-white">
<CloseIcon className={clsx('h-6 transition-all ease-in-out hover:scale-110 ', className)} />
</div>
);
}

View File

@ -1,53 +1,44 @@
import CloseIcon from 'components/icons/close';
import LoadingDots from 'components/ui/loading-dots';
import LoadingDots from 'components/loading-dots';
import { useRouter } from 'next/navigation';
import { startTransition, useState } from 'react';
import clsx from 'clsx';
import { removeItem } from 'components/cart/actions';
import type { CartItem } from 'lib/shopify/types';
import { useTransition } from 'react';
export default function DeleteItemButton({ item }: { item: CartItem }) {
const router = useRouter();
const [removing, setRemoving] = useState(false);
const [isPending, startTransition] = useTransition();
async function handleRemove() {
setRemoving(true);
const response = await fetch(`/api/cart`, {
method: 'DELETE',
body: JSON.stringify({
lineId: item.id
})
});
const data = await response.json();
if (data.error) {
alert(data.error);
return;
}
setRemoving(false);
startTransition(() => {
router.refresh();
});
}
return (
<button
aria-label="Remove cart item"
onClick={handleRemove}
disabled={removing}
onClick={() => {
// @ts-ignore
startTransition(async () => {
const error = await removeItem(item.id);
if (error) {
// Trigger the error boundary in the root error.js
throw new Error(error.toString());
}
router.refresh();
});
}}
disabled={isPending}
className={clsx(
'ease flex min-w-[36px] max-w-[36px] items-center justify-center border px-2 transition-all duration-200 hover:border-gray-800 hover:bg-gray-100 dark:border-gray-700 dark:hover:border-gray-600 dark:hover:bg-gray-900',
'ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200',
{
'cursor-not-allowed px-0': removing
'cursor-not-allowed px-0': isPending
}
)}
>
{removing ? (
<LoadingDots className="bg-black dark:bg-white" />
{isPending ? (
<LoadingDots className="bg-white" />
) : (
<CloseIcon className="hover:text-accent-3 mx-[1px] h-4 w-4" />
<CloseIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white " />
)}
</button>
);

View File

@ -1,10 +1,11 @@
import { useRouter } from 'next/navigation';
import { startTransition, useState } from 'react';
import { useTransition } from 'react';
import clsx from 'clsx';
import { removeItem, updateItemQuantity } from 'components/cart/actions';
import MinusIcon from 'components/icons/minus';
import PlusIcon from 'components/icons/plus';
import LoadingDots from 'components/ui/loading-dots';
import LoadingDots from 'components/loading-dots';
import type { CartItem } from 'lib/shopify/types';
export default function EditItemQuantityButton({
@ -15,52 +16,46 @@ export default function EditItemQuantityButton({
type: 'plus' | 'minus';
}) {
const router = useRouter();
const [editing, setEditing] = useState(false);
const [isPending, startTransition] = useTransition();
async function handleEdit() {
setEditing(true);
const response = await fetch(`/api/cart`, {
method: type === 'minus' && item.quantity - 1 === 0 ? 'DELETE' : 'PUT',
body: JSON.stringify({
lineId: item.id,
variantId: item.merchandise.id,
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
})
});
const data = await response.json();
if (data.error) {
alert(data.error);
return;
}
setEditing(false);
startTransition(() => {
router.refresh();
});
}
return (
<button
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
onClick={handleEdit}
disabled={editing}
onClick={() => {
// @ts-ignore
startTransition(async () => {
const error =
type === 'minus' && item.quantity - 1 === 0
? await removeItem(item.id)
: await updateItemQuantity({
lineId: item.id,
variantId: item.merchandise.id,
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
});
if (error) {
// Trigger the error boundary in the root error.js
throw new Error(error.toString());
}
router.refresh();
});
}}
disabled={isPending}
className={clsx(
'ease flex min-w-[36px] max-w-[36px] items-center justify-center border px-2 transition-all duration-200 hover:border-gray-800 hover:bg-gray-100 dark:border-gray-700 dark:hover:border-gray-600 dark:hover:bg-gray-900',
'ease flex h-full min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full px-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80',
{
'cursor-not-allowed': editing,
'cursor-not-allowed': isPending,
'ml-auto': type === 'minus'
}
)}
>
{editing ? (
{isPending ? (
<LoadingDots className="bg-black dark:bg-white" />
) : type === 'plus' ? (
<PlusIcon className="h-4 w-4" />
<PlusIcon className="h-4 w-4 dark:text-neutral-500" />
) : (
<MinusIcon className="h-4 w-4" />
<MinusIcon className="h-4 w-4 dark:text-neutral-500" />
)}
</button>
);

View File

@ -1,23 +1,14 @@
import { createCart, getCart } from 'lib/shopify';
import { getCart } from 'lib/shopify';
import { cookies } from 'next/headers';
import CartButton from './button';
import CartModal from './modal';
export default async function Cart() {
const cartId = cookies().get('cartId')?.value;
let cartIdUpdated = false;
let cart;
if (cartId) {
cart = await getCart(cartId);
}
// If the `cartId` from the cookie is not set or the cart is empty
// (old carts becomes `null` when you checkout), then get a new `cartId`
// and re-fetch the cart.
if (!cartId || !cart) {
cart = await createCart();
cartIdUpdated = true;
}
return <CartButton cart={cart} cartIdUpdated={cartIdUpdated} />;
return <CartModal cart={cart} />;
}

View File

@ -1,187 +1,160 @@
import { Dialog } from '@headlessui/react';
import { AnimatePresence, motion } from 'framer-motion';
import Image from 'next/image';
import Link from 'next/link';
'use client';
import CloseIcon from 'components/icons/close';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import ShoppingBagIcon from 'components/icons/shopping-bag';
import Price from 'components/product/price';
import Price from 'components/price';
import { DEFAULT_OPTION } from 'lib/constants';
import type { Cart } from 'lib/shopify/types';
import { createUrl } from 'lib/utils';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import DeleteItemButton from './delete-item-button';
import EditItemQuantityButton from './edit-item-quantity-button';
import OpenCart from './open-cart';
type MerchandiseSearchParams = {
[key: string]: string;
};
export default function CartModal({
isOpen,
onClose,
cart
}: {
isOpen: boolean;
onClose: () => void;
cart: Cart;
}) {
export default function CartModal({ cart }: { cart: Cart | undefined }) {
const [isOpen, setIsOpen] = useState(false);
const quantityRef = useRef(cart?.totalQuantity);
const t = useTranslations('cart');
useEffect(() => {
// Open cart modal when quantity changes.
if (cart?.totalQuantity !== quantityRef.current) {
// But only if it's not already open (quantity also changes when editing items in cart).
if (!isOpen) {
setIsOpen(true);
}
// Always update the quantity reference
quantityRef.current = cart?.totalQuantity;
}
}, [isOpen, cart?.totalQuantity, quantityRef]);
return (
<AnimatePresence initial={false}>
{isOpen && (
<Dialog
as={motion.div}
initial="closed"
animate="open"
exit="closed"
key="dialog"
static
open={isOpen}
onClose={onClose}
className="relative z-50"
>
<motion.div
variants={{
open: { opacity: 1, backdropFilter: 'blur(0.5px)' },
closed: { opacity: 0, backdropFilter: 'blur(0px)' }
}}
className="fixed inset-0 bg-black/30"
aria-hidden="true"
/>
<>
<Sheet open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>
<SheetTrigger aria-label={t('openCart')}>
<OpenCart quantity={cart?.totalQuantity} />
</SheetTrigger>
<SheetContent className="bg-app">
<SheetHeader>
<SheetTitle className="text-lg font-semibold">{t('myCartTitle')}</SheetTitle>
</SheetHeader>
{!cart || cart.lines.length === 0 ? (
<div className="mt-20 flex w-full flex-col items-center justify-center overflow-hidden">
<ShoppingBagIcon className="h-12" />
<p className="mt-6 text-center text-2xl font-bold">{t('empty.title')}</p>
</div>
) : (
<div className="flex h-full flex-col justify-between overflow-hidden p-1">
<ul className="flex-grow overflow-auto py-4">
{cart.lines.map((item, i) => {
const merchandiseSearchParams = {} as MerchandiseSearchParams;
<div className="fixed inset-0 flex justify-end" data-testid="cart">
<Dialog.Panel
as={motion.div}
variants={{
open: { translateX: 0 },
closed: { translateX: '100%' }
}}
transition={{ type: 'spring', bounce: 0, duration: 0.3 }}
className="flex w-full flex-col bg-white p-8 text-black dark:bg-black dark:text-white md:w-3/5 lg:w-2/5"
>
<div className="flex items-center justify-between">
<p className="text-lg font-bold">My Cart</p>
<button
aria-label="Close cart"
onClick={onClose}
className="text-black transition-colors hover:text-gray-500 dark:text-gray-100"
data-testid="close-cart"
>
<CloseIcon className="h-7" />
</button>
</div>
item.merchandise.selectedOptions.forEach(({ name, value }) => {
if (value !== DEFAULT_OPTION) {
merchandiseSearchParams[name.toLowerCase()] = value;
}
});
{cart.lines.length === 0 ? (
<div className="mt-20 flex w-full flex-col items-center justify-center overflow-hidden">
<ShoppingBagIcon className="h-16" />
<p className="mt-6 text-center text-2xl font-bold">Your cart is empty.</p>
</div>
) : null}
{cart.lines.length !== 0 ? (
<div className="flex h-full flex-col justify-between overflow-hidden">
<ul className="flex-grow overflow-auto p-6">
{cart.lines.map((item, i) => {
const merchandiseSearchParams = {} as MerchandiseSearchParams;
const merchandiseUrl = createUrl(
`/product/${item.merchandise.product.handle}`,
new URLSearchParams(merchandiseSearchParams)
);
item.merchandise.selectedOptions.forEach(({ name, value }) => {
if (value !== DEFAULT_OPTION) {
merchandiseSearchParams[name.toLowerCase()] = value;
}
});
const merchandiseUrl = createUrl(
`/product/${item.merchandise.product.handle}`,
new URLSearchParams(merchandiseSearchParams)
);
return (
<li key={i} data-testid="cart-item">
<Link
className="flex flex-row space-x-4 py-4"
href={merchandiseUrl}
onClick={onClose}
>
<div className="relative h-16 w-16 cursor-pointer overflow-hidden bg-white">
<Image
className="h-full w-full object-cover"
width={64}
height={64}
alt={
item.merchandise.product.featuredImage.altText ||
item.merchandise.product.title
}
src={item.merchandise.product.featuredImage.url}
/>
</div>
<div className="flex flex-1 flex-col text-base">
<span className="font-semibold">
{item.merchandise.product.title}
</span>
{item.merchandise.title !== DEFAULT_OPTION ? (
<p className="text-sm" data-testid="cart-product-variant">
{item.merchandise.title}
</p>
) : null}
</div>
<Price
className="flex flex-col justify-between space-y-2 text-sm"
amount={item.cost.totalAmount.amount}
currencyCode={item.cost.totalAmount.currencyCode}
return (
<li
key={i}
className="flex w-full flex-col border-b border-neutral-300 dark:border-neutral-700"
>
<div className="relative flex w-full flex-row justify-between px-1 py-4">
<div className="absolute z-40 -mt-2 ml-[55px]">
<DeleteItemButton item={item} />
</div>
<Link
href={merchandiseUrl}
onClick={() => setIsOpen(false)}
className="z-30 flex flex-row space-x-4"
>
<div className="relative h-16 w-16 cursor-pointer overflow-hidden rounded-md border border-neutral-300 bg-neutral-300 dark:border-neutral-700 dark:bg-neutral-900 dark:hover:bg-neutral-800">
<Image
className="h-full w-full object-cover"
width={64}
height={64}
alt={
item.merchandise.product.featuredImage.altText ||
item.merchandise.product.title
}
src={item.merchandise.product.featuredImage.url}
/>
</Link>
<div className="flex h-9 flex-row">
<DeleteItemButton item={item} />
<p className="ml-2 flex w-full items-center justify-center border dark:border-gray-700">
<span className="w-full px-2">{item.quantity}</span>
</p>
</div>
<div className="flex flex-1 flex-col text-base">
<span className="leading-tight">{item.merchandise.product.title}</span>
{item.merchandise.title !== DEFAULT_OPTION ? (
<p className="text-sm text-neutral-500 dark:text-neutral-400">
{item.merchandise.title}
</p>
) : null}
</div>
</Link>
<div className="flex h-16 flex-col justify-between">
<Price
className="flex justify-end space-y-2 text-right text-sm"
amount={item.cost.totalAmount.amount}
currencyCode={item.cost.totalAmount.currencyCode}
/>
<div className="ml-auto flex h-9 flex-row items-center rounded-full border border-neutral-200 dark:border-neutral-700">
<EditItemQuantityButton item={item} type="minus" />
<p className="w-6 text-center">
<span className="w-full text-sm">{item.quantity}</span>
</p>
<EditItemQuantityButton item={item} type="plus" />
</div>
</li>
);
})}
</ul>
<div className="border-t border-gray-200 pt-2 text-sm text-black dark:text-white">
<div className="mb-2 flex items-center justify-between">
<p>Subtotal</p>
<Price
className="text-right"
amount={cart.cost.subtotalAmount.amount}
currencyCode={cart.cost.subtotalAmount.currencyCode}
/>
</div>
<div className="mb-2 flex items-center justify-between">
<p>Taxes</p>
<Price
className="text-right"
amount={cart.cost.totalTaxAmount.amount}
currencyCode={cart.cost.totalTaxAmount.currencyCode}
/>
</div>
<div className="mb-2 flex items-center justify-between border-b border-gray-200 pb-2">
<p>Shipping</p>
<p className="text-right">Calculated at checkout</p>
</div>
<div className="mb-2 flex items-center justify-between font-bold">
<p>Total</p>
<Price
className="text-right"
amount={cart.cost.totalAmount.amount}
currencyCode={cart.cost.totalAmount.currencyCode}
/>
</div>
</div>
<a
href={cart.checkoutUrl}
className="flex w-full items-center justify-center bg-black p-3 text-sm font-medium uppercase text-white opacity-90 hover:opacity-100 dark:bg-white dark:text-black"
>
<span>Proceed to Checkout</span>
</a>
</div>
</div>
</li>
);
})}
</ul>
<div className="py-4 text-sm text-neutral-500 dark:text-neutral-400">
<div className="mb-3 flex items-center justify-between border-b border-neutral-200 pb-1 dark:border-neutral-700">
<p>Taxes</p>
<Price
className="text-right text-base text-black dark:text-white"
amount={cart.cost.totalTaxAmount.amount}
currencyCode={cart.cost.totalTaxAmount.currencyCode}
/>
</div>
) : null}
</Dialog.Panel>
</div>
</Dialog>
)}
</AnimatePresence>
<div className="mb-3 flex items-center justify-between border-b border-neutral-200 pb-1 pt-1 dark:border-neutral-700">
<p>Shipping</p>
<p className="text-right">{t('calculatedAtCheckout')}</p>
</div>
<div className="mb-3 flex items-center justify-between border-b border-neutral-200 pb-1 pt-1 dark:border-neutral-700">
<p>Total</p>
<Price
className="text-right text-base text-black dark:text-white"
amount={cart.cost.totalAmount.amount}
currencyCode={cart.cost.totalAmount.currencyCode}
/>
</div>
</div>
<a
href={cart.checkoutUrl}
className="bg-blue-600 block w-full rounded-full p-3 text-center text-sm font-medium text-white opacity-90 hover:opacity-100"
>
{t('proceedToCheckout')}
</a>
</div>
)}
</SheetContent>
</Sheet>
</>
);
}

View File

@ -0,0 +1,27 @@
import clsx from 'clsx';
import ShoppingBagIcon from 'components/icons/shopping-bag';
export default function OpenCart({
className,
quantity
}: {
className?: string;
quantity?: number;
}) {
return (
<div className="relative flex h-11 w-11 items-center justify-center rounded-md border border-ui-border text-high-contrast transition-colors">
<ShoppingBagIcon
className={clsx(
'h-4 stroke-current transition-all ease-in-out hover:scale-110 ',
className
)}
/>
{quantity ? (
<div className="bg-blue-600 absolute right-0 top-0 -mr-2 -mt-2 h-4 w-4 rounded text-[11px] font-medium text-white">
{quantity}
</div>
) : null}
</div>
);
}

View File

@ -1,26 +0,0 @@
import clsx from 'clsx';
function Grid(props: React.ComponentProps<'ul'>) {
return (
<ul {...props} className={clsx('grid grid-flow-row gap-4 py-5', props.className)}>
{props.children}
</ul>
);
}
function GridItem(props: React.ComponentProps<'li'>) {
return (
<li
{...props}
className={clsx(
'relative aspect-square h-full w-full overflow-hidden transition-opacity',
props.className
)}
>
{props.children}
</li>
);
}
Grid.Item = GridItem;
export default Grid;

View File

@ -1,53 +0,0 @@
import { GridTileImage } from 'components/grid/tile';
import { getCollectionProducts } from 'lib/shopify';
import type { Product } from 'lib/shopify/types';
import Link from 'next/link';
function ThreeItemGridItem({
item,
size,
background
}: {
item: Product;
size: 'full' | 'half';
background: 'white' | 'pink' | 'purple' | 'black';
}) {
return (
<div
className={size === 'full' ? 'lg:col-span-4 lg:row-span-2' : 'lg:col-span-2 lg:row-span-1'}
>
<Link className="block h-full" href={`/product/${item.handle}`}>
<GridTileImage
src={item.featuredImage.url}
width={size === 'full' ? 1080 : 540}
height={size === 'full' ? 1080 : 540}
priority={true}
background={background}
alt={item.title}
labels={{
title: item.title as string,
amount: item.priceRange.maxVariantPrice.amount,
currencyCode: item.priceRange.maxVariantPrice.currencyCode
}}
/>
</Link>
</div>
);
}
export async function ThreeItemGrid() {
// Collections that start with `hidden-*` are hidden from the search page.
const homepageItems = await getCollectionProducts('hidden-homepage-featured-items');
if (!homepageItems[0] || !homepageItems[1] || !homepageItems[2]) return null;
const [firstProduct, secondProduct, thirdProduct] = homepageItems;
return (
<section className="lg:grid lg:grid-cols-6 lg:grid-rows-2" data-testid="homepage-products">
<ThreeItemGridItem size="full" item={firstProduct} background="purple" />
<ThreeItemGridItem size="half" item={secondProduct} background="black" />
<ThreeItemGridItem size="half" item={thirdProduct} background="pink" />
</section>
);
}

View File

@ -1,70 +0,0 @@
import clsx from 'clsx';
import Image from 'next/image';
import Price from 'components/product/price';
export function GridTileImage({
isInteractive = true,
background,
active,
labels,
...props
}: {
isInteractive?: boolean;
background?: 'white' | 'pink' | 'purple' | 'black' | 'purple-dark' | 'blue' | 'cyan' | 'gray';
active?: boolean;
labels?: {
title: string;
amount: string;
currencyCode: string;
isSmall?: boolean;
};
} & React.ComponentProps<typeof Image>) {
return (
<div
className={clsx('relative flex h-full w-full items-center justify-center overflow-hidden', {
'bg-white dark:bg-white': background === 'white',
'bg-[#ff0080] dark:bg-[#ff0080]': background === 'pink',
'bg-[#7928ca] dark:bg-[#7928ca]': background === 'purple',
'bg-gray-900 dark:bg-gray-900': background === 'black',
'bg-violetDark dark:bg-violetDark': background === 'purple-dark',
'bg-blue-500 dark:bg-blue-500': background === 'blue',
'bg-cyan-500 dark:bg-cyan-500': background === 'cyan',
'bg-gray-100 dark:bg-gray-100': background === 'gray',
'bg-gray-100 dark:bg-gray-900': !background,
relative: labels
})}
>
{active !== undefined && active ? (
<span className="absolute h-full w-full bg-white opacity-25"></span>
) : null}
{props.src ? (
<Image
className={clsx('relative h-full w-full object-contain', {
'transition duration-300 ease-in-out hover:scale-105': isInteractive
})}
{...props}
alt={props.title || ''}
/>
) : null}
{labels ? (
<div className="absolute left-0 top-0 w-3/4 text-black dark:text-white">
<h3
data-testid="product-name"
className={clsx(
'inline bg-white box-decoration-clone py-3 pl-5 font-semibold leading-loose shadow-[1.25rem_0_0] shadow-white dark:bg-black dark:shadow-black',
!labels.isSmall ? 'text-3xl' : 'text-lg'
)}
>
{labels.title}
</h3>
<Price
className="w-fit bg-white px-5 py-3 text-sm font-semibold dark:bg-black dark:text-white"
amount={labels.amount}
currencyCode={labels.currencyCode}
/>
</div>
) : null}
</div>
);
}

View File

@ -1,6 +1,6 @@
'use client';
import { Info } from 'lucide-react';
import { InfoCircledIcon } from '@radix-ui/react-icons';
import dynamic from 'next/dynamic';
import Hero from 'components/modules/hero';
@ -57,7 +57,7 @@ const getContentComponent = ({ _type, _key, disabled, ...rest }: getContentCompo
key={`index-${_key}`}
>
<span className="inline-flex items-center bg-red p-2 text-sm font-bold">
<Info className="mr-1" />
<InfoCircledIcon className="mr-1" />
{`No matching component (Type: ${_type})`}
</span>
</div>

View File

@ -0,0 +1,15 @@
'use client';
import { useTranslations } from 'next-intl';
export default function CopyRight() {
const currentYear = new Date().getFullYear();
const copyrightDate = 2023 + (currentYear > 2023 ? `-${currentYear}` : '');
const t = useTranslations('ui');
return (
<p className="text-xs text-white">
&copy; {copyrightDate} Kodamera - {t('copyright')}
</p>
);
}

View File

@ -1,28 +1,72 @@
'use client'
import Text from '@/components/ui/text';
import { footerMenusQuery } from '@/lib/sanity/queries';
import { clientFetch } from '@/lib/sanity/sanity.client';
import LocaleSwitcher from 'components/ui/locale-switcher/locale-switcher';
import Logo from 'components/ui/logo/logo';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import CopyRight from './copyright';
const Footer = () => {
const currentYear = new Date().getFullYear();
const copyrightDate = 2023 + (currentYear > 2023 ? `-${currentYear}` : '');
const t = useTranslations('ui');
interface FooterProps {
locale: string;
}
export default async function Footer({ locale }: FooterProps) {
const params = {
locale: locale
};
const footerMenus = await clientFetch(footerMenusQuery, params);
return (
<footer className="border-t border-ui-border bg-app">
<div className="mx-auto w-full py-4 px-4 lg:py-6 lg:px-8 2xl:px-16 2xl:py-8">
<div className="flex flex-col w-full space-y-2 items-center transition-colors duration-150 md:flex-row md:items-baseline md:justify-between md:space-y-0">
<div className="mx-auto flex w-full flex-col">
<div className="flex w-full items-center justify-between p-4 transition-colors duration-150 md:space-y-0 lg:px-8 lg:py-6 2xl:px-16 2xl:py-8">
<Link className="flex flex-initial items-center font-bold md:mr-24" href="/">
<Logo />
</Link>
<p className="text-sm text-low-contrast">
&copy; {copyrightDate} Kodamera - {t('copyright')}
</p>
<LocaleSwitcher />
</div>
{footerMenus.length > 0 && (
<div className="grid w-full grid-cols-2 gap-4 p-4 lg:grid-cols-4 lg:gap-8 lg:px-8 lg:py-6 2xl:px-16 2xl:py-8">
{footerMenus.map((menu: object | any, index: number) => {
return (
<div key={index}>
<Text variant="label">{menu.title}</Text>
<ul className="mt-4 flex flex-col space-y-2" aria-label={menu.title}>
{menu.menu.links.map((link: object | any, index: number) => {
return (
<li className="text-sm" key={index}>
{link._type == 'linkInternal' ? (
<Link
className="hover:underline"
href={`/${link.reference.locale}/${link.reference.slug.current}`}
>
{link.title}
</Link>
) : (
<a
className="hover:underline"
href={link.url}
target={link.newWindow ? '_blank' : '_self'}
>
{link.title}
</a>
)}
</li>
);
})}
</ul>
</div>
);
})}
</div>
)}
<div className="flex items-center justify-center border-t border-ui-border bg-black px-4 py-3 lg:px-8 2xl:px-16">
<CopyRight />
</div>
</div>
</footer>
);
}
export default Footer;

View File

@ -0,0 +1,33 @@
import { categoriesQuery } from '@/lib/sanity/queries';
import { clientFetch } from '@/lib/sanity/sanity.client';
import Link from 'next/link';
interface DesktopMenuProps {
locale: string;
}
export default async function DesktopMenu({ locale }: DesktopMenuProps) {
const params = {
locale: locale
};
const categories = await clientFetch(categoriesQuery, params);
if (!categories) {
return;
}
return (
<ul className="flex space-x-4 lg:space-x-6">
{categories.map((category: { slug: string } | any, index: number) => {
return (
<li className="font-medium" key={index}>
<Link className="hover:underline" href={`/category/${category.slug}`}>
{category.title}
</Link>
</li>
);
})}
</ul>
);
}

View File

@ -1,73 +1,44 @@
'use client';
import LocaleSwitcher from 'components/ui/locale-switcher/locale-switcher';
import Cart from 'components/cart';
import OpenCart from 'components/cart/open-cart';
import Logo from 'components/ui/logo/logo';
import {
NavigationMenu,
NavigationMenuItem,
NavigationMenuLink,
NavigationMenuList,
navigationMenuTriggerStyle
} from 'components/ui/navigation-menu';
import { useLocale } from 'next-intl';
import Link from 'next/link';
import { FC } from 'react';
import { Suspense } from 'react';
import DesktopMenu from './desktop-menu';
import HeaderRoot from './header-root';
import MobileModal from './mobile-modal';
interface HeaderProps {
localeData: {
type: string;
locale: string;
translations: [];
};
locale: string;
}
const Header: FC<HeaderProps> = ({ localeData }: HeaderProps) => {
const locale = useLocale();
const Header = ({ locale }: HeaderProps) => {
return (
<HeaderRoot>
<div className="relative flex flex-col">
<div className="relative flex flex-col border-b border-ui-border bg-app">
<div className="relative flex h-14 w-full items-center justify-between px-4 py-2 lg:h-16 lg:px-8 lg:py-3 2xl:px-16">
<div className="md:hidden">
<MobileModal />
</div>
<div className="flex items-center">
<Link
href={`/${locale}`}
className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 transform cursor-pointer duration-100 ease-in-out lg:relative lg:left-0 lg:top-0 lg:translate-x-0 lg:translate-y-0"
href={`/`}
className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 transform cursor-pointer duration-100 ease-in-out md:relative md:left-0 md:top-0 md:translate-x-0 md:translate-y-0"
aria-label="Logo"
>
<Logo />
</Link>
</div>
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 transform">
<NavigationMenu delayDuration={0} className="hidden lg:block">
<NavigationMenuList>
<NavigationMenuItem>
<Link href={'/kategori/junior'} legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Junior
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href={'/kategori/trojor'} legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Tröjor
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href={'/kategori/byxor'} legacyBehavior passHref>
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Byxor
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
<div className="absolute left-1/2 top-1/2 hidden -translate-x-1/2 -translate-y-1/2 transform md:flex">
{/* @ts-expect-error Server Component (https://github.com/vercel/next.js/issues/42292) */}
<DesktopMenu locale={locale} />
</div>
<div>
<LocaleSwitcher localeData={localeData} currentLocale={locale} />
<div className="flex justify-end md:w-1/3">
<Suspense fallback={<OpenCart />}>
{/* @ts-expect-error Server Component (https://github.com/vercel/next.js/issues/42292) */}
<Cart />
</Suspense>
</div>
</div>
</div>

View File

@ -0,0 +1,26 @@
'use client';
import MenuIcon from '@/components/icons/menu';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import { useState } from 'react';
export default function MobileModal() {
const [isOpen, setIsOpen] = useState(false);
return (
<>
<Sheet open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>
<SheetTrigger aria-label="Open menu">
<div className="relative flex h-11 w-11 items-center justify-center rounded-md border border-ui-border text-high-contrast transition-colors">
<MenuIcon className="h-4 stroke-current transition-all ease-in-out hover:scale-110" />
</div>
</SheetTrigger>
<SheetContent side="left" className="bg-app">
<SheetHeader>
<SheetTitle className="text-lg font-semibold">Menu</SheetTitle>
</SheetHeader>
</SheetContent>
</Sheet>
</>
);
}

View File

@ -1,29 +0,0 @@
import Grid from 'components/grid';
import { GridTileImage } from 'components/grid/tile';
import { Product } from 'lib/shopify/types';
import Link from 'next/link';
export default function ProductGridItems({ products }: { products: Product[] }) {
return (
<>
{products.map((product) => (
<Grid.Item key={product.handle} className="animate-fadeIn">
<Link className="h-full w-full" href={`/product/${product.handle}`}>
<GridTileImage
alt={product.title}
labels={{
isSmall: true,
title: product.title,
amount: product.priceRange.maxVariantPrice.amount,
currencyCode: product.priceRange.maxVariantPrice.currencyCode
}}
src={product.featuredImage?.url}
width={600}
height={600}
/>
</Link>
</Grid.Item>
))}
</>
);
}

View File

@ -1,16 +1,16 @@
import dynamic from 'next/dynamic'
import dynamic from 'next/dynamic';
import { Carousel, CarouselItem } from 'components/modules/carousel/carousel'
const Card = dynamic(() => import('components/ui/card'))
import { Carousel, CarouselItem } from 'components/modules/carousel/carousel';
const Card = dynamic(() => import('components/ui/card'));
import Text from 'components/ui/text'
import Text from 'components/ui/text';
interface BlurbSectionProps {
blurbs: any
title: string
mobileLayout: string
desktopLayout: string
imageFormat: 'square' | 'portrait' | 'landscape'
blurbs: any;
title: string;
mobileLayout: string;
desktopLayout: string;
imageFormat: 'square' | 'portrait' | 'landscape';
}
const BlurbSection = ({
@ -18,37 +18,33 @@ const BlurbSection = ({
mobileLayout,
desktopLayout,
blurbs,
imageFormat,
imageFormat
}: BlurbSectionProps) => {
const gridLayout =
desktopLayout === '2-column'
? 'lg:grid-cols-2'
: desktopLayout === '3-column'
? 'lg:grid-cols-3'
: 'lg:grid-cols-4'
: 'lg:grid-cols-4';
const sliderLayout =
desktopLayout === '2-column' ? 2 : desktopLayout === '3-column' ? 3 : 4
const sliderLayout = desktopLayout === '2-column' ? 2 : desktopLayout === '3-column' ? 3 : 4;
return (
<div>
{title ? (
<Text
className="mb-4 px-4 lg:px-8 lg:mb-6 2xl:px-16 2xl:mb-8"
variant="sectionHeading"
>
<Text className="mb-4 px-4 lg:mb-6 lg:px-8 2xl:mb-8 2xl:px-16" variant="sectionHeading">
{title}
</Text>
) : (
<Text
className="italic mb-4 px-4 lg:px-8 lg:mb-6 2xl:px-16 2xl:mb-8"
className="mb-4 px-4 italic lg:mb-6 lg:px-8 2xl:mb-8 2xl:px-16"
variant="sectionHeading"
>
No title provided yet
</Text>
)}
<div
className={`px-4 grid ${gridLayout} gap-x-4 gap-y-8 ${
className={`grid px-4 ${gridLayout} gap-x-4 gap-y-8 ${
mobileLayout === 'stacked' ? 'lg:hidden' : 'hidden'
} lg:px-8 2xl:!px-16`}
>
@ -63,15 +59,11 @@ const BlurbSection = ({
imageFormat={blurb?.imageFormat}
/>
</div>
)
);
})}
</div>
<div
className={`${
mobileLayout === 'stacked' ? 'hidden lg:block' : 'block'
}`}
>
<div className={`${mobileLayout === 'stacked' ? 'hidden lg:block' : 'block'}`}>
{blurbs && (
<Carousel
gliderClasses={'px-4 lg:px-8 2xl:px-16'}
@ -80,9 +72,8 @@ const BlurbSection = ({
responsive={{
breakpoint: 1024,
settings: {
slidesToShow:
sliderLayout <= 4 ? sliderLayout + 0.5 : sliderLayout,
},
slidesToShow: sliderLayout <= 4 ? sliderLayout + 0.5 : sliderLayout
}
}}
>
{blurbs.map((blurb: any, index: number) => (
@ -100,7 +91,7 @@ const BlurbSection = ({
)}
</div>
</div>
)
}
);
};
export default BlurbSection
export default BlurbSection;

View File

@ -1,28 +1,28 @@
import { ArrowLeftIcon, ArrowRightIcon } from '@radix-ui/react-icons';
import 'glider-js/glider.min.css';
import { ArrowLeft, ArrowRight } from 'lucide-react';
import React from 'react';
import Glider from 'react-glider';
export interface CarouselItemProps {
children: React.ReactNode
className?: string
children: React.ReactNode;
className?: string;
}
export const CarouselItem: React.FC<CarouselItemProps> = ({
children,
className = 'ml-2 first:ml-0 lg:ml-4'
}: CarouselItemProps) => {
return <div className={className}>{children}</div>
}
return <div className={className}>{children}</div>;
};
export interface CarouselProps {
children: JSX.Element | JSX.Element[] | any
gliderClasses?: string
hasArrows?: boolean
hasDots?: boolean
slidesToShow?: number
slidesToScroll?: number
responsive?: any
children: JSX.Element | JSX.Element[] | any;
gliderClasses?: string;
hasArrows?: boolean;
hasDots?: boolean;
slidesToShow?: number;
slidesToScroll?: number;
responsive?: any;
}
export const Carousel: React.FC<CarouselProps> = ({
@ -32,29 +32,26 @@ export const Carousel: React.FC<CarouselProps> = ({
hasDots = true,
slidesToShow = 1,
slidesToScroll = 1,
responsive,
responsive
}) => {
return (
<>
<Glider
className={`block relative ${gliderClasses}`}
className={`relative block ${gliderClasses}`}
draggable
slidesToShow={slidesToShow}
scrollLock
slidesToScroll={slidesToScroll}
hasArrows={hasArrows}
hasDots={hasDots}
iconLeft={<ArrowLeft className="stroke-current" />}
iconRight={<ArrowRight className="stroke-current" />}
iconLeft={<ArrowLeftIcon className="h-6 w-6" />}
iconRight={<ArrowRightIcon className="h-6 w-6" />}
responsive={[responsive]}
>
{React.Children.map(children, (child) => {
return React.cloneElement(child)
})}
{React.Children.map(children, (child) => {
return React.cloneElement(child);
})}
</Glider>
</>
)
}
);
};

View File

@ -1,41 +1,40 @@
import dynamic from 'next/dynamic'
import dynamic from 'next/dynamic';
import Link from 'components/ui/link/link'
import Text from 'components/ui/text/text'
const SanityImage = dynamic(() => import('components/ui/sanity-image'))
import Link from 'components/ui/link/link';
import Text from 'components/ui/text/text';
const SanityImage = dynamic(() => import('components/ui/sanity-image'));
interface HeroProps {
variant: string
text?: string
label?: string
title: string
image: object | any
desktopImage: object | any
variant: string;
text?: string;
label?: string;
title: string;
image: object | any;
desktopImage: object | any;
link: {
title: string
title: string;
reference: {
title: string
title: string;
slug: {
current: string
}
}
}
current: string;
};
};
};
}
type HeroSize = keyof typeof heroSize
type HeroSize = keyof typeof heroSize;
const heroSize = {
fullScreen: 'aspect-[3/4] lg:aspect-auto lg:h-[calc(100vh-4rem)]',
halfScreen: 'aspect-square max-h-[60vh] lg:aspect-auto lg:min-h-[60vh]',
}
fullScreen: 'aspect-[3/4] lg:aspect-auto lg:h-[calc(75vh-4rem)]',
halfScreen: 'aspect-square max-h-[50vh] lg:aspect-auto lg:min-h-[50vh]'
};
const Hero = ({ variant, title, text, label, image, link }: HeroProps) => {
const heroClass = heroSize[variant as HeroSize] || heroSize.fullScreen
const heroClass = heroSize[variant as HeroSize] || heroSize.fullScreen;
return (
<div
className={`relative w-screen ${heroClass} flex flex-col justify-end relative text-high-contrast`}
className={`relative w-screen ${heroClass} relative flex flex-col justify-end text-high-contrast`}
>
{image && (
<SanityImage
@ -44,10 +43,10 @@ const Hero = ({ variant, title, text, label, image, link }: HeroProps) => {
priority={true}
width={1200}
height={600}
className="absolute inset-0 h-full w-full object-cover z-10"
className="absolute inset-0 z-10 h-full w-full object-cover"
/>
)}
<div className="flex flex-col items-start text-high-contrast absolute max-w-md z-50 left-4 bottom-5 lg:max-w-2xl lg:bottom-8 lg:left-8 2xl:left-16 2xl:bottom-16">
<div className="absolute bottom-5 left-4 z-50 flex max-w-md flex-col items-start text-high-contrast lg:bottom-8 lg:left-8 lg:max-w-2xl 2xl:bottom-16 2xl:left-16">
{label && (
<Text className="mb-1 lg:mb-2" variant="label">
{label}
@ -67,7 +66,7 @@ const Hero = ({ variant, title, text, label, image, link }: HeroProps) => {
)}
{link?.reference && (
<Link
className="inline-flex transition bg-high-contrast text-white text-base py-4 px-10 mt-6 hover:bg-low-contrast lg:mt-8"
className="mt-6 inline-flex bg-high-contrast px-10 py-4 text-base text-white transition hover:bg-low-contrast lg:mt-8"
href={link.reference.slug.current}
>
{link?.title ? link.title : link.reference.title}
@ -75,7 +74,7 @@ const Hero = ({ variant, title, text, label, image, link }: HeroProps) => {
)}
</div>
</div>
)
}
);
};
export default Hero
export default Hero;

View File

@ -1,4 +1,4 @@
'use client'
'use client';
// Once rollup supports 'use client' module directives then 'next-sanity' will include them and this re-export will no longer be necessary
export { PreviewSuspense as default } from 'next-sanity/preview'
export { PreviewSuspense as default } from 'next-sanity/preview';

24
components/price.tsx Normal file
View File

@ -0,0 +1,24 @@
import clsx from 'clsx';
const Price = ({
amount,
className,
currencyCode = 'USD',
currencyCodeClassName
}: {
amount: string;
className?: string;
currencyCode: string;
currencyCodeClassName?: string;
} & React.ComponentProps<'p'>) => (
<p suppressHydrationWarning={true} className={className}>
{`${new Intl.NumberFormat(undefined, {
style: 'currency',
currency: currencyCode,
currencyDisplay: 'narrowSymbol'
}).format(parseFloat(amount))}`}
<span className={clsx('ml-1 inline', currencyCodeClassName)}>{`${currencyCode}`}</span>
</p>
);
export default Price;

View File

@ -6,7 +6,7 @@ import clsx from 'clsx';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState, useTransition } from 'react';
import LoadingDots from 'components/ui/loading-dots';
import LoadingDots from 'components/loading-dots';
import { ProductVariant } from 'lib/shopify/types';
export function AddToCart({

View File

@ -1,14 +1,14 @@
'use client';
import { Carousel, CarouselItem } from 'components/modules/carousel/carousel';
import Price from 'components/product/price';
import SanityImage from 'components/ui/sanity-image';
import SanityImage from 'components/ui/sanity-image/sanity-image';
import Text from 'components/ui/text/text';
import { Product } from 'lib/storm/types/product';
import { cn } from 'lib/utils';
import { useTranslations } from 'next-intl';
import dynamic from 'next/dynamic';
import Price from './price';
const ProductCard = dynamic(() => import('components/ui/product-card'));
const Text = dynamic(() => import('components/ui/text'));
interface ProductViewProps {
product: Product;
relatedProducts: Product[];
@ -27,7 +27,7 @@ export default function ProductView({ product, relatedProducts }: ProductViewPro
<div className={`pdp aspect-square lg:hidden`}>
{images && (
<Carousel
hasArrows={true}
hasArrows={images.length > 1 ? true : false}
hasDots={false}
gliderClasses={'lg:px-8 2xl:px-16'}
slidesToScroll={1}
@ -69,11 +69,11 @@ export default function ProductView({ product, relatedProducts }: ProductViewPro
</div>
</div>
<div className="col-span-1 mx-auto flex h-auto w-full flex-col px-4 py-6 lg:sticky lg:top-8 lg:col-span-5 lg:px-8 lg:py-0 lg:pr-0 2xl:top-16 2xl:px-16 2xl:pr-0">
<div className="col-span-1 mx-auto flex h-auto w-full flex-col p-4 lg:sticky lg:top-8 lg:col-span-5 lg:px-8 lg:py-0 lg:pr-0 2xl:top-16 2xl:px-16 2xl:pr-0">
<Text variant={'productHeading'}>{product.name}</Text>
<Price
className="text-sm font-medium leading-tight lg:text-base"
className="mt-2 text-sm font-medium leading-tight lg:text-base"
amount={`${product.price.value}`}
currencyCode={product.price.currencyCode ? product.price.currencyCode : 'SEK'}
/>

View File

@ -1,22 +1,15 @@
// @ts-nocheck
'use client';
import clsx from 'clsx';
import { ProductOption, ProductVariant } from 'lib/shopify/types';
import { createUrl } from 'lib/utils';
import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { usePathname, useSearchParams } from 'next/navigation';
type ParamsMap = {
[key: string]: string; // ie. { color: 'Red', size: 'Large', ... }
};
type OptimizedVariant = {
type Combination = {
id: string;
availableForSale: boolean;
params: URLSearchParams;
[key: string]: string | boolean | URLSearchParams; // ie. { color: 'Red', size: 'Large', ... }
[key: string]: string | boolean; // ie. { color: 'Red', size: 'Large', ... }
};
export function VariantSelector({
@ -27,8 +20,7 @@ export function VariantSelector({
variants: ProductVariant[];
}) {
const pathname = usePathname();
const currentParams = useSearchParams();
const router = useRouter();
const searchParams = useSearchParams();
const hasNoOptionsOrJustOneOption =
!options.length || (options.length === 1 && options[0]?.values.length === 1);
@ -36,96 +28,77 @@ export function VariantSelector({
return null;
}
// Discard any unexpected options or values from url and create params map.
const paramsMap: ParamsMap = Object.fromEntries(
Array.from(currentParams.entries()).filter(([key, value]) =>
options.find((option) => option.name.toLowerCase() === key && option.values.includes(value))
const combinations: Combination[] = variants.map((variant) => ({
id: variant.id,
availableForSale: variant.availableForSale,
// Adds key / value pairs for each variant (ie. "color": "Black" and "size": 'M").
...variant.selectedOptions.reduce(
(accumulator, option) => ({ ...accumulator, [option.name.toLowerCase()]: option.value }),
{}
)
);
// Optimize variants for easier lookups.
const optimizedVariants: OptimizedVariant[] = variants.map((variant) => {
const optimized: OptimizedVariant = {
id: variant.id,
availableForSale: variant.availableForSale,
params: new URLSearchParams()
};
variant.selectedOptions.forEach((selectedOption) => {
const name = selectedOption.name.toLowerCase();
const value = selectedOption.value;
optimized[name] = value;
optimized.params.set(name, value);
});
return optimized;
});
// Find the first variant that is:
//
// 1. Available for sale
// 2. Matches all options specified in the url (note that this
// could be a partial match if some options are missing from the url).
//
// If no match (full or partial) is found, use the first variant that is
// available for sale.
const selectedVariant: OptimizedVariant | undefined =
optimizedVariants.find(
(variant) =>
variant.availableForSale &&
Object.entries(paramsMap).every(([key, value]) => variant[key] === value)
) || optimizedVariants.find((variant) => variant.availableForSale);
const selectedVariantParams = new URLSearchParams(selectedVariant?.params);
const currentUrl = createUrl(pathname, currentParams);
const selectedVariantUrl = createUrl(pathname, selectedVariantParams);
if (currentUrl !== selectedVariantUrl) {
router.replace(selectedVariantUrl);
}
}));
return options.map((option) => (
<dl className="mb-8" key={option.id}>
<dt className="mb-4 text-sm uppercase tracking-wide">{option.name}</dt>
<dd className="flex flex-wrap gap-3">
{option.values.map((value) => {
// Base option params on selected variant params.
const optionParams = new URLSearchParams(selectedVariantParams);
// Update the params using the current option to reflect how the url would change.
optionParams.set(option.name.toLowerCase(), value);
const optionNameLowerCase = option.name.toLowerCase();
const optionUrl = createUrl(pathname, optionParams);
// Base option params on current params so we can preserve any other param state in the url.
const optionSearchParams = new URLSearchParams(searchParams.toString());
// The option is active if it in the url params.
const isActive = selectedVariantParams.get(option.name.toLowerCase()) === value;
// Update the option params using the current option to reflect how the url *would* change,
// if the option was clicked.
optionSearchParams.set(optionNameLowerCase, value);
const optionUrl = createUrl(pathname, optionSearchParams);
// The option is available for sale if it fully matches the variant in the option's url params.
// It's super important to note that this is the options params, *not* the selected variant's params.
// This is the "magic" that will cross check possible future variant combinations and preemptively
// disable combinations that are not possible.
const isAvailableForSale = optimizedVariants.find((a) =>
Array.from(optionParams.entries()).every(([key, value]) => a[key] === value)
)?.availableForSale;
// In order to determine if an option is available for sale, we need to:
//
// 1. Filter out all other param state
// 2. Filter out invalid options
// 3. Check if the option combination is available for sale
//
// This is the "magic" that will cross check possible variant combinations and preemptively
// disable combinations that are not available. For example, if the color gray is only available in size medium,
// then all other sizes should be disabled.
const filtered = Array.from(optionSearchParams.entries()).filter(([key, value]) =>
options.find(
(option) => option.name.toLowerCase() === key && option.values.includes(value)
)
);
const isAvailableForSale = combinations.find((combination) =>
filtered.every(
([key, value]) => combination[key] === value && combination.availableForSale
)
);
// The option is active if it's in the url params.
const isActive = searchParams.get(optionNameLowerCase) === value;
// You can't disable a link, so we need to render something that isn't clickable.
const DynamicTag = isAvailableForSale ? Link : 'p';
const dynamicProps = {
...(isAvailableForSale && { scroll: false })
};
return (
<DynamicTag
key={value}
aria-disabled={!isAvailableForSale}
href={optionUrl}
title={`${option.name} ${value}${!isAvailableForSale ? ' (Out of Stock)' : ''}`}
className={clsx(
'flex h-12 min-w-[48px] items-center justify-center rounded-full px-2 text-sm',
'flex min-w-[48px] items-center justify-center rounded-full border bg-neutral-100 px-2 py-1 text-sm dark:border-neutral-800 dark:bg-neutral-900',
{
'cursor-default ring-2 ring-black dark:ring-white': isActive,
'ring-1 ring-gray-300 transition duration-300 ease-in-out hover:scale-110 hover:bg-gray-100 hover:ring-black dark:ring-gray-700 dark:hover:bg-transparent dark:hover:ring-white':
'cursor-default ring-2 ring-blue-600': isActive,
'ring-1 ring-transparent transition duration-300 ease-in-out hover:scale-110 hover:ring-blue-600 ':
!isActive && isAvailableForSale,
'relative z-10 cursor-not-allowed overflow-hidden bg-gray-100 ring-1 ring-gray-300 before:absolute before:inset-x-0 before:-z-10 before:h-px before:-rotate-45 before:bg-gray-300 before:transition-transform dark:bg-gray-900 dark:ring-gray-700 before:dark:bg-gray-700':
'relative z-10 cursor-not-allowed overflow-hidden bg-neutral-100 text-neutral-500 ring-1 ring-neutral-300 before:absolute before:inset-x-0 before:-z-10 before:h-px before:-rotate-45 before:bg-neutral-300 before:transition-transform dark:bg-neutral-900 dark:text-neutral-400 dark:ring-neutral-700 before:dark:bg-neutral-700':
!isAvailableForSale
}
)}
data-testid={isActive ? 'selected-variant' : 'variant'}
{...dynamicProps}
>
{value}
</DynamicTag>

View File

@ -10,7 +10,7 @@ const Prose: FunctionComponent<TextProps> = ({ html, className }) => {
return (
<div
className={clsx(
'prose mx-auto max-w-6xl text-base leading-7 text-black prose-headings:mt-8 prose-headings:font-semibold prose-headings:tracking-wide prose-headings:text-black prose-h1:text-5xl prose-h2:text-4xl prose-h3:text-3xl prose-h4:text-2xl prose-h5:text-xl prose-h6:text-lg prose-a:text-black prose-a:underline hover:prose-a:text-gray-300 prose-strong:text-black prose-ol:mt-8 prose-ol:list-decimal prose-ol:pl-6 prose-ul:mt-8 prose-ul:list-disc prose-ul:pl-6 dark:text-white dark:prose-headings:text-white dark:prose-a:text-white dark:prose-strong:text-white',
'prose mx-auto max-w-6xl text-base leading-7 text-black prose-headings:mt-8 prose-headings:font-semibold prose-headings:tracking-wide prose-headings:text-black prose-h1:text-5xl prose-h2:text-4xl prose-h3:text-3xl prose-h4:text-2xl prose-h5:text-xl prose-h6:text-lg prose-a:text-black prose-a:underline hover:prose-a:text-neutral-300 prose-strong:text-black prose-ol:mt-8 prose-ol:list-decimal prose-ol:pl-6 prose-ul:mt-8 prose-ul:list-disc prose-ul:pl-6 dark:text-white dark:prose-headings:text-white dark:prose-a:text-white dark:prose-strong:text-white',
className
)}
dangerouslySetInnerHTML={{ __html: html as string }}

View File

@ -1,48 +1,47 @@
'use client'
'use client';
import SanityImage from 'components/ui/sanity-image'
import { cn } from 'lib/utils'
import Link from 'next/link'
import { FC } from 'react'
import SanityImage from 'components/ui/sanity-image';
import { cn } from 'lib/utils';
import Link from 'next/link';
import { FC } from 'react';
interface CardProps {
className?: string
title: string
image: object | any
link: object | any
text?: string
imageFormat?: 'square' | 'portrait' | 'landscape'
className?: string;
title: string;
image: object | any;
link: object | any;
text?: string;
imageFormat?: 'square' | 'portrait' | 'landscape';
}
const placeholderImg = '/product-img-placeholder.svg'
const Card: FC<CardProps> = ({ className, title, image, link, text, imageFormat = 'square' }) => {
const rootClassName = cn('relative', className);
const Card: FC<CardProps> = ({
className,
title,
image,
link,
text,
imageFormat = 'square',
}) => {
const rootClassName = cn('relative', className)
const { linkType } = link
const { linkType } = link;
const imageWrapperClasses = cn('w-full h-full overflow-hidden relative', {
['aspect-square']: imageFormat === 'square',
['aspect-[3/4]']: imageFormat === 'portrait',
['aspect-[4/3]']: imageFormat === 'landscape',
})
const imageClasses = cn('object-cover w-full h-full')
['aspect-[4/3]']: imageFormat === 'landscape'
});
const imageClasses = cn('object-cover w-full h-full');
function Card() {
if (linkType === 'internal') {
const type = link.internalLink.reference._type;
let href = '';
if (type === 'product') {
href = `/product/${link.internalLink.reference.slug.current}`;
} else if (type === 'category') {
href = `/category/${link.internalLink.reference.slug.current}`;
} else {
href = `${link.internalLink.reference.slug.current}`;
}
return (
<Link
href={link.internalLink.reference.slug.current}
className={rootClassName}
aria-label={title}
>
<Link href={href} className={rootClassName} aria-label={title}>
<div className="flex flex-col">
{image && (
<div className={imageWrapperClasses}>
@ -54,25 +53,17 @@ const Card: FC<CardProps> = ({
/>
</div>
)}
<h3 className="mt-2 text-high-contrast font-medium text-sm underline underline-offset-2 lg:text-lg lg:mt-3 lg:underline-offset-4 2xl:text-xl">
<h3 className="mt-2 text-sm font-medium text-high-contrast underline underline-offset-2 lg:mt-3 lg:text-lg lg:underline-offset-4 2xl:text-xl">
{title}
</h3>
{text && (
<p className="text-sm mt-1 text-low-contrast lg:text-base lg:mt-2">
{text}
</p>
)}
{text && <p className="mt-1 text-sm text-low-contrast lg:mt-2 lg:text-base">{text}</p>}
</div>
</Link>
)
);
}
return (
<a
href={link.externalLink.url}
className={rootClassName}
aria-label={title}
>
<a href={link.externalLink.url} className={rootClassName} aria-label={title}>
<div className="flex flex-col">
{image && (
<div className={imageWrapperClasses}>
@ -84,20 +75,16 @@ const Card: FC<CardProps> = ({
/>
</div>
)}
<h3 className="mt-2 text-high-contrast font-medium text-sm underline underline-offset-2 lg:text-lg lg:mt-3 lg:underline-offset-4 2xl:text-xl">
<h3 className="mt-2 text-sm font-medium text-high-contrast underline underline-offset-2 lg:mt-3 lg:text-lg lg:underline-offset-4 2xl:text-xl">
{title}
</h3>
{text && (
<p className="text-sm mt-1 text-low-contrast lg:text-base lg:mt-2">
{text}
</p>
)}
{text && <p className="mt-1 text-sm text-low-contrast lg:mt-2 lg:text-base">{text}</p>}
</div>
</a>
)
);
}
return <Card />
}
return <Card />;
};
export default Card
export default Card;

View File

@ -1,33 +1,34 @@
'use client'
'use client';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'
import { CheckIcon, ChevronRightIcon, CircleIcon } from '@radix-ui/react-icons'
import * as React from 'react'
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { CheckIcon, ChevronRightIcon, CircleIcon } from '@radix-ui/react-icons';
import { cn } from 'lib/utils'
import * as React from 'react';
const DropdownMenu = DropdownMenuPrimitive.Root
import { cn } from '@/lib/utils';
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
'flex cursor-default select-none items-center rounded-sm py-1.5 px-2 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100',
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent',
inset && 'pl-8',
className
)}
@ -36,9 +37,8 @@ const DropdownMenuSubTrigger = React.forwardRef<
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
));
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
@ -47,14 +47,13 @@ const DropdownMenuSubContent = React.forwardRef<
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border border-slate-100 bg-white p-1 text-high-contrast shadow-md animate-in slide-in-from-left-1',
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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',
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
));
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
@ -65,32 +64,32 @@ const DropdownMenuContent = React.forwardRef<
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[8rem] overflow-hidden bg-app text-high-contrast animate-in data-[side=right]:slide-in-from-left-2 data-[side=left]:slide-in-from-right-2 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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',
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1 text-sm font-medium outline-none hover:bg-subtle focus:bg-subtle data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
inset && 'pl-8',
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
@ -99,7 +98,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm font-medium outline-none hover:bg-subtle focus:bg-subtle data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
checked={checked}
@ -112,9 +111,8 @@ const DropdownMenuCheckboxItem = React.forwardRef<
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
));
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
@ -123,7 +121,7 @@ const DropdownMenuRadioItem = React.forwardRef<
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm font-medium outline-none hover:bg-subtle focus:bg-subtle data-[disabled]:pointer-events-none data-[disabled]:opacity-50 ',
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
@ -135,26 +133,22 @@ const DropdownMenuRadioItem = React.forwardRef<
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
'px-2 py-1.5 text-sm font-semibold text-high-contrast',
inset && 'pl-8',
className
)}
className={cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', className)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
@ -162,32 +156,33 @@ const DropdownMenuSeparator = React.forwardRef<
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-ui-border', className)}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
'ml-auto text-xs tracking-widest text-low-contrast',
className
)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = 'DropdownMenuShortcut'
<span className={cn('ml-auto text-xs tracking-widest opacity-60', className)} {...props} />
);
};
DropdownMenuShortcut.displayName = 'DropdownMenuShortcut';
export {
DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator,
DropdownMenuShortcut, DropdownMenuSub,
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuPortal,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger, DropdownMenuTrigger
}
DropdownMenuSubTrigger,
DropdownMenuTrigger
};

View File

@ -1,82 +1,82 @@
import LanguageIcon from 'components/icons/language';
'use client';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger
} from 'components/ui/dropdown/dropdown';
} from '@/components/ui/dropdown-menu';
import LanguageIcon from 'components/icons/language';
import { useLocale, useTranslations } from 'next-intl';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useState } from 'react';
import { i18n } from '../../../i18n-config';
import { supportedLanguages } from '../../../i18n-config';
interface LocaleSwitcherProps {
currentLocale: string;
localeData: {
type: string;
locale: string;
translations: [];
};
}
// interface LocaleSwitcherProps {
// localeData: {
// type: string;
// locale: string;
// translations: [];
// };
// }
export default function LocaleSwitcher({ currentLocale, localeData }: LocaleSwitcherProps) {
export default function LocaleSwitcher() {
const pathName = usePathname();
const translations = localeData.translations;
const currentLocale = useLocale();
const t = useTranslations('ui');
// const translations = localeData.translations;
const redirectedPathName = (locale: string) => {
if (!pathName || translations.length === 0) return '/';
if (!pathName) return '/';
if (translations.length > 0) {
const translation = translations.find((obj) => {
return obj['locale'] === locale;
});
// if (translations.length > 0) {
// const translation = translations.find((obj) => {
// return obj['locale'] === locale;
// });
if (translation) {
const url = `/${translation['locale']}${translation['slug']}`;
// if (translation) {
// const url = `/${translation['locale']}${translation['slug']}`;
return url;
}
}
// return url;
// }
// }
return '/';
return `/${locale}`;
};
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<>
<DropdownMenu open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>
<DropdownMenuTrigger asChild>
<button
className={
'flex shrink-0 items-center justify-center space-x-1 rounded bg-app p-2 text-xs font-semibold uppercase outline-none ring-2 ring-transparent transition duration-200 hover:ring-ui-border focus:ring-ui-border'
}
aria-label="Language selector"
>
<LanguageIcon className="h-6 w-6" />
<span>{currentLocale}</span>
</button>
<DropdownMenuTrigger
className="relative flex h-11 w-11 items-center justify-center rounded-md border border-neutral-200 text-black transition-colors"
aria-label={t('languageSelector')}
>
<LanguageIcon className="h-6 w-6" />
<span className="sr-only">{currentLocale}</span>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="drop-shadow-xl">
<DropdownMenuContent align="end" className="bg-app">
<ul className="">
{i18n.locales.map((locale) => {
if (currentLocale === locale.id) {
return;
} else {
return (
<li className="" key={locale.id}>
<Link
className="flex w-full cursor-pointer px-4 py-2 text-sm"
href={redirectedPathName(locale.id)}
>
{locale.title}
</Link>
</li>
);
}
{supportedLanguages.locales.map((locale) => {
return (
<DropdownMenuItem className="p-0" key={locale.id}>
<Link
className={`flex w-full cursor-pointer items-center px-4 py-2 text-sm ${
currentLocale == locale.id && 'font-bold'
}`}
href={redirectedPathName(locale.id)}
>
{locale.title}
</Link>
</DropdownMenuItem>
);
})}
</ul>
</DropdownMenuContent>
</DropdownMenu>
</div>
</>
);
}

View File

@ -1,2 +0,0 @@
export * from './navigation-menu';

View File

@ -1,123 +0,0 @@
'use client'
import * as NavigationMenuPrimitive from '@radix-ui/react-navigation-menu'
import { cva } from 'class-variance-authority'
import { ChevronDown } from 'lucide-react'
import * as React from 'react'
import { cn } from 'lib/utils'
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn(
'relative flex flex-1 items-center justify-center',
className
)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
))
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn(
'group flex flex-1 list-none items-center justify-center',
className
)}
{...props}
/>
))
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
'inline-flex items-center justify-center font-medium transition-colors focus:outline-none focus:bg-subtle disabled:opacity-50 disabled:pointer-events-none hover:bg-ui-hover data-[state=open]:bg-ui-hover data-[active]:bg-ui-active h-10 py-1 px-3 group w-max'
)
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), 'group', className)}
{...props}
>
{children}{' '}
<ChevronDown
className="relative top-[1px] ml-2 h-5 w-5 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
))
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
'data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=to-start]:slide-out-to-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=from-end]:slide-in-from-right-52 top-0 left-0 w-full md:absolute md:w-auto',
className
)}
{...props}
/>
))
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName
const NavigationMenuLink = NavigationMenuPrimitive.Link
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn('absolute left-0 top-full flex justify-center z-50')}>
<NavigationMenuPrimitive.Viewport
className={cn(
'origin-top-center data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:zoom-in-90 data-[state=closed]:zoom-out-95 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden drop-shadow bg-white md:w-[var(--radix-navigation-menu-viewport-width)]',
className
)}
ref={ref}
{...props}
/>
</div>
))
NavigationMenuViewport.displayName =
NavigationMenuPrimitive.Viewport.displayName
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
'data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=visible]:fade-in data-[state=hidden]:fade-out top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden',
className
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 bg-ui" />
</NavigationMenuPrimitive.Indicator>
))
NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
NavigationMenu, NavigationMenuContent, NavigationMenuIndicator, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger, NavigationMenuViewport, navigationMenuTriggerStyle
}

View File

@ -8,8 +8,6 @@ import dynamic from 'next/dynamic';
import Link from 'next/link';
import { FC } from 'react';
const WishlistButton = dynamic(() => import('components/ui/wishlist-button'));
const SanityImage = dynamic(() => import('components/ui/sanity-image'));
interface Props {
@ -23,18 +21,13 @@ const ProductCard: FC<Props> = ({ product, className, variant = 'default' }) =>
return (
<Link
href={`${product.slug}`}
href={`/product/${product.slug}`}
className={rootClassName}
aria-label={product.name}
locale={product.locale}
>
{variant === 'default' && (
<div className={'relative flex h-full w-full flex-col justify-center'}>
<WishlistButton
className={'absolute right-4 top-4 z-10'}
productId={product.id}
variant={product?.variants ? (product.variants[0] as any) : null}
/>
<div className="relative h-full w-full overflow-hidden">
{product?.images && (
<SanityImage
@ -46,11 +39,11 @@ const ProductCard: FC<Props> = ({ product, className, variant = 'default' }) =>
</div>
<div className={cn('flex flex-col items-start text-high-contrast', className)}>
<Text className="mt-2 lg:mt-3" variant="listChildHeading">
<Text className="mt-3" variant="listChildHeading">
{product.title}
</Text>
<Price
className="text-sm font-medium leading-tight lg:text-base"
className="mt-1 text-sm font-bold leading-tight lg:text-base"
amount={`${product.price.value}`}
currencyCode={product.price.currencyCode ? product.price.currencyCode : 'SEK'}
/>

View File

@ -1,21 +1,21 @@
'use client'
'use client';
import { urlForImage } from 'lib/sanity/sanity.image'
import { cn } from 'lib/utils'
import Image from 'next/image'
import { urlForImage } from 'lib/sanity/sanity.image';
import { cn } from 'lib/utils';
import Image from 'next/image';
interface SanityImageProps {
image: object | any
alt: string
priority?: boolean
width?: number
height?: number
quality?: number
sizes?: string
className?: string
image: object | any;
alt: string;
priority?: boolean;
width?: number;
height?: number;
quality?: number;
sizes?: string;
className?: string;
}
const placeholderImg = '/product-img-placeholder.svg'
const placeholderImg = '/product-img-placeholder.svg';
export default function SanityImage(props: SanityImageProps) {
const {
@ -26,10 +26,10 @@ export default function SanityImage(props: SanityImageProps) {
height = 1080,
width = 1080,
sizes = '100vw',
className,
} = props
className
} = props;
const rootClassName = cn('w-full h-auto', className)
const rootClassName = cn('w-full h-auto', className);
const image = source?.asset?._rev ? (
<>
@ -39,11 +39,7 @@ export default function SanityImage(props: SanityImageProps) {
width={width}
height={height}
alt={alt}
src={urlForImage(source)
.width(width)
.height(height)
.quality(quality)
.url()}
src={urlForImage(source).width(width).height(height).quality(quality).url()}
sizes={sizes}
priority={priority}
blurDataURL={source.asset.metadata.lqip}
@ -61,7 +57,7 @@ export default function SanityImage(props: SanityImageProps) {
priority={false}
/>
</>
)
);
return image
return image;
}

122
components/ui/sheet.tsx Normal file
View File

@ -0,0 +1,122 @@
'use client';
import * as SheetPrimitive from '@radix-ui/react-dialog';
import { Cross1Icon } from '@radix-ui/react-icons';
import { cva, type VariantProps } from 'class-variance-authority';
import * as React from 'react';
import { cn } from '@/lib/utils';
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = ({ className, ...props }: SheetPrimitive.DialogPortalProps) => (
<SheetPrimitive.Portal className={cn(className)} {...props} />
);
SheetPortal.displayName = SheetPrimitive.Portal.displayName;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
'fixed inset-0 z-50 bg-background/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
'fixed z-50 gap-4 bg-background p-4 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 lg:p-6',
{
variants: {
side: {
top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
bottom:
'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
left: 'inset-y-0 left-0 h-full w-full border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left md:max-w-md',
right:
'inset-y-0 right-0 h-full w-full border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right md:max-w-md'
}
},
defaultVariants: {
side: 'right'
}
}
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = 'right', className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary md:right-6 md:top-6">
<Cross1Icon className="h-6 w-6" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
));
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col space-y-2', className)} {...props} />
);
SheetHeader.displayName = 'SheetHeader';
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
{...props}
/>
);
SheetFooter.displayName = 'SheetFooter';
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold text-foreground', className)}
{...props}
/>
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger
};

View File

@ -69,8 +69,8 @@ const Text: FunctionComponent<TextProps> = ({
variant === 'productHeading',
['max-w-prose font-display text-2xl font-extrabold leading-none md:text-3xl md:leading-none lg:text-4xl lg:leading-none']:
variant === 'sectionHeading',
['text-sm font-medium leading-tight lg:text-base']: variant === 'listChildHeading',
['max-w-prose text-sm lg:text-base 2xl:text-lg']: variant === 'label',
['text-sm leading-tight lg:text-base']: variant === 'listChildHeading',
['max-w-prose text-lg text-high-contrast lg:text-xl']: variant === 'label',
['max-w-prose lg:text-lg 2xl:text-xl']: variant === 'paragraph'
},
className

View File

@ -1 +0,0 @@
export { default } from './wishlist-button';

View File

@ -1,79 +0,0 @@
import type { Product, ProductVariant } from 'lib/storm/types/product'
import { cn } from 'lib/utils'
import { Heart } from 'lucide-react'
import { useTranslations } from 'next-intl'
import React, { FC, useState } from 'react'
type Props = {
productId: Product['id']
variant: ProductVariant
} & React.ButtonHTMLAttributes<HTMLButtonElement>
const WishlistButton: FC<Props> = ({
productId,
variant,
className,
...props
}) => {
const [loading, setLoading] = useState(false)
const t = useTranslations('ui.button')
// @ts-ignore Wishlist is not always enabled
// const itemInWishlist = data?.items?.find(
// // @ts-ignore Wishlist is not always enabled
// (item) => item.product_id === productId && item.variant_id === variant.id
// )
const handleWishlistChange = async (e: any) => {
e.preventDefault()
if (loading) return
// A login is required before adding an item to the wishlist
// if (!customer) {
// setModalView('LOGIN_VIEW')
// return openModal()
// }
// setLoading(true)
// try {
// if (itemInWishlist) {
// await removeItem({ id: itemInWishlist.id! })
// } else {
// await addItem({
// productId,
// variantId: variant?.id!,
// })
// }
// setLoading(false)
// } catch (err) {
// setLoading(false)
// }
}
return (
<button
aria-label={t('wishList')}
className={cn(
'w-10 h-10 text-high-contrast bg-app border border-high-contrast flex items-center justify-center font-semibold cursor-pointer text-sm duration-200 ease-in-out transition-[color,background-color,opacity] ',
className
)}
// onClick={handleWishlistChange}
{...props}
>
<Heart
className={cn(
'duration-200 ease-in-out w-5 h-5 transition-[transform,fill] text-current',
{
['fill-low-contrast']: loading,
// ['fill-high-contrast']: itemInWishlist,
}
)}
/>
</button>
)
}
export default WishlistButton

View File

@ -1,4 +1,4 @@
export const i18n = {
export const supportedLanguages = {
defaultLocale: 'sv',
locales: [
{
@ -12,4 +12,4 @@ export const i18n = {
],
} as const
export type Locale = typeof i18n['locales'][number]
export type Locale = typeof supportedLanguages['locales'][number]

30
lib/constants.ts Normal file
View File

@ -0,0 +1,30 @@
export type SortFilterItem = {
title: string;
slug: string | null;
sortKey: 'RELEVANCE' | 'BEST_SELLING' | 'CREATED_AT' | 'PRICE';
reverse: boolean;
};
export const defaultSort: SortFilterItem = {
title: 'Relevance',
slug: null,
sortKey: 'RELEVANCE',
reverse: false
};
export const sorting: SortFilterItem[] = [
defaultSort,
{ title: 'Trending', slug: 'trending-desc', sortKey: 'BEST_SELLING', reverse: false }, // asc
{ title: 'Latest arrivals', slug: 'latest-desc', sortKey: 'CREATED_AT', reverse: true },
{ title: 'Price: Low to high', slug: 'price-asc', sortKey: 'PRICE', reverse: false }, // asc
{ title: 'Price: High to low', slug: 'price-desc', sortKey: 'PRICE', reverse: true }
];
export const TAGS = {
collections: 'collections',
products: 'products'
};
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden';
export const DEFAULT_OPTION = 'Default Title';
export const SHOPIFY_GRAPHQL_API_ENDPOINT = '/api/2023-01/graphql.json';

View File

@ -1,25 +0,0 @@
export type SortFilterItem = {
title: string;
slug: string | null;
sortKey: 'RELEVANCE' | 'BEST_SELLING' | 'CREATED_AT' | 'PRICE';
reverse: boolean;
};
export const defaultSort: SortFilterItem = {
title: 'Relevance',
slug: null,
sortKey: 'RELEVANCE',
reverse: false
};
export const sorting: SortFilterItem[] = [
defaultSort,
{ title: 'Trending', slug: 'trending-desc', sortKey: 'BEST_SELLING', reverse: false }, // asc
{ title: 'Latest arrivals', slug: 'latest-desc', sortKey: 'CREATED_AT', reverse: true },
{ title: 'Price: Low to high', slug: 'price-asc', sortKey: 'PRICE', reverse: false }, // asc
{ title: 'Price: High to low', slug: 'price-desc', sortKey: 'PRICE', reverse: true }
];
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden';
export const DEFAULT_OPTION = 'Default Title';
export const SHOPIFY_GRAPHQL_API_ENDPOINT = '/api/2023-01/graphql.json';

View File

@ -107,6 +107,7 @@ export const modules = `
desktopLayout,
imageFormat,
blurbs[]->{
_type,
title,
text,
link {
@ -209,29 +210,27 @@ export const productQuery = `*[_type == "product" && slug.current == $slug && la
"slug": slug.current,
"locale": language
},
"product": {
id,
"name": title,
description,
"descriptionHtml": "",
images[] {
${imageFields}
},
price {
value,
currencyCode,
retailPrice
},
options[] {
id,
displayName,
values[] {
label,
"hexColors": hexColors.hex
}
},
"variants": []
id,
"name": title,
description,
"descriptionHtml": "",
images[] {
${imageFields}
},
price {
value,
currencyCode,
retailPrice
},
options[] {
id,
displayName,
values[] {
label,
"hexColors": hexColors.hex
}
},
"variants": [],
seo {
${seoFields}
}
@ -243,15 +242,8 @@ export const categoryQuery = `*[_type == "category" && slug.current == $slug &&
title,
"slug": slug.current,
"locale": language,
showBanner,
banner {
_type,
_key,
title,
text,
image {
${imageFields}
}
image {
${imageFields}
},
"translations": *[_type == "translation.metadata" && references(^._id)].translations[].value->{
title,
@ -263,6 +255,34 @@ export const categoryQuery = `*[_type == "category" && slug.current == $slug &&
}
}`;
// Categories query
export const categoriesQuery = `*[_type == "category" && language == $locale] | order(title asc) {
_type,
title,
"slug": slug.current,
"locale": language,
}`;
// Footer menu query
export const footerMenusQuery = `*[_type == "footerMenu" && language == $locale] | order(title asc) {
_type,
title,
"locale": language,
menu {
title,
links[] {
_type,
title,
reference-> {
slug,
"locale": language
},
url,
newWindow
}
}
}`;
// Site settings query
export const siteSettingsQuery = `*[_type == "settings" && language == $locale][0] {
menuMain {

View File

@ -9,7 +9,7 @@ export const client = createClient({
projectId,
dataset,
apiVersion,
useCdn: false,
useCdn: true,
});
export const clientFetch = cache(client.fetch.bind(client));

View File

@ -1,5 +1,8 @@
import { HIDDEN_PRODUCT_TAG, SHOPIFY_GRAPHQL_API_ENDPOINT } from 'lib/constants';
import { HIDDEN_PRODUCT_TAG, SHOPIFY_GRAPHQL_API_ENDPOINT, TAGS } from 'lib/constants';
import { isShopifyError } from 'lib/type-guards';
import { revalidateTag } from 'next/cache';
import { headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import {
addToCartMutation,
createCartMutation,
@ -23,6 +26,7 @@ import {
Cart,
Collection,
Connection,
Image,
Menu,
Page,
Product,
@ -52,15 +56,17 @@ const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN!;
type ExtractVariables<T> = T extends { variables: object } ? T['variables'] : never;
export async function shopifyFetch<T>({
query,
variables,
cache = 'force-cache',
headers,
cache = 'force-cache'
query,
tags,
variables
}: {
query: string;
variables?: ExtractVariables<T>;
headers?: HeadersInit;
cache?: RequestCache;
headers?: HeadersInit;
query: string;
tags?: string[];
variables?: ExtractVariables<T>;
}): Promise<{ status: number; body: T } | never> {
try {
const result = await fetch(endpoint, {
@ -75,7 +81,7 @@ export async function shopifyFetch<T>({
...(variables && { variables })
}),
cache,
next: { revalidate: 900 } // 15 minutes
...(tags && { next: { tags } })
});
const body = await result.json();
@ -149,6 +155,18 @@ const reshapeCollections = (collections: ShopifyCollection[]) => {
return reshapedCollections;
};
const reshapeImages = (images: Connection<Image>, productTitle: string) => {
const flattened = removeEdgesAndNodes(images);
return flattened.map((image) => {
const filename = image.url.match(/.*\/(.*)\..*/)[1];
return {
...image,
altText: image.altText || `${productTitle} - ${filename}`
};
});
};
const reshapeProduct = (product: ShopifyProduct, filterHiddenProducts: boolean = true) => {
if (!product || (filterHiddenProducts && product.tags.includes(HIDDEN_PRODUCT_TAG))) {
return undefined;
@ -158,7 +176,7 @@ const reshapeProduct = (product: ShopifyProduct, filterHiddenProducts: boolean =
return {
...rest,
images: removeEdgesAndNodes(images),
images: reshapeImages(images, product.title),
variants: removeEdgesAndNodes(variants)
};
};
@ -232,15 +250,16 @@ export async function updateCart(
return reshapeCart(res.body.data.cartLinesUpdate.cart);
}
export async function getCart(cartId: string): Promise<Cart | null> {
export async function getCart(cartId: string): Promise<Cart | undefined> {
const res = await shopifyFetch<ShopifyCartOperation>({
query: getCartQuery,
variables: { cartId },
cache: 'no-store'
});
// Old carts becomes `null` when you checkout.
if (!res.body.data.cart) {
return null;
return undefined;
}
return reshapeCart(res.body.data.cart);
@ -249,6 +268,7 @@ export async function getCart(cartId: string): Promise<Cart | null> {
export async function getCollection(handle: string): Promise<Collection | undefined> {
const res = await shopifyFetch<ShopifyCollectionOperation>({
query: getCollectionQuery,
tags: [TAGS.collections],
variables: {
handle
}
@ -257,16 +277,27 @@ export async function getCollection(handle: string): Promise<Collection | undefi
return reshapeCollection(res.body.data.collection);
}
export async function getCollectionProducts(handle: string): Promise<Product[]> {
export async function getCollectionProducts({
collection,
reverse,
sortKey
}: {
collection: string;
reverse?: boolean;
sortKey?: string;
}): Promise<Product[]> {
const res = await shopifyFetch<ShopifyCollectionProductsOperation>({
query: getCollectionProductsQuery,
tags: [TAGS.collections, TAGS.products],
variables: {
handle
handle: collection,
reverse,
sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey
}
});
if (!res.body.data.collection) {
console.log('No collection found for handle', handle);
console.log(`No collection found for \`${collection}\``);
return [];
}
@ -274,7 +305,10 @@ export async function getCollectionProducts(handle: string): Promise<Product[]>
}
export async function getCollections(): Promise<Collection[]> {
const res = await shopifyFetch<ShopifyCollectionsOperation>({ query: getCollectionsQuery });
const res = await shopifyFetch<ShopifyCollectionsOperation>({
query: getCollectionsQuery,
tags: [TAGS.collections]
});
const shopifyCollections = removeEdgesAndNodes(res.body?.data?.collections);
const collections = [
{
@ -301,6 +335,7 @@ export async function getCollections(): Promise<Collection[]> {
export async function getMenu(handle: string): Promise<Menu[]> {
const res = await shopifyFetch<ShopifyMenuOperation>({
query: getMenuQuery,
tags: [TAGS.collections],
variables: {
handle
}
@ -334,6 +369,7 @@ export async function getPages(): Promise<Page[]> {
export async function getProduct(handle: string): Promise<Product | undefined> {
const res = await shopifyFetch<ShopifyProductOperation>({
query: getProductQuery,
tags: [TAGS.products],
variables: {
handle
}
@ -345,6 +381,7 @@ export async function getProduct(handle: string): Promise<Product | undefined> {
export async function getProductRecommendations(productId: string): Promise<Product[]> {
const res = await shopifyFetch<ShopifyProductRecommendationsOperation>({
query: getProductRecommendationsQuery,
tags: [TAGS.products],
variables: {
productId
}
@ -364,6 +401,7 @@ export async function getProducts({
}): Promise<Product[]> {
const res = await shopifyFetch<ShopifyProductsOperation>({
query: getProductsQuery,
tags: [TAGS.products],
variables: {
query,
reverse,
@ -373,3 +411,35 @@ export async function getProducts({
return reshapeProducts(removeEdgesAndNodes(res.body.data.products));
}
// This is called from `app/api/revalidate.ts` so providers can control revalidation logic.
export async function revalidate(req: NextRequest): Promise<NextResponse> {
// We always need to respond with a 200 status code to Shopify,
// otherwise it will continue to retry the request.
const collectionWebhooks = ['collections/create', 'collections/delete', 'collections/update'];
const productWebhooks = ['products/create', 'products/delete', 'products/update'];
const topic = headers().get('x-shopify-topic') || 'unknown';
const secret = req.nextUrl.searchParams.get('secret');
const isCollectionUpdate = collectionWebhooks.includes(topic);
const isProductUpdate = productWebhooks.includes(topic);
if (!secret || secret !== process.env.SHOPIFY_REVALIDATION_SECRET) {
console.error('Invalid revalidation secret.');
return NextResponse.json({ status: 200 });
}
if (!isCollectionUpdate && !isProductUpdate) {
// We don't need to revalidate anything for any other topics.
return NextResponse.json({ status: 200 });
}
if (isCollectionUpdate) {
revalidateTag(TAGS.collections);
}
if (isProductUpdate) {
revalidateTag(TAGS.products);
}
return NextResponse.json({ status: 200, revalidated: true, now: Date.now() });
}

View File

@ -37,9 +37,13 @@ export const getCollectionsQuery = /* GraphQL */ `
`;
export const getCollectionProductsQuery = /* GraphQL */ `
query getCollectionProducts($handle: String!) {
query getCollectionProducts(
$handle: String!
$sortKey: ProductCollectionSortKeys
$reverse: Boolean
) {
collection(handle: $handle) {
products(first: 100) {
products(sortKey: $sortKey, reverse: $reverse, first: 100) {
edges {
node {
...product

View File

@ -201,6 +201,8 @@ export type ShopifyCollectionProductsOperation = {
};
variables: {
handle: string;
reverse?: boolean;
sortKey?: string;
};
};

View File

@ -147,61 +147,6 @@ export interface Product {
locale?: string
}
export interface SearchProductsBody {
/**
* The search query string to filter the products by.
*/
search?: string
/**
* The category ID to filter the products by.
*/
categoryId?: string
/**
* The brand ID to filter the products by.
*/
brandId?: string
/**
* The sort key to sort the products by.
* @example 'trending-desc' | 'latest-desc' | 'price-asc' | 'price-desc'
*/
sort?: string
/**
* The locale code, used to localize the product data (if the provider supports it).
*/
locale?: string
}
/**
* Fetches a list of products based on the given search criteria.
*/
export type SearchProductsHook = {
data: {
/**
* List of products matching the query.
*/
products: Product[]
/**
* Indicates if there are any products matching the query.
*/
found: boolean
}
body: SearchProductsBody
input: SearchProductsBody
fetcherInput: SearchProductsBody
}
/**
* Product API schema
*/
export type ProductsSchema = {
endpoint: {
options: {}
handlers: {
getProducts: SearchProductsHook
}
}
}
/**
* Product operations

View File

@ -1,5 +1,9 @@
import { ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export const createUrl = (pathname: string, params: URLSearchParams) => {
const paramsString = params.toString();
@ -7,7 +11,3 @@ export const createUrl = (pathname: string, params: URLSearchParams) => {
return `${pathname}${queryString}`;
};
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@ -9,7 +9,8 @@
"titlePart": "Preview of:",
"exitPreviewLabel": "Exit Preview"
},
"copyright": "All rights reserved."
"copyright": "All rights reserved.",
"languageSelector": "Language selector"
},
"search": {
"search": "Search",
@ -38,7 +39,7 @@
"selectSize": "Select size"
},
"cart": {
"myCarttitle": "My cart",
"myCartTitle": "My cart",
"subTotal": "Subtotal",
"taxes": "Taxes",
"calculatedAtCheckout": "Calculated at checkout",
@ -61,7 +62,8 @@
"seo": {
"title": "My cart",
"description": "All products in my shopping cart are displayed here"
}
},
"openCart": "Open cart"
},
"checkout": {
"checkoutTitle": "Checkout",

View File

@ -9,7 +9,8 @@
"titlePart": "Förhandsvisning av:",
"exitPreviewLabel": "Avsluta förhandsvisning"
},
"copyright": "Alla rättigheter förbehållna."
"copyright": "Alla rättigheter förbehållna.",
"languageSelector": "Språkväljare"
},
"search": {
"search": "Sök",
@ -38,7 +39,7 @@
"selectSize": "Välj storlek"
},
"cart": {
"myCarttitle": "Min varukorg",
"myCartTitle": "Min varukorg",
"subTotal": "Delsumma",
"taxes": "Moms",
"calculatedAtCheckout": "Beräknas i kassan",
@ -60,7 +61,8 @@
"seo": {
"title": "Min varukorg",
"description": "Här visas alla produkter i min varukorg"
}
},
"openCart": "Öppna varukorg"
},
"checkout": {
"checkoutTitle": "Kassa",

View File

@ -6,7 +6,6 @@ export default createMiddleware({
// If this locale is matched, pathnames work without a prefix (e.g. `/about`)
defaultLocale: 'sv',
localeDetection: false
});
export const config = {

View File

@ -11,6 +11,7 @@ module.exports = withBundleAnalyzer(
},
experimental: {
scrollRestoration: true,
serverActions: true,
},
images: {
formats: ['image/avif', 'image/webp'],

View File

@ -19,14 +19,16 @@
"*": "prettier --write --ignore-unknown"
},
"dependencies": {
"@headlessui/react": "^1.7.14",
"@next/bundle-analyzer": "^13.4.3",
"@portabletext/react": "^3.0.0",
"@radix-ui/react-dialog": "^1.0.4",
"@radix-ui/react-dropdown-menu": "^2.0.4",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-navigation-menu": "^1.1.2",
"@sanity/client": "^6.4.4",
"@sanity/icons": "^2.3.1",
"@sanity/image-url": "^1.0.2",
"@sanity/preview-kit": "^2.4.9",
"@sanity/types": "^3.11.1",
"@sanity/ui": "^1.3.3",
"@sanity/webhook": "^2.0.0",
@ -36,9 +38,8 @@
"clsx": "^1.2.1",
"framer-motion": "^8.5.5",
"is-empty-iterable": "^3.0.0",
"lucide-react": "^0.194.0",
"next": "13.4.7",
"next-intl": "^2.14.6",
"next": "13.4.13",
"next-intl": "2.19.1",
"next-sanity": "^4.3.2",
"react": "18.2.0",
"react-cookie": "^4.1.1",
@ -55,8 +56,8 @@
"@tailwindcss/typography": "^0.5.9",
"@types/negotiator": "^0.6.1",
"@types/node": "18.13.0",
"@types/react": "18.0.27",
"@types/react-dom": "18.0.10",
"@types/react": "18.2.19",
"@types/react-dom": "18.2.7",
"@vercel/git-hooks": "^1.0.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.41.0",

657
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -41,6 +41,40 @@ module.exports = {
green: '#55b467',
red: '#ec5d40',
yellow: '#ffcb47',
// UI.SHADCN.COM
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
textColor: {
base: '#333333',
@ -52,18 +86,18 @@ module.exports = {
display: ['var(--font-inter-tight)', ...fontFamily.sans],
},
keyframes: {
'accordion-down': {
"accordion-down": {
from: { height: 0 },
to: { height: 'var(--radix-accordion-content-height)' },
to: { height: "var(--radix-accordion-content-height)" },
},
'accordion-up': {
from: { height: 'var(--radix-accordion-content-height)' },
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: 0 },
},
},
animation: {
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
@ -88,4 +122,4 @@ module.exports = {
future: {
hoverOnlyWhenSupported: true
},
}
}

View File

@ -20,8 +20,11 @@
{
"name": "next"
}
]
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
}