feat: Age gate

This commit is contained in:
Sol Irvine 2023-08-20 15:22:46 +09:00
parent 4c20ed4361
commit bd2906de25
13 changed files with 394 additions and 8 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,25 @@
import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';
const COOKIE_NAME = 'age_confirm';
export const useAgeConfirmation = () => {
const [ageConfirmed, setAgeConfirmed] = useState(true);
useEffect(() => {
if (!Cookies.get(COOKIE_NAME)) {
setAgeConfirmed(false);
}
}, []);
const confirmAge = () => {
setAgeConfirmed(true);
Cookies.set(COOKIE_NAME, 'confirmed', { expires: 365 });
};
return {
ageConfirmed,
onAgeConfirmed: confirmAge
};
};

View File

@ -0,0 +1,42 @@
'use client';
import { useAgeConfirmation } from 'app/hooks/use-age-confirmation';
import AgeGateForm from 'components/product/age-gate-form';
import Link from 'next/link';
import { FC, ReactNode, useState } from 'react';
type AgeConfirmBeforeCheckoutProps = {
children: ReactNode[] | ReactNode | string;
checkoutUrl: string;
};
const AgeConfirmBeforeCheckout: FC<AgeConfirmBeforeCheckoutProps> = ({ children, checkoutUrl }) => {
const [isConfirming, setIsConfirming] = useState<boolean>(false);
const { ageConfirmed } = useAgeConfirmation();
return ageConfirmed ? (
<>
<Link
href={checkoutUrl}
className="block w-full border border-white/20 bg-dark px-12 py-6 text-center font-sans font-medium uppercase tracking-wider text-white transition-colors duration-300 hover:bg-white hover:text-black"
>
{children}
</Link>
</>
) : (
<>
<button
type="button"
onClick={() => setIsConfirming(true)}
className="block w-full border border-white/20 bg-dark px-12 py-6 text-center font-sans font-medium uppercase tracking-wider text-white transition-colors duration-300 hover:bg-white hover:text-black"
>
{children}
</button>
{!!isConfirming && (
<AgeGateForm didCancel={() => setIsConfirming(false)} checkoutUrl={checkoutUrl} />
)}
</>
);
};
export default AgeConfirmBeforeCheckout;

View File

@ -6,9 +6,11 @@ import Price from 'components/price';
import { DEFAULT_OPTION } from 'lib/constants'; import { DEFAULT_OPTION } from 'lib/constants';
import type { Cart } from 'lib/shopify/types'; import type { Cart } from 'lib/shopify/types';
import { createUrl } from 'lib/utils'; import { createUrl } from 'lib/utils';
import { useTranslations } from 'next-intl';
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { Fragment, useEffect, useRef, useState } from 'react'; import { Fragment, useEffect, useRef, useState } from 'react';
import AgeConfirmBeforeCheckout from './age-gate-confirm-before-checkout';
import CloseCart from './close-cart'; import CloseCart from './close-cart';
import DeleteItemButton from './delete-item-button'; import DeleteItemButton from './delete-item-button';
import EditItemQuantityButton from './edit-item-quantity-button'; import EditItemQuantityButton from './edit-item-quantity-button';
@ -19,6 +21,7 @@ type MerchandiseSearchParams = {
}; };
export default function CartModal({ cart }: { cart: Cart | undefined }) { export default function CartModal({ cart }: { cart: Cart | undefined }) {
const t = useTranslations('Index');
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const quantityRef = useRef(cart?.totalQuantity); const quantityRef = useRef(cart?.totalQuantity);
const openCart = () => setIsOpen(true); const openCart = () => setIsOpen(true);
@ -169,12 +172,9 @@ export default function CartModal({ cart }: { cart: Cart | undefined }) {
/> />
</div> </div>
</div> </div>
<a <AgeConfirmBeforeCheckout checkoutUrl={cart.checkoutUrl}>
href={cart.checkoutUrl} {t('cart.proceed')}
className="block w-full rounded-full bg-blue-600 p-3 text-center text-sm font-medium text-white opacity-90 hover:opacity-100" </AgeConfirmBeforeCheckout>
>
Proceed to Checkout
</a>
</div> </div>
)} )}
</Dialog.Panel> </Dialog.Panel>

View File

@ -0,0 +1,212 @@
'use client';
/* This example requires Tailwind CSS v2.0+ */
import { FC, Fragment, useEffect, useRef, useState, useTransition } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { CheckIcon } from '@heroicons/react/24/outline';
import { useAgeConfirmation } from 'app/hooks/use-age-confirmation';
import clsx from 'clsx';
import { isBefore, isValid, parse } from 'date-fns';
import { useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
type AgeGateFormProps = {
checkoutUrl: string;
didCancel?: () => void;
};
const AgeGateForm: FC<AgeGateFormProps> = ({ checkoutUrl, didCancel }) => {
const t = useTranslations('Index');
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [hasValidDate, setHasValidDate] = useState(false);
const [month, setMonth] = useState<number>();
const [day, setDay] = useState<number>();
const [year, setYear] = useState<number>();
const { onAgeConfirmed } = useAgeConfirmation();
const yearFieldRef = useRef(null);
const minAge = 20;
const maxAge = 130;
const save = () => {
if (hasValidDate) {
onAgeConfirmed();
startTransition(() => {
router.push(checkoutUrl);
});
}
};
const cancel = () => {
if (didCancel) {
didCancel();
}
};
useEffect(() => {
const now = new Date();
const thresholdDate = new Date(now.getFullYear() - minAge, now.getMonth(), now.getDate());
const minDate = new Date(now.getFullYear() - maxAge, now.getMonth(), now.getDate());
if (month && day && year) {
const date = parse(`${month}-${day}-${year}`, 'MM-dd-yyyy', new Date());
const oldEnough = isBefore(date, thresholdDate);
const tooOld = isBefore(date, minDate);
setHasValidDate(isValid(date) && oldEnough && !tooOld);
} else {
setHasValidDate(false);
}
}, [month, day, year]);
return (
<>
<Transition.Root show={true} as={Fragment}>
<Dialog
as="div"
className="fixed inset-0 z-50 overflow-y-auto"
initialFocus={yearFieldRef}
onClose={() => {}}
>
<div
className={clsx(
'flex min-h-screen items-end justify-center px-4 pb-20 pt-4 text-center sm:block sm:p-0'
)}
>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Dialog.Overlay className="fixed inset-0 bg-dark bg-opacity-80 backdrop-blur-sm transition-opacity" />
</Transition.Child>
{/* This element is to trick the browser into centering the modal contents. */}
<span className="hidden sm:inline-block sm:h-screen sm:align-middle" aria-hidden="true">
&#8203;
</span>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<div className="inline-block transform space-y-6 overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left align-bottom text-dark shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6 sm:align-middle">
<div>
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900">
<CheckIcon
className="h-6 w-6 text-green-600 dark:text-green-400"
aria-hidden="true"
/>
</div>
<div className="text-center sm:mt-5">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-dark dark:text-white"
>
{t('age-gate.title')}
</Dialog.Title>
<div className="mt-2">
<p className="dark:text-secondary-neutral text-sm text-white">
{t('age-gate.description')}
</p>
</div>
</div>
</div>
<div>
<div className="text-center text-sm font-medium">{t('age-gate.birthdate')}</div>
</div>
<div>
<div className="flex flex-row justify-center space-x-2">
<div className="flex flex-col items-start space-y-1">
<input
type="text"
className="w-full border bg-white p-2 text-center selection:bg-emerald-200"
ref={yearFieldRef}
placeholder="YYYY"
maxLength={4}
onChange={(e) => setYear(parseInt(e?.target?.value))}
/>
<div className="w-full text-center text-xs">{t('age-gate.year')}</div>
</div>
<div className="flex flex-col items-start space-y-1">
<input
type="text"
className="w-full border bg-white p-2 text-center selection:bg-emerald-200"
placeholder="MM"
maxLength={2}
onChange={(e) => setMonth(parseInt(e?.target?.value))}
/>
<div className="w-full text-center text-xs">{t('age-gate.month')}</div>
</div>
<div className="flex flex-col items-start space-y-1">
<input
type="text"
className="w-full border bg-white p-2 text-center selection:bg-emerald-200"
placeholder="DD"
maxLength={2}
onChange={(e) => setDay(parseInt(e?.target?.value))}
/>
<div className="w-full text-center text-xs">{t('age-gate.day')}</div>
</div>
</div>
</div>
<div className="text-black sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
<button
type="button"
className={clsx(
'inline-flex w-full justify-center',
hasValidDate
? 'border border-dark hover:border-dark/50'
: 'border border-dark/50 hover:border-dark/20',
'bg-white px-4 py-2',
'text-base font-medium text-black',
'shadow-sm transition-colors duration-300',
'focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2',
'disabled:cursor-not-allowed disabled:opacity-50',
'disabled:border-dark/50 disabled:hover:border-dark/50',
'sm:col-start-2 sm:text-sm'
)}
onClick={() => save()}
disabled={!hasValidDate}
>
{isPending ? t('age-gate.confirming') : t('age-gate.confirm')}
</button>
<button
type="button"
className={clsx(
'mt-3 inline-flex w-full justify-center',
'border border-dark/50 hover:border-dark/20',
'bg-white px-4 py-2',
'text-base font-medium',
'text-black shadow-sm transition-all duration-300 hover:bg-white hover:bg-opacity-20',
'focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2',
'sm:col-start-1 sm:mt-0 sm:text-sm',
'disabled:border-dark/50 disabled:hover:border-dark/50'
)}
onClick={() => cancel()}
disabled={isPending}
>
{t('age-gate.deny')}
</button>
</div>
</div>
</Transition.Child>
</div>
</Dialog>
</Transition.Root>
</>
);
};
export default AgeGateForm;

View File

@ -69,7 +69,38 @@
}, },
"cart": { "cart": {
"add": "Add to cart", "add": "Add to cart",
"out-of-stock": "Out of stock" "out-of-stock": "Out of stock",
"title": "Shopping Bag",
"subtitle": "Review your Order",
"empty": "Your shopping bag is empty",
"declinedCard": "We couldn't process the purchase. Please check your card information and try again.",
"thankYou": "Thank you for your order.",
"subtotal": "Subtotal",
"taxes": "Taxes",
"taxCalculation": "Calculated at checkout",
"shipping": "Shipping",
"shippingCalculation": "Calculated at checkout",
"total": "Total",
"proceed": "Proceed to Checkout",
"continue": "Continue Shopping",
"note": "Notes",
"notePlaceholder": "Enter any notes you would like to include with your order",
"addNote": "Add a note to your order",
"editNote": "Edit note",
"hideNote": "Hide",
"saving": "Saving...",
"addFeaturedProduct": "+ Add"
},
"age-gate": {
"title": "Confirm Your Age",
"description": "In order to shop on this site, please confirm that you are of legal age to purchase alcohol under the laws that apply to you.",
"confirm": "Confirm",
"confirming": "Confirming",
"deny": "No",
"birthdate": "Your date of birth",
"year": "Year",
"month": "Month",
"day": "Day"
} }
} }
} }

View File

@ -69,7 +69,38 @@
}, },
"cart": { "cart": {
"add": "カートに入れる", "add": "カートに入れる",
"out-of-stock": "品切れ中" "out-of-stock": "品切れ中",
"title": "ショッピングカード",
"subtitle": "ご注文内容の確認",
"empty": "買い物袋が空っぽ",
"declinedCard": "購入手続きができませんでした。カード情報をご確認の上、再度お試しください。",
"thankYou": "この度はご注文ありがとうございました。",
"subtotal": "サブトータル",
"taxes": "税金",
"taxCalculation": "チェックアウト時に計算されます",
"shipping": "配送",
"shippingCalculation": "チェックアウト時に計算されます",
"total": "合計",
"proceed": "チェックアウトに進む",
"continue": "ショッピングを続ける",
"note": "メモ",
"notePlaceholder": "注文時に添えるメモを入力してください",
"addNote": "注文にメモを追加します",
"editNote": "メモを編集します",
"hideNote": "隠れる",
"saving": "セービング...",
"addFeaturedProduct": "+ 入れる"
},
"age-gate": {
"title": "年齢確認",
"description": "当サイトでのご購入には、お客さまがアルコール飲料を購入できる年齢であることの確認が必要となります。",
"confirm": "はい",
"confirming": "確認中",
"deny": "いいえ",
"birthdate": "生年月日を入力してください。",
"year": "年",
"month": "月",
"day": "日"
} }
} }
} }

View File

@ -27,8 +27,10 @@
"@heroicons/react": "^2.0.18", "@heroicons/react": "^2.0.18",
"@thgh/next-gtm": "^0.1.4", "@thgh/next-gtm": "^0.1.4",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"date-fns": "^2.30.0",
"eslint-plugin-tailwindcss": "^3.13.0", "eslint-plugin-tailwindcss": "^3.13.0",
"eslint-plugin-unused-imports": "^3.0.0", "eslint-plugin-unused-imports": "^3.0.0",
"js-cookie": "^3.0.5",
"negotiator": "^0.6.3", "negotiator": "^0.6.3",
"next": "latest", "next": "latest",
"next-intl": "latest", "next-intl": "latest",
@ -40,6 +42,7 @@
"devDependencies": { "devDependencies": {
"@tailwindcss/container-queries": "^0.1.1", "@tailwindcss/container-queries": "^0.1.1",
"@tailwindcss/typography": "^0.5.9", "@tailwindcss/typography": "^0.5.9",
"@types/js-cookie": "^3.0.3",
"@types/negotiator": "^0.6.1", "@types/negotiator": "^0.6.1",
"@types/node": "20.4.4", "@types/node": "20.4.4",
"@types/react": "18.2.16", "@types/react": "18.2.16",

View File

@ -55,6 +55,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@babel/runtime@npm:^7.21.0":
version: 7.22.10
resolution: "@babel/runtime@npm:7.22.10"
dependencies:
regenerator-runtime: ^0.14.0
checksum: 524d41517e68953dbc73a4f3616b8475e5813f64e28ba89ff5fca2c044d535c2ea1a3f310df1e5bb06162e1f0b401b5c4af73fe6e2519ca2450d9d8c44cf268d
languageName: node
linkType: hard
"@eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0": "@eslint-community/eslint-utils@npm:^4.2.0, @eslint-community/eslint-utils@npm:^4.4.0":
version: 4.4.0 version: 4.4.0
resolution: "@eslint-community/eslint-utils@npm:4.4.0" resolution: "@eslint-community/eslint-utils@npm:4.4.0"
@ -476,6 +485,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@types/js-cookie@npm:^3.0.3":
version: 3.0.3
resolution: "@types/js-cookie@npm:3.0.3"
checksum: 927254ec37ce4fbe4d9d54f53a446b4351259799d9933db5808ddb7c430396aa2496bdd0a4e47e1b56048ffbec98645cbd4daa9e3ed9a6fff55e25eb640fcb15
languageName: node
linkType: hard
"@types/json5@npm:^0.0.29": "@types/json5@npm:^0.0.29":
version: 0.0.29 version: 0.0.29
resolution: "@types/json5@npm:0.0.29" resolution: "@types/json5@npm:0.0.29"
@ -1272,18 +1288,21 @@ __metadata:
"@tailwindcss/container-queries": ^0.1.1 "@tailwindcss/container-queries": ^0.1.1
"@tailwindcss/typography": ^0.5.9 "@tailwindcss/typography": ^0.5.9
"@thgh/next-gtm": ^0.1.4 "@thgh/next-gtm": ^0.1.4
"@types/js-cookie": ^3.0.3
"@types/negotiator": ^0.6.1 "@types/negotiator": ^0.6.1
"@types/node": 20.4.4 "@types/node": 20.4.4
"@types/react": 18.2.16 "@types/react": 18.2.16
"@types/react-dom": 18.2.7 "@types/react-dom": 18.2.7
autoprefixer: ^10.4.14 autoprefixer: ^10.4.14
clsx: ^2.0.0 clsx: ^2.0.0
date-fns: ^2.30.0
eslint: ^8.45.0 eslint: ^8.45.0
eslint-config-next: latest eslint-config-next: latest
eslint-config-prettier: ^8.8.0 eslint-config-prettier: ^8.8.0
eslint-plugin-tailwindcss: ^3.13.0 eslint-plugin-tailwindcss: ^3.13.0
eslint-plugin-unicorn: ^48.0.0 eslint-plugin-unicorn: ^48.0.0
eslint-plugin-unused-imports: ^3.0.0 eslint-plugin-unused-imports: ^3.0.0
js-cookie: ^3.0.5
lint-staged: ^13.2.3 lint-staged: ^13.2.3
negotiator: ^0.6.3 negotiator: ^0.6.3
next: latest next: latest
@ -1348,6 +1367,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"date-fns@npm:^2.30.0":
version: 2.30.0
resolution: "date-fns@npm:2.30.0"
dependencies:
"@babel/runtime": ^7.21.0
checksum: f7be01523282e9bb06c0cd2693d34f245247a29098527d4420628966a2d9aad154bd0e90a6b1cf66d37adcb769cd108cf8a7bd49d76db0fb119af5cdd13644f4
languageName: node
linkType: hard
"debug@npm:4, debug@npm:^4.1.0, debug@npm:^4.1.1, debug@npm:^4.3.2, debug@npm:^4.3.3, debug@npm:^4.3.4": "debug@npm:4, debug@npm:^4.1.0, debug@npm:^4.1.1, debug@npm:^4.3.2, debug@npm:^4.3.3, debug@npm:^4.3.4":
version: 4.3.4 version: 4.3.4
resolution: "debug@npm:4.3.4" resolution: "debug@npm:4.3.4"
@ -2919,6 +2947,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"js-cookie@npm:^3.0.5":
version: 3.0.5
resolution: "js-cookie@npm:3.0.5"
checksum: 2dbd2809c6180fbcf060c6957cb82dbb47edae0ead6bd71cbeedf448aa6b6923115003b995f7d3e3077bfe2cb76295ea6b584eb7196cca8ba0a09f389f64967a
languageName: node
linkType: hard
"js-tokens@npm:^3.0.0 || ^4.0.0, js-tokens@npm:^4.0.0": "js-tokens@npm:^3.0.0 || ^4.0.0, js-tokens@npm:^4.0.0":
version: 4.0.0 version: 4.0.0
resolution: "js-tokens@npm:4.0.0" resolution: "js-tokens@npm:4.0.0"
@ -4212,6 +4247,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"regenerator-runtime@npm:^0.14.0":
version: 0.14.0
resolution: "regenerator-runtime@npm:0.14.0"
checksum: 1c977ad82a82a4412e4f639d65d22be376d3ebdd30da2c003eeafdaaacd03fc00c2320f18120007ee700900979284fc78a9f00da7fb593f6e6eeebc673fba9a3
languageName: node
linkType: hard
"regexp-tree@npm:^0.1.27": "regexp-tree@npm:^0.1.27":
version: 0.1.27 version: 0.1.27
resolution: "regexp-tree@npm:0.1.27" resolution: "regexp-tree@npm:0.1.27"