Tried to optimize product page

This commit is contained in:
Henrik Larsson 2023-08-11 10:19:55 +02:00
parent a7efbf8fc3
commit 767245672c
18 changed files with 190 additions and 263 deletions

View File

@ -53,6 +53,8 @@ interface PageParams {
} }
export default async function Page({ params }: PageParams) { export default async function Page({ params }: PageParams) {
console.log(params);
let queryParams = { let queryParams = {
locale: params.locale, locale: params.locale,
slug: '' slug: ''

View File

@ -34,36 +34,6 @@
--radius: 0.5rem; --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 { @layer base {

View File

@ -42,17 +42,19 @@ export default async function Header({ locale }: HeaderProps) {
</div> </div>
<div className="absolute left-1/2 top-1/2 hidden -translate-x-1/2 -translate-y-1/2 transform md:flex"> <div className="absolute left-1/2 top-1/2 hidden -translate-x-1/2 -translate-y-1/2 transform md:flex">
<ul className="flex gap-6"> <Suspense>
{mainMenu.map((item: { title: string; slug: string }, i: number) => { <ul className="flex gap-6">
return ( {mainMenu.map((item: { title: string; slug: string }, i: number) => {
<li key={i}> return (
<Link className="font-medium" href={`/category/${item.slug}`}> <li key={i}>
{item.title} <Link className="font-medium" href={`/category/${item.slug}`}>
</Link> {item.title}
</li> </Link>
); </li>
})} );
</ul> })}
</ul>
</Suspense>
</div> </div>
<div className="flex translate-x-2 transform justify-end space-x-1"> <div className="flex translate-x-2 transform justify-end space-x-1">
<Suspense fallback={<OpenSearch />}> <Suspense fallback={<OpenSearch />}>

View File

@ -8,7 +8,6 @@ interface HeroProps {
label?: string; label?: string;
title: string; title: string;
image: object | any; image: object | any;
desktopImage: object | any;
link: { link: {
title: string; title: string;
reference: { reference: {
@ -30,9 +29,11 @@ const heroSize = {
const Hero = ({ variant, title, text, label, image, link }: HeroProps) => { 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;
console.log(image);
return ( return (
<div <div
className={`relative w-screen ${heroClass} relative flex flex-col justify-end text-high-contrast`} className={`relative w-screen ${heroClass} relative flex flex-col justify-end bg-neutral-300 text-high-contrast`}
> >
{image && ( {image && (
<SanityImage <SanityImage

View File

@ -1,82 +0,0 @@
// @ts-nocheck
'use client';
import clsx from 'clsx';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState, useTransition } from 'react';
import LoadingDots from 'components/loading-dots';
import { ProductVariant } from 'lib/shopify/types';
export function AddToCart({
variants,
availableForSale
}: {
variants: ProductVariant[];
availableForSale: boolean;
}) {
const [selectedVariantId, setSelectedVariantId] = useState(variants[0]?.id);
const router = useRouter();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const [adding, setAdding] = useState(false);
useEffect(() => {
const variant = variants.find((variant: ProductVariant) =>
variant.selectedOptions.every(
(option) => option.value === searchParams.get(option.name.toLowerCase())
)
);
if (variant) {
setSelectedVariantId(variant.id);
}
}, [searchParams, variants, setSelectedVariantId]);
const isMutating = adding || isPending;
async function handleAdd() {
if (!availableForSale) return;
setAdding(true);
const response = await fetch(`/api/cart`, {
method: 'POST',
body: JSON.stringify({
merchandiseId: selectedVariantId
})
});
const data = await response.json();
if (data.error) {
alert(data.error);
return;
}
setAdding(false);
startTransition(() => {
router.refresh();
});
}
return (
<button
aria-label="Add item to cart"
disabled={isMutating}
onClick={handleAdd}
className={clsx(
'flex w-full items-center justify-center bg-black p-4 text-sm uppercase tracking-wide text-white opacity-90 hover:opacity-100 dark:bg-white dark:text-black',
{
'cursor-not-allowed opacity-60': !availableForSale,
'cursor-not-allowed': isMutating
}
)}
>
<span>{availableForSale ? 'Add To Cart' : 'Out Of Stock'}</span>
{isMutating ? <LoadingDots className="bg-white dark:bg-black" /> : null}
</button>
);
}

View File

@ -0,0 +1,67 @@
'use client';
import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline';
import { createUrl } from 'lib/utils';
import Image from 'next/image';
import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';
export function Gallery({ images }: { images: { src: string; alt: string }[] }) {
const pathname = usePathname();
const searchParams = useSearchParams();
const imageSearchParam = searchParams.get('image');
const imageIndex = imageSearchParam ? parseInt(imageSearchParam) : 0;
const nextSearchParams = new URLSearchParams(searchParams.toString());
const nextImageIndex = imageIndex + 1 < images.length ? imageIndex + 1 : 0;
nextSearchParams.set('image', nextImageIndex.toString());
const nextUrl = createUrl(pathname, nextSearchParams);
const previousSearchParams = new URLSearchParams(searchParams.toString());
const previousImageIndex = imageIndex === 0 ? images.length - 1 : imageIndex - 1;
previousSearchParams.set('image', previousImageIndex.toString());
const previousUrl = createUrl(pathname, previousSearchParams);
const buttonClassName =
'h-12 w-12 transition-all ease-in-out hover:scale-110 flex items-center justify-center';
return (
<>
<div className="relative aspect-square h-full w-full overflow-hidden">
{images[imageIndex] && (
<Image
className="h-full w-full object-cover"
fill
sizes="(min-width: 1024px) 66vw, 100vw"
alt={images[imageIndex]?.alt as string}
src={images[imageIndex]?.src as string}
priority={true}
/>
)}
{images.length > 1 ? (
<div className="absolute top-1/2 flex w-full px-1">
<div className="flex w-full justify-between">
<Link
aria-label="Previous product image"
href={previousUrl}
className={buttonClassName}
scroll={false}
>
<ArrowLeftIcon className="h-6" />
</Link>
<Link
aria-label="Next product image"
href={nextUrl}
className={buttonClassName}
scroll={false}
>
<ArrowRightIcon className="h-6" />
</Link>
</div>
</div>
) : null}
</div>
</>
);
}

View File

@ -0,0 +1,37 @@
import Image from 'next/image';
export function Grid({
images
}: {
images: { src: string; alt: string; width: number | undefined; height: number | undefined }[];
}) {
return (
<div className="grid grid-cols-2 gap-4">
{images.map(
(
image: {
src: string;
alt: string;
height: number | undefined;
width: number | undefined;
},
index: number
) => {
return (
<Image
className="aspect-square h-full w-full object-contain first:col-span-2"
src={image.src}
height={image.height}
width={image.width}
sizes={`${
index === 0 ? '(min-width: 1024px) 66vw, 100vw' : '(min-width: 1024px) 50vw, 0'
}`}
alt={image.alt}
key={index}
/>
);
}
)}
</div>
);
}

View File

@ -1,22 +1,23 @@
'use client'; 'use client';
import { Carousel, CarouselItem } from 'components/modules/carousel/carousel'; import { Product } from '@/lib/storm/product';
import SanityImage from 'components/ui/sanity-image/sanity-image'; import { Image } from '@/lib/storm/types';
import Text from 'components/ui/text/text'; import Text from 'components/ui/text/text';
import { Product } from 'lib/storm/types/product';
import { cn } from 'lib/utils'; import { cn } from 'lib/utils';
import { useTranslations } from 'next-intl'; import { useTranslations } from 'next-intl';
import { Suspense } from 'react'; import { Suspense } from 'react';
import ProductCard from '../ui/product-card/product-card'; import { Gallery } from './gallery';
import { Grid } from './grid';
import Price from './price'; import Price from './price';
interface ProductViewProps { interface ProductViewProps {
product: Product; product: Product;
relatedProducts: Product[]; relatedProducts: Product[];
} }
export default function ProductView({ product, relatedProducts }: ProductViewProps) { export default function ProductView({ product, relatedProducts }: ProductViewProps) {
const images = product.images;
const t = useTranslations('product'); const t = useTranslations('product');
const { name, description, price, images } = product;
return ( return (
<div className="mb-8 flex w-full flex-col lg:my-16"> <div className="mb-8 flex w-full flex-col lg:my-16">
@ -24,59 +25,50 @@ export default function ProductView({ product, relatedProducts }: ProductViewPro
className={cn('relative grid grid-cols-1 items-start lg:grid-cols-12 lg:px-8 2xl:px-16')} className={cn('relative grid grid-cols-1 items-start lg:grid-cols-12 lg:px-8 2xl:px-16')}
> >
<div className="relative col-span-1 lg:col-span-7"> <div className="relative col-span-1 lg:col-span-7">
<div className={`pdp aspect-square lg:hidden`}> <div className="lg:hidden">
{images && ( <Gallery
<Carousel images={images.map((image: Image) => ({
hasArrows={images.length > 1 ? true : false} src: image.url,
hasDots={false} alt: image.alt
gliderClasses={'lg:px-8 2xl:px-16'} }))}
slidesToScroll={1} />
slidesToShow={images.length > 1 ? 1.0125 : 1}
responsive={{
breakpoint: 1024,
settings: {
slidesToShow: 1
}
}}
>
{images.map((image: any, index: number) => (
<CarouselItem className="ml-1 first:ml-0" key={`${index}`}>
<SanityImage
image={image}
alt={image.alt}
priority={true}
quality={85}
sizes="(max-width: 1024px) 100vw, 70vw"
/>
</CarouselItem>
))}
</Carousel>
)}
</div> </div>
<div className="hidden grid-cols-2 gap-4 lg:grid"> <div className="hidden lg:flex">
{images.map((image: any, index: number) => ( <Grid
images={images.map((image: Image) => ({
src: image.url,
alt: image.alt,
height: image.height,
width: image.width
}))}
/>
{/* {images.map((image: Image, index: number) => (
<div key={index} className="first:col-span-2"> <div key={index} className="first:col-span-2">
<SanityImage <SanityImage
image={image} image={image}
alt={image.alt} alt={image.alt}
priority={true} priority={index === 0 ? true : false}
quality={85}
sizes="(max-width: 1024px) 100vw, 70vw" sizes="(max-width: 1024px) 100vw, 70vw"
/> />
</div> </div>
))} ))} */}
</div> </div>
</div> </div>
<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"> <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> <Text variant={'productHeading'}>{name}</Text>
<Price <Price
className="mt-2 text-sm font-medium leading-tight lg:text-base" className="mt-2 text-sm font-bold leading-tight lg:text-base"
amount={`${product.price.value}`} amount={`${price.value}`}
currencyCode={product.price.currencyCode ? product.price.currencyCode : 'SEK'} currencyCode={price.currencyCode ? price.currencyCode : 'SEK'}
/> />
<Text className="mt-2" variant="paragraph">
{description}
</Text>
</div> </div>
</div> </div>
@ -86,26 +78,6 @@ export default function ProductView({ product, relatedProducts }: ProductViewPro
<Text className="px-4 lg:px-8 2xl:px-16" variant="sectionHeading"> <Text className="px-4 lg:px-8 2xl:px-16" variant="sectionHeading">
{t('related')} {t('related')}
</Text> </Text>
<Carousel
gliderClasses={'px-4 lg:px-8 2xl:px-16'}
hasArrows={true}
hasDots={true}
slidesToShow={2.2}
slidesToScroll={1}
responsive={{
breakpoint: 1024,
settings: {
slidesToShow: 4.5
}
}}
>
{relatedProducts.map((p) => (
<CarouselItem key={`product-${p.path}`}>
<ProductCard product={p} />
</CarouselItem>
))}
</Carousel>
</section> </section>
</Suspense> </Suspense>
)} )}

View File

@ -24,7 +24,7 @@ export default function Search() {
); );
} }
return ( return (
<div className="flex flex-col overflow-auto"> <div className="flex flex-col">
<InstantSearch searchClient={searchClient} indexName="shopify_products"> <InstantSearch searchClient={searchClient} indexName="shopify_products">
{/* Widgets */} {/* Widgets */}
<SearchBox <SearchBox
@ -42,7 +42,7 @@ export default function Search() {
<Hits <Hits
classNames={{ classNames={{
root: 'flex flex-col mt-4', root: 'flex flex-col mt-4',
list: 'grid grid-cols-1 gap-4' list: 'grid grid-cols-1 gap-4 overflow-auto'
}} }}
hitComponent={Hit} hitComponent={Hit}
/> />

View File

@ -1,9 +1,9 @@
'use client'; 'use client';
import SanityImage from '@/components/ui/sanity-image/sanity-image'; import SanityImage from '@/components/ui/sanity-image/sanity-image';
import type { Product } from '@/lib/storm/product';
import Price from 'components/product/price'; import Price from 'components/product/price';
import Text from 'components/ui/text'; import Text from 'components/ui/text';
import type { Product } from 'lib/storm/types/product';
import { cn } from 'lib/utils'; import { cn } from 'lib/utils';
import Link from 'next/link'; import Link from 'next/link';
import { FC } from 'react'; import { FC } from 'react';

View File

@ -24,7 +24,7 @@ const SheetOverlay = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay <SheetPrimitive.Overlay
className={cn( 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', 'fixed inset-0 z-50 bg-foreground/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className className
)} )}
{...props} {...props}

View File

@ -71,7 +71,7 @@ const Text: FunctionComponent<TextProps> = ({
variant === 'sectionHeading', variant === 'sectionHeading',
['text-sm leading-tight lg:text-base']: variant === 'listChildHeading', ['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 text-lg text-high-contrast lg:text-xl']: variant === 'label',
['max-w-prose lg:text-lg 2xl:text-xl']: variant === 'paragraph' ['max-w-prose']: variant === 'paragraph'
}, },
className className
)} )}

View File

@ -1,17 +1,17 @@
export const docQuery = `*[_type in ["home", "page", "category", "product"] && defined(slug.current)] {
_type,
"slug": slug.current,
"locale": language
}`;
export const imageFields = ` export const imageFields = `
alt, alt,
crop, crop,
hotspot, hotspot,
"url": asset->url,
"width": asset->metadata.dimensions.width,
"height": asset->metadata.dimensions.height,
asset-> { asset-> {
..., _id,
assetId,
metadata,
_type, _type,
_ref, _ref,
_rev
} }
`; `;

View File

@ -1,4 +1,4 @@
import { Image } from './common' import { Image } from './types'
export interface ProductPrice { export interface ProductPrice {
/** /**
@ -146,27 +146,3 @@ export interface Product {
*/ */
locale?: string locale?: string
} }
/**
* Product operations
*/
export type GetAllProductPathsOperation = {
data: { products: Pick<Product, 'path'>[] }
variables: { first?: number }
}
export type GetAllProductsOperation = {
data: { products: Product[] }
variables: {
relevance?: 'featured' | 'best_selling' | 'newest'
ids?: string[]
first?: number
}
}
export type GetProductOperation = {
data: { product?: Product }
variables: { path: string; slug?: never } | { path?: never; slug: string }
}

18
lib/storm/types.ts Normal file
View File

@ -0,0 +1,18 @@
export type Image = {
/**
* The URL of the image.
*/
url: string
/**
* A word or phrase that describes the content of an image.
*/
alt: string
/**
* The image's width.
*/
width?: number
/**
* The image's height.
*/
height?: number
};

View File

@ -1,36 +0,0 @@
export interface Discount {
/**
* The value of the discount, can be an amount or percentage.
*/
value: number
}
export interface Measurement {
/**
* The measurement's value.
*/
value: number
/**
* The measurement's unit, such as "KILOGRAMS", "GRAMS", "POUNDS" & "OOUNCES".
*/
unit: 'KILOGRAMS' | 'GRAMS' | 'POUNDS' | 'OUNCES'
}
export interface Image {
/**
* The URL of the image.
*/
url: string
/**
* A word or phrase that describes the content of an image.
*/
alt?: string
/**
* The image's width.
*/
width?: number
/**
* The image's height.
*/
height?: number
}

View File

@ -10,7 +10,7 @@
"prettier:check": "prettier --check --ignore-unknown .", "prettier:check": "prettier --check --ignore-unknown .",
"test": "pnpm lint && pnpm prettier:check", "test": "pnpm lint && pnpm prettier:check",
"test:e2e": "playwright test", "test:e2e": "playwright test",
"analyze": "BUNDLE_ANALYZE=true next build" "analyze": "cross-env BUNDLE_ANALYZE=true pnpm build"
}, },
"git": { "git": {
"pre-commit": "lint-staged" "pre-commit": "lint-staged"