fix: Use next-intl for improved locale support

This commit is contained in:
Sol Irvine
2023-08-17 11:56:36 +09:00
parent 32bb4ffd0c
commit c1d06e90bb
42 changed files with 237 additions and 212 deletions

View File

@@ -0,0 +1,15 @@
import Footer from 'components/layout/footer';
import { Suspense } from 'react';
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<Suspense>
<div className="w-full">
<div className="mx-8 max-w-2xl py-20 sm:mx-auto">
<Suspense>{children}</Suspense>
</div>
</div>
<Footer />
</Suspense>
);
}

View File

@@ -0,0 +1,11 @@
import OpengraphImage from 'components/opengraph-image';
import { getPage } from 'lib/shopify';
export const runtime = 'edge';
export default async function Image({ params }: { params: { page: string } }) {
const page = await getPage({ handle: params.page });
const title = page.seo?.title || page.title;
return await OpengraphImage({ title });
}

View File

@@ -0,0 +1,49 @@
import type { Metadata } from 'next';
import Prose from 'components/prose';
import { getPage } from 'lib/shopify';
import { notFound } from 'next/navigation';
export const runtime = 'edge';
export const revalidate = 43200; // 12 hours in seconds
export async function generateMetadata({
params
}: {
params: { page: string };
}): Promise<Metadata> {
const page = await getPage({ handle: params.page });
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'
}
};
}
export default async function Page({ params }: { params: { page: string } }) {
const page = await getPage({ handle: params.page });
if (!page) return notFound();
return (
<>
<h1 className="mb-8 text-5xl font-bold">{page.title}</h1>
<Prose className="mb-8" html={page.body as string} />
<p className="text-sm italic">
{`This document was last updated on ${new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(new Date(page.updatedAt))}.`}
</p>
</>
);
}

19
app/[locale]/error.tsx Normal file
View File

@@ -0,0 +1,19 @@
'use client';
export default function Error({ reset }: { reset: () => void }) {
return (
<div className="mx-auto my-4 flex max-w-xl flex-col rounded-lg border border-neutral-200 bg-white p-8 dark:border-neutral-800 dark:bg-black md:p-12">
<h2 className="text-xl font-bold">Oh no!</h2>
<p className="my-2">
There was an issue with our storefront. This could be a temporary issue, please try your
action again.
</p>
<button
className="mx-auto mt-4 flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white hover:opacity-90"
onClick={() => reset()}
>
Try Again
</button>
</div>
);
}

29
app/[locale]/globals.css Normal file
View File

@@ -0,0 +1,29 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
}
@supports (font: -apple-system-body) and (-webkit-appearance: none) {
img[loading='lazy'] {
clip-path: inset(0.6px);
}
}
a,
input,
button {
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-50 dark:focus-visible:ring-neutral-600 dark:focus-visible:ring-offset-neutral-900;
}
.font-multilingual {
@apply font-serif;
}
[lang='ja'] .font-multilingual {
@apply font-japan;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 MiB

104
app/[locale]/layout.tsx Normal file
View File

@@ -0,0 +1,104 @@
import Navbar from 'components/layout/navbar';
import { Locale } from 'i18n-config';
import { Noto_Sans_JP } from 'next/font/google';
import localFont from 'next/font/local';
import { ReactNode, Suspense } from 'react';
import { NextIntlClientProvider } from 'next-intl';
import { notFound } from 'next/navigation';
import './globals.css';
const { TWITTER_CREATOR, TWITTER_SITE, SITE_NAME } = process.env;
const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
: 'http://localhost:3000';
export const metadata = {
metadataBase: new URL(baseUrl),
title: {
default: SITE_NAME!,
template: `%s | ${SITE_NAME}`
},
robots: {
follow: true,
index: true
},
...(TWITTER_CREATOR &&
TWITTER_SITE && {
twitter: {
card: 'summary_large_image',
creator: TWITTER_CREATOR,
site: TWITTER_SITE
}
})
};
// Font files can be colocated inside of `app`
const cinzel = localFont({
src: '../fonts/Cinzel-Regular.ttf',
display: 'swap',
variable: '--font-cinzel'
});
const alpina = localFont({
src: [
{
path: '../fonts/GT-Alpina-Regular-Trial.woff2',
weight: '400',
style: 'normal'
},
{
path: '../fonts/GT-Alpina-Bold-Trial.woff2',
weight: '700',
style: 'normal'
}
],
variable: '--font-alpina'
});
const noto = Noto_Sans_JP({
subsets: ['latin'],
display: 'swap',
weight: ['300', '600'],
variable: '--font-noto'
});
const mincho = localFont({
src: '../fonts/A-OTF-A1MinchoStd-Bold.otf',
display: 'swap',
variable: '--font-mincho'
});
export function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'ja' }];
}
export default async function RootLayout({
children,
params
}: {
children: ReactNode;
params: { locale: Locale };
}) {
let messages;
try {
messages = (await import(`../../messages/${params?.locale}.json`)).default;
} catch (error) {
notFound();
}
return (
<html lang={params.locale} className={`${cinzel.variable} ${alpina.variable} ${noto.variable}`}>
<body className="bg-dark text-white selection:bg-green-800 selection:text-green-400">
<div className="mx-auto max-w-screen-2xl">
<NextIntlClientProvider locale={params?.locale} messages={messages}>
<Navbar />
<Suspense>
<main>{children}</main>
</Suspense>
</NextIntlClientProvider>
</div>
</body>
</html>
);
}

View File

@@ -0,0 +1,7 @@
import OpengraphImage from 'components/opengraph-image';
export const runtime = 'edge';
export default async function Image() {
return await OpengraphImage();
}

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

@@ -0,0 +1,60 @@
import { Carousel } from 'components/carousel';
import { ThreeItemGrid } from 'components/grid/three-items';
import Footer from 'components/layout/footer';
import { LanguageControl, SupportedLocales } from 'components/layout/navbar/language-control';
import clsx from 'clsx';
import LogoNamemark from 'components/icons/namemark';
import NewsletterSignup from 'components/layout/newsletter-signup';
import Shoplist from 'components/layout/shoplist';
import Image from 'next/image';
import { Suspense } from 'react';
import HomeImage001 from './images/home-image-001.webp';
export const runtime = 'edge';
const { SITE_NAME } = process.env;
export const metadata = {
title: SITE_NAME,
description: SITE_NAME,
openGraph: {
type: 'website'
}
};
export default async function HomePage({
params: { locale }
}: {
params: { locale: SupportedLocales };
}) {
return (
<>
<div className="invisible absolute right-40 top-12 md:visible">
<LanguageControl lang={locale} />
</div>
<div className="px-6 pb-12 pt-6 md:pb-48 md:pl-6 md:pt-12">
<LogoNamemark className="w-[260px] fill-current md:w-[600px]" />
</div>
<ThreeItemGrid lang={locale} />
<div className="py-48">
<NewsletterSignup />
</div>
<div className="relative max-w-screen-2xl">
<Image
src={HomeImage001}
alt="A picture of Narai Black bottle in a mossy creek."
className={clsx('h-full w-full object-cover')}
/>
</div>
<div className="py-24">
<Shoplist />
</div>
<Suspense>
<Carousel />
<Suspense>
<Footer />
</Suspense>
</Suspense>
</>
);
}

View File

@@ -0,0 +1,142 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { Suspense } from 'react';
import { GridTileImage } from 'components/grid/tile';
import Footer from 'components/layout/footer';
import { Gallery } from 'components/product/gallery';
import { ProductDescription } from 'components/product/product-description';
import { HIDDEN_PRODUCT_TAG } from 'lib/constants';
import { getProduct, getProductRecommendations } from 'lib/shopify';
import { Image } from 'lib/shopify/types';
import Link from 'next/link';
export const runtime = 'edge';
export async function generateMetadata({
params
}: {
params: { handle: string };
}): Promise<Metadata> {
const product = await getProduct({ handle: params.handle });
if (!product) return notFound();
const { url, width, height, altText: alt } = product.featuredImage || {};
const indexable = !product.tags.includes(HIDDEN_PRODUCT_TAG);
return {
title: product.seo.title || product.title,
description: product.seo.description || product.description,
robots: {
index: indexable,
follow: indexable,
googleBot: {
index: indexable,
follow: indexable
}
},
openGraph: url
? {
images: [
{
url,
width,
height,
alt
}
]
}
: null
};
}
export default async function ProductPage({ params }: { params: { handle: string } }) {
const product = await getProduct({ handle: params.handle });
if (!product) return notFound();
const productJsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.title,
description: product.description,
image: product.featuredImage.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)
}}
/>
<div className="mx-auto max-w-screen-2xl px-4">
<div className="flex flex-col rounded-lg border border-neutral-200 bg-white p-8 dark:border-neutral-800 dark:bg-black md:p-12 lg:flex-row">
<div className="h-full w-full basis-full lg:basis-4/6">
<Gallery
images={product.images.map((image: Image) => ({
src: image.url,
altText: image.altText
}))}
/>
</div>
<div className="basis-full lg:basis-2/6">
<ProductDescription product={product} />
</div>
</div>
<Suspense>
<RelatedProducts id={product.id} />
</Suspense>
</div>
<Suspense>
<Footer />
</Suspense>
</>
);
}
async function RelatedProducts({ id }: { id: string }) {
const relatedProducts = await getProductRecommendations({ productId: id });
if (!relatedProducts.length) return null;
return (
<div className="py-8">
<h2 className="mb-4 text-2xl font-bold">Related Products</h2>
<ul className="flex w-full gap-4 overflow-x-auto pt-1">
{relatedProducts.map((product) => (
<li
key={product.handle}
className="aspect-square w-full flex-none min-[475px]:w-1/2 sm:w-1/3 md:w-1/4 lg:w-1/5"
>
<Link className="relative h-full w-full" href={`/product/${product.handle}`}>
<GridTileImage
alt={product.title}
label={{
title: product.title,
amount: product.priceRange.maxVariantPrice.amount,
currencyCode: product.priceRange.maxVariantPrice.currencyCode
}}
src={product.featuredImage?.url}
fill
sizes="(min-width: 1024px) 20vw, (min-width: 768px) 25vw, (min-width: 640px) 33vw, (min-width: 475px) 50vw, 100vw"
/>
</Link>
</li>
))}
</ul>
</div>
);
}

15
app/[locale]/robots.ts Normal file
View File

@@ -0,0 +1,15 @@
const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
: 'http://localhost:3000';
export default function robots() {
return {
rules: [
{
userAgent: '*'
}
],
sitemap: `${baseUrl}/sitemap.xml`,
host: baseUrl
};
}

View File

@@ -0,0 +1,11 @@
import OpengraphImage from 'components/opengraph-image';
import { getCollection } from 'lib/shopify';
export const runtime = 'edge';
export default async function Image({ params }: { params: { collection: string } }) {
const collection = await getCollection({ handle: params.collection });
const title = collection?.seo?.title || collection?.title;
return await OpengraphImage({ title });
}

View File

@@ -0,0 +1,49 @@
import { getCollection, getCollectionProducts } from 'lib/shopify';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Grid from 'components/grid';
import ProductGridItems from 'components/layout/product-grid-items';
import { defaultSort, sorting } from 'lib/constants';
export const runtime = 'edge';
export async function generateMetadata({
params
}: {
params: { collection: string };
}): Promise<Metadata> {
const collection = await getCollection({ handle: params.collection });
if (!collection) return notFound();
return {
title: collection.seo?.title || collection.title,
description:
collection.seo?.description || collection.description || `${collection.title} products`
};
}
export default async function CategoryPage({
params,
searchParams
}: {
params: { collection: string };
searchParams?: { [key: string]: string | string[] | undefined };
}) {
const { sort } = searchParams as { [key: string]: string };
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
const products = await getCollectionProducts({ collection: params.collection, sortKey, reverse });
return (
<section>
{products.length === 0 ? (
<p className="py-3 text-lg">{`No products found in this collection`}</p>
) : (
<Grid className="grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
<ProductGridItems products={products} />
</Grid>
)}
</section>
);
}

View File

@@ -0,0 +1,22 @@
import Footer from 'components/layout/footer';
import Collections from 'components/layout/search/collections';
import FilterList from 'components/layout/search/filter';
import { sorting } from 'lib/constants';
import { Suspense } from 'react';
export default function SearchLayout({ children }: { children: React.ReactNode }) {
return (
<Suspense>
<div className="mx-auto flex max-w-screen-2xl flex-col gap-8 px-4 pb-4 text-black dark:text-white md:flex-row">
<div className="order-first w-full flex-none md:max-w-[125px]">
<Collections />
</div>
<div className="order-last min-h-screen w-full md:order-none">{children}</div>
<div className="order-none flex-none md:order-last md:w-[125px]">
<FilterList list={sorting} title="Sort by" />
</div>
</div>
<Footer />
</Suspense>
);
}

View File

@@ -0,0 +1,15 @@
import Grid from 'components/grid';
export default function Loading() {
return (
<Grid className="grid-cols-2 lg:grid-cols-3">
{Array(12)
.fill(0)
.map((_, index) => {
return (
<Grid.Item key={index} className="animate-pulse bg-neutral-100 dark:bg-neutral-900" />
);
})}
</Grid>
);
}

View File

@@ -0,0 +1,41 @@
import Grid from 'components/grid';
import ProductGridItems from 'components/layout/product-grid-items';
import { defaultSort, sorting } from 'lib/constants';
import { getProducts } from 'lib/shopify';
export const runtime = 'edge';
export const metadata = {
title: 'Search',
description: 'Search for products in the store.'
};
export default async function SearchPage({
searchParams
}: {
searchParams?: { [key: string]: string | string[] | undefined };
}) {
const { sort, q: searchValue } = searchParams as { [key: string]: string };
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
const products = await getProducts({ sortKey, reverse, query: searchValue });
const resultsText = products.length > 1 ? 'results' : 'result';
return (
<>
{searchValue ? (
<p className="mb-4">
{products.length === 0
? 'There are no products that match '
: `Showing ${products.length} ${resultsText} for `}
<span className="font-bold">&quot;{searchValue}&quot;</span>
</p>
) : null}
{products.length > 0 ? (
<Grid className="grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
<ProductGridItems products={products} />
</Grid>
) : null}
</>
);
}

49
app/[locale]/sitemap.ts Normal file
View File

@@ -0,0 +1,49 @@
import { getCollections, getPages, getProducts } from 'lib/shopify';
import { MetadataRoute } from 'next';
type Route = {
url: string;
lastModified: string;
};
const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
: 'http://localhost:3000';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const routesMap = [''].map((route) => ({
url: `${baseUrl}${route}`,
lastModified: new Date().toISOString()
}));
const collectionsPromise = getCollections().then((collections) =>
collections.map((collection) => ({
url: `${baseUrl}${collection.path}`,
lastModified: collection.updatedAt
}))
);
const productsPromise = getProducts({}).then((products) =>
products.map((product) => ({
url: `${baseUrl}/product/${product.handle}`,
lastModified: product.updatedAt
}))
);
const pagesPromise = getPages({}).then((pages) =>
pages.map((page) => ({
url: `${baseUrl}/${page.handle}`,
lastModified: page.updatedAt
}))
);
let fetchedRoutes: Route[] = [];
try {
fetchedRoutes = (await Promise.all([collectionsPromise, productsPromise, pagesPromise])).flat();
} catch (error) {
throw JSON.stringify(error, null, 2);
}
return [...routesMap, ...fetchedRoutes];
}