feat: Basic internationalization

This commit is contained in:
Sol Irvine 2023-08-14 02:27:52 +09:00
parent 7a4a7cf4ed
commit 4c8abdfe6f
24 changed files with 202 additions and 55 deletions

View File

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

View File

@ -13,7 +13,7 @@ export async function generateMetadata({
}: {
params: { page: string };
}): Promise<Metadata> {
const page = await getPage(params.page);
const page = await getPage({ handle: params.page });
if (!page) return notFound();
@ -29,7 +29,7 @@ export async function generateMetadata({
}
export default async function Page({ params }: { params: { page: string } }) {
const page = await getPage(params.page);
const page = await getPage({ handle: params.page });
if (!page) return notFound();

View File

@ -19,3 +19,11 @@ 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;
}

View File

@ -3,6 +3,7 @@ import { Locale, i18n } from 'i18n-config';
import localFont from 'next/font/local';
import { ReactNode, Suspense } from 'react';
import { LanguageProvider } from 'app/context/language-context';
import './globals.css';
const { TWITTER_CREATOR, TWITTER_SITE, SITE_NAME } = process.env;
@ -37,6 +38,12 @@ const cinzel = localFont({
variable: '--font-cinzel'
});
const mincho = localFont({
src: '../fonts/A-OTF-A1MinchoStd-Bold.otf',
display: 'swap',
variable: '--font-cinzel'
});
const alpina = localFont({
src: [
{
@ -65,13 +72,15 @@ export default async function RootLayout({
params: { lang: string };
}) {
return (
<html lang={params.lang} className={`${cinzel.variable} ${alpina.variable}`}>
<html lang={params.lang} className={`${cinzel.variable} ${alpina.variable} ${mincho.variable}`}>
<body className="bg-dark text-white selection:bg-green-800 selection:text-green-400">
<div className="mx-auto max-w-screen-2xl">
<Navbar lang={params.lang as Locale} />
<Suspense>
<main>{children}</main>
</Suspense>
<LanguageProvider language={params.lang as Locale}>
<Navbar />
<Suspense>
<main>{children}</main>
</Suspense>
</LanguageProvider>
</div>
</body>
</html>

View File

@ -32,7 +32,7 @@ export default async function HomePage({ params: { lang } }: { params: { lang: L
className="max-w-[260px] md:max-w-[600px]"
/>
</div>
<ThreeItemGrid />
<ThreeItemGrid lang={lang} />
<Suspense>
<Carousel />
<Suspense>

View File

@ -18,7 +18,7 @@ export async function generateMetadata({
}: {
params: { handle: string };
}): Promise<Metadata> {
const product = await getProduct(params.handle);
const product = await getProduct({ handle: params.handle });
if (!product) return notFound();
@ -52,7 +52,7 @@ export async function generateMetadata({
}
export default async function ProductPage({ params }: { params: { handle: string } }) {
const product = await getProduct(params.handle);
const product = await getProduct({ handle: params.handle });
if (!product) return notFound();
@ -108,7 +108,7 @@ export default async function ProductPage({ params }: { params: { handle: string
}
async function RelatedProducts({ id }: { id: string }) {
const relatedProducts = await getProductRecommendations(id);
const relatedProducts = await getProductRecommendations({ productId: id });
if (!relatedProducts.length) return null;

View File

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

View File

@ -13,7 +13,7 @@ export async function generateMetadata({
}: {
params: { collection: string };
}): Promise<Metadata> {
const collection = await getCollection(params.collection);
const collection = await getCollection({ handle: params.collection });
if (!collection) return notFound();

View File

@ -30,7 +30,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
}))
);
const pagesPromise = getPages().then((pages) =>
const pagesPromise = getPages({}).then((pages) =>
pages.map((page) => ({
url: `${baseUrl}/${page.handle}`,
lastModified: page.updatedAt

View File

@ -0,0 +1,36 @@
'use client';
import { Locale } from 'i18n-config';
import { ReactNode, createContext, useContext, useState } from 'react';
interface IContextProps {
currentLanguage?: Locale;
setCurrentLanguage: (language: Locale) => void;
}
export const LanguageContext = createContext<IContextProps>({} as IContextProps);
export function LanguageProvider({
language,
children
}: {
language: Locale;
children: ReactNode | ReactNode[] | string;
}) {
const [currentLanguage, setCurrentLanguage] = useState<Locale>(language || 'en');
return (
<LanguageContext.Provider
value={{
currentLanguage,
setCurrentLanguage
}}
>
{children}
</LanguageContext.Provider>
);
}
export const useLanguage = () => {
return useContext(LanguageContext);
};

Binary file not shown.

View File

@ -1,5 +1,6 @@
import clsx from 'clsx';
import { GridTileImage } from 'components/grid/tile';
import { Locale } from 'i18n-config';
import { getCollectionProducts } from 'lib/shopify';
import type { Product } from 'lib/shopify/types';
import Link from 'next/link';
@ -14,7 +15,10 @@ function ThreeItemGridItem({ item, priority }: { item: Product; priority?: boole
>
<GridTileImage
src={item.featuredImage.url}
fill
height={1690}
width={1192}
layout="responsive"
// fill
sizes={'(min-width: 768px) 33vw, 100vw'}
priority={priority}
alt={item.title}
@ -26,17 +30,21 @@ function ThreeItemGridItem({ item, priority }: { item: Product; priority?: boole
amount={item.priceRange.maxVariantPrice.amount}
currencyCode={item.priceRange.maxVariantPrice.currencyCode}
/>
<div className="line-clamp-4">{item?.description}</div>
</div>
</div>
);
}
export async function ThreeItemGrid() {
export async function ThreeItemGrid({ lang }: { lang: Locale }) {
// Collections that start with `hidden-*` are hidden from the search page.
const homepageItems = await getCollectionProducts({
collection: 'hidden-homepage-featured-items'
collection: 'hidden-homepage-featured-items',
language: lang.toUpperCase()
});
console.debug({ homepageItems });
if (!homepageItems[0] || !homepageItems[1] || !homepageItems[2]) return null;
const [firstProduct, secondProduct, thirdProduct] = homepageItems;

View File

@ -16,7 +16,7 @@ export function GridTileImage({
};
} & React.ComponentProps<typeof Image>) {
return (
<div className="flex flex-col space-y-2">
<>
{props.src ? (
// eslint-disable-next-line jsx-a11y/alt-text -- `alt` is inherited from `props`, which is being enforced with TypeScript
<Image
@ -26,6 +26,6 @@ export function GridTileImage({
{...props}
/>
) : null}
</div>
</>
);
}

View File

@ -12,7 +12,7 @@ const Label = ({
}) => {
return (
<div className={clsx('@container/label')}>
<div className="flex flex-col space-y-2">
<div className="font-multilingual flex flex-col space-y-2">
<h3 className="mr-4 line-clamp-2 flex-grow text-3xl">{title}</h3>
<Price
className="flex-none"

View File

@ -1,14 +1,15 @@
'use client';
import { Dialog, Transition } from '@headlessui/react';
import { useLanguage } from 'app/context/language-context';
import CloseIcon from 'components/icons/close';
import MenuIcon from 'components/icons/menu';
import type { Locale } from 'i18n-config';
import Link from 'next/link';
import { Fragment, useRef, useState } from 'react';
import { LanguageControl } from '../navbar/language-control';
export function MenuModal({ lang }: { lang: Locale }) {
export function MenuModal() {
const { currentLanguage } = useLanguage();
let [isOpen, setIsOpen] = useState(false);
let closeButtonRef = useRef(null);
@ -45,7 +46,7 @@ export function MenuModal({ lang }: { lang: Locale }) {
<Transition.Child as={Fragment}>
<div className="fixed right-5 top-6 z-40 px-2 py-1 md:top-11">
<div className="flex flex-row space-x-4">
<LanguageControl lang={lang} />
<LanguageControl lang={currentLanguage} />
<button ref={closeButtonRef} onClick={close} className="">
<CloseIcon className="h-10 w-10 stroke-current transition-opacity duration-150 hover:opacity-50" />

View File

@ -1,17 +1,16 @@
import Cart from 'components/cart';
import OpenCart from 'components/cart/open-cart';
import type { Locale } from 'i18n-config';
import { Suspense } from 'react';
import { MenuModal } from '../menu/modal';
export default async function Navbar({ lang }: { lang: Locale }) {
export default async function Navbar() {
return (
<nav className="fixed right-0 top-6 z-10 md:top-12">
<div className="flex justify-end pr-5">
<Suspense fallback={<OpenCart />}>
<div className="flex flex-col-reverse items-center justify-center space-y-2 rounded bg-dark/40 px-2 backdrop-blur-sm md:flex-row md:space-x-6">
<Cart />
<MenuModal lang={lang} />
<MenuModal />
</div>
</Suspense>
</div>

View File

@ -7,7 +7,6 @@ import { usePathname } from 'next/navigation';
export const LanguageControl = ({ lang }: { lang?: Locale }) => {
const pathName = usePathname();
console.debug({ lang });
const redirectedPathName = (locale: string) => {
if (!pathName) return '/';
const segments = pathName.split('/');
@ -21,7 +20,7 @@ export const LanguageControl = ({ lang }: { lang?: Locale }) => {
<Link
href={redirectedPathName('ja')}
className={clsx(
lang === 'ja' && 'opacity-70',
lang === 'ja' ? 'opacity-100' : 'opacity-70',
'transition-opacity duration-150 hover:opacity-50'
)}
>
@ -33,7 +32,7 @@ export const LanguageControl = ({ lang }: { lang?: Locale }) => {
<Link
href={redirectedPathName('en')}
className={clsx(
lang === 'en' && 'opacity-70',
lang === 'en' ? 'opacity-100' : 'opacity-70',
'transition-opacity duration-150 hover:opacity-50'
)}
>

View File

@ -17,7 +17,9 @@ const Price = ({
currency: currencyCode,
currencyDisplay: 'narrowSymbol'
}).format(parseFloat(amount))}`}
<span className={clsx('ml-1 inline', currencyCodeClassName)}>{`${currencyCode}`}</span>
<span
className={clsx('font-multilingual ml-1 inline', currencyCodeClassName)}
>{`${currencyCode}`}</span>
</p>
);

View File

@ -265,12 +265,22 @@ export async function getCart(cartId: string): Promise<Cart | undefined> {
return reshapeCart(res.body.data.cart);
}
export async function getCollection(handle: string): Promise<Collection | undefined> {
export async function getCollection({
handle,
language,
country
}: {
handle: string;
language?: string;
country?: string;
}): Promise<Collection | undefined> {
const res = await shopifyFetch<ShopifyCollectionOperation>({
query: getCollectionQuery,
tags: [TAGS.collections],
variables: {
handle
handle,
language,
country
}
});
@ -280,11 +290,15 @@ export async function getCollection(handle: string): Promise<Collection | undefi
export async function getCollectionProducts({
collection,
reverse,
sortKey
sortKey,
language,
country
}: {
collection: string;
reverse?: boolean;
sortKey?: string;
language?: string;
country?: string;
}): Promise<Product[]> {
const res = await shopifyFetch<ShopifyCollectionProductsOperation>({
query: getCollectionProductsQuery,
@ -292,7 +306,9 @@ export async function getCollectionProducts({
variables: {
handle: collection,
reverse,
sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey
sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey,
language: language,
country: country
}
});
@ -349,41 +365,76 @@ export async function getMenu(handle: string): Promise<Menu[]> {
);
}
export async function getPage(handle: string): Promise<Page> {
export async function getPage({
handle,
language,
country
}: {
handle: string;
language?: string;
country?: string;
}): Promise<Page> {
const res = await shopifyFetch<ShopifyPageOperation>({
query: getPageQuery,
variables: { handle }
variables: { handle, language, country }
});
return res.body.data.pageByHandle;
}
export async function getPages(): Promise<Page[]> {
export async function getPages({
language,
country
}: {
language?: string;
country?: string;
}): Promise<Page[]> {
const res = await shopifyFetch<ShopifyPagesOperation>({
query: getPagesQuery
query: getPagesQuery,
variables: { language, country }
});
return removeEdgesAndNodes(res.body.data.pages);
}
export async function getProduct(handle: string): Promise<Product | undefined> {
export async function getProduct({
handle,
language,
country
}: {
handle: string;
language?: string;
country?: string;
}): Promise<Product | undefined> {
const res = await shopifyFetch<ShopifyProductOperation>({
query: getProductQuery,
tags: [TAGS.products],
variables: {
handle
handle,
language,
country
}
});
return reshapeProduct(res.body.data.product, false);
}
export async function getProductRecommendations(productId: string): Promise<Product[]> {
export async function getProductRecommendations({
productId,
language,
country
}: {
productId: string;
language?: string;
country?: string;
}): Promise<Product[]> {
const res = await shopifyFetch<ShopifyProductRecommendationsOperation>({
query: getProductRecommendationsQuery,
tags: [TAGS.products],
variables: {
productId
productId,
language,
country
}
});
@ -393,11 +444,15 @@ export async function getProductRecommendations(productId: string): Promise<Prod
export async function getProducts({
query,
reverse,
sortKey
sortKey,
language,
country
}: {
query?: string;
reverse?: boolean;
sortKey?: string;
language?: string;
country?: string;
}): Promise<Product[]> {
const res = await shopifyFetch<ShopifyProductsOperation>({
query: getProductsQuery,
@ -405,7 +460,9 @@ export async function getProducts({
variables: {
query,
reverse,
sortKey
sortKey,
language,
country
}
});

View File

@ -15,7 +15,8 @@ const collectionFragment = /* GraphQL */ `
`;
export const getCollectionQuery = /* GraphQL */ `
query getCollection($handle: String!) {
query getCollection($handle: String!, $country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
collection(handle: $handle) {
...collection
}
@ -41,7 +42,9 @@ export const getCollectionProductsQuery = /* GraphQL */ `
$handle: String!
$sortKey: ProductCollectionSortKeys
$reverse: Boolean
) {
$country: CountryCode
$language: LanguageCode
) @inContext(country: $country, language: $language) {
collection(handle: $handle) {
products(sortKey: $sortKey, reverse: $reverse, first: 100) {
edges {

View File

@ -19,7 +19,8 @@ const pageFragment = /* GraphQL */ `
`;
export const getPageQuery = /* GraphQL */ `
query getPage($handle: String!) {
query getPage($handle: String!, $country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
pageByHandle(handle: $handle) {
...page
}
@ -28,7 +29,8 @@ export const getPageQuery = /* GraphQL */ `
`;
export const getPagesQuery = /* GraphQL */ `
query getPages {
query getPages($country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
pages(first: 100) {
edges {
node {

View File

@ -1,7 +1,8 @@
import productFragment from '../fragments/product';
export const getProductQuery = /* GraphQL */ `
query getProduct($handle: String!) {
query getProduct($handle: String!, $country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
product(handle: $handle) {
...product
}
@ -10,7 +11,13 @@ export const getProductQuery = /* GraphQL */ `
`;
export const getProductsQuery = /* GraphQL */ `
query getProducts($sortKey: ProductSortKeys, $reverse: Boolean, $query: String) {
query getProducts(
$sortKey: ProductSortKeys
$reverse: Boolean
$query: String
$country: CountryCode
$language: LanguageCode
) @inContext(country: $country, language: $language) {
products(sortKey: $sortKey, reverse: $reverse, query: $query, first: 100) {
edges {
node {
@ -23,7 +30,8 @@ export const getProductsQuery = /* GraphQL */ `
`;
export const getProductRecommendationsQuery = /* GraphQL */ `
query getProductRecommendations($productId: ID!) {
query getProductRecommendations($productId: ID!, $country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
productRecommendations(productId: $productId) {
...product
}

View File

@ -190,6 +190,8 @@ export type ShopifyCollectionOperation = {
};
variables: {
handle: string;
language?: string;
country?: string;
};
};
@ -203,6 +205,8 @@ export type ShopifyCollectionProductsOperation = {
handle: string;
reverse?: boolean;
sortKey?: string;
language?: string;
country?: string;
};
};
@ -228,19 +232,25 @@ export type ShopifyMenuOperation = {
export type ShopifyPageOperation = {
data: { pageByHandle: Page };
variables: { handle: string };
variables: { handle: string; language?: string; country?: string };
};
export type ShopifyPagesOperation = {
data: {
pages: Connection<Page>;
};
variables: {
language?: string;
country?: string;
};
};
export type ShopifyProductOperation = {
data: { product: ShopifyProduct };
variables: {
handle: string;
language?: string;
country?: string;
};
};
@ -250,6 +260,8 @@ export type ShopifyProductRecommendationsOperation = {
};
variables: {
productId: string;
language?: string;
country?: string;
};
};
@ -261,5 +273,7 @@ export type ShopifyProductsOperation = {
query?: string;
reverse?: boolean;
sortKey?: string;
language?: string;
country?: string;
};
};

View File

@ -11,10 +11,11 @@ module.exports = {
},
fontFamily: {
sans: ['var(--font-alpina)', 'sans-serif'],
title: ['var(--font-cinzel)', 'sans-serif']
title: ['var(--font-cinzel)', 'sans-serif'],
japan: ['var(--font-mincho)', 'sans-serif']
},
aspectRatio: {
bottle: '0.7065217391'
bottle: '0.91'
},
keyframes: {
fadeIn: {