Agnostic UI (#199)

* changes

* Progress

* Normalized Products output

* Progress

* Restored Index Agnostic

* Progress

* Reordering

* Moved normalizer to BC function

* Removed Futures

* More Types

* More Types

* More Types

* Fix useCallback

* Progress, Changes types, readme and restoring functionality

* Changes

* TS Issues

* Changes

* Normalizer

* Normalizing more operations

* Normalizing more operations

* changes

* Merge Issues

* Cleanup

* change

* changes

* index.ts broke my tree shaking

* slug

* Normalized Options and Swatches

* Restored Add to cart

* Correct Variant Added to Cart

* Normalizing Cart Responses

* Changes

* changes breaking

* Adding immutable normalizer for Product

* Cart Normalized

* changes

* Progress

* More updates

* Removed some comments

* Add loading state for data hooks

* Bug fix

* Changed the way isEmpty works

* Improve navbar performance

* Added useResponse hook

* added useResponse to useWhishlist

* Added husky and lint-staged

* Ran prettier fix

* Added more cart types

* Moved types.d.ts to the commerce folder

* Minor changes

* Moved normalizer to happen after fetch

* updated useCart types

* Updated normalizer for useData

* Added new normalizer for the cart to the UI

* More corrections for useCart

* Updated cart update hooks

* Removed import

* Progress

* Switch away from global types

* Making multiple changes

* Improved types for operations

* Moved and updated cart types

* Updated the useAddItem and useRemoveItem hooks

* Minor life improvement

* Minor change

* Implement Shopify Provider

* Update README.md

* Update README.md

* normalizations & missing files

* Update index.ts

* fixes

* Update normalize.ts

* fix: cart error on first load

* shopify checkout redirect & api handler

* Update get-checkout-id.ts

* userAvatar

* Fix: color option

* Update normalize.ts

* changes

* Update next.config.js

* start customer auth & signup

* Update config.ts

* Login, Sign Up, Log Out, and checkout & customer association

* Automatic login after sign-up

* Update handle-login.ts

* MOving stuff around and adding temporal new files

* changes

* Replace use-cart with the new hook

* Removed old hook

* Improved HookHandler type

* Moved types

* Simplified useData types

* Updated Fetcher type

* Moved SwrOptions type

* Removed duplicated fetcher

* Moved provider to its own file

* Added proper type for fetch input

* Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic"

This reverts commit 23c8ed7c2d, reversing
changes made to bf50965a39.

* change readme

* Revert "Merge branch 'master' of https://github.com/vercel/commerce into agnostic"

This reverts commit bf50965a39, reversing
changes made to 0dad4ddedb.

* Revert "Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic""

This reverts commit c9a43f1bce.

* align with upstream changes

* Updated how the hook input is handled

* Add more options to the hook handler

* Final touches to the hook handler type

* Moved useWishlist to use new handler

* Move useCustomer to the new hook

* Added a default fetcher

* query all products for vendors & paths, improve search

* Update use-search.tsx

* fix cart after upstream changes

* Shopify Provider (#186)

* Start of Shopify provider

* add missing comment to documentation

* add missing env vars to documentation

* update reference to types file

* Moved useSearch to the new hook

* Removed old use-data lib

* Removed generics for result and body

* Removed normalizr

* Wishlist

* New changes and initial Features API

* Fixed some types

* Fixed more types

* fixes after upstream changes

* Fixed product types

* Fixed another product type

* Updated type

* Fixed remaining issues with types

* Added a MutationHandler

* Moved the handlers to each hook

* Moved the fetcher to its own file

* Moved handler to each hook

* Added initial version of useAddItem

* Added better mutation types, and moved some hooks

* Removed use-cart-actions

* Added initial version of useAddItem

* Updated types

* Update use-add-item.tsx

* changes

* Changes

* Reordering and changes

* Adding Features APO

* Adding wishlist api

* Implementing FeaturesAPI with Wishlist

* Removing bug with touchstart

* Adding tyni typing

* moved use-remove-item

* Removed MutationHandler type

* Moved more hooks and updated types to make them smaller

* Moved data hooks to new format

* Removed no longer required types

* Removed useResponse helper

* Updated useData type

* Moved wishlist use-add-item

* Moved wishlist use-remove-item to provider

* Moved use-login and use-logout

* Update use-signup

* Removed use-action helper

* Moved auth & cart hooks + several fixes

* Updated cart item, fixed deprecations

* Update next.config.js

* Updates to wishlist feature

* Moved the features to be environment variable only

* More changes for wishlist config

* Disable wishlist

* Removed useWishlistActions

* Updated readme

* updates

* typos

* Updated the way the provider config is set

* Removed features.ts

* Removed bootstrap.js

* Aligned with upstream changes

* Updates

* shopify: changes

* shopify: changes

* Update next.config.js

* Shopify Provider Updates (#209)

* Implement Shopify Provider

* Update README.md

* Update README.md

* normalizations & missing files

* Update index.ts

* fixes

* Update normalize.ts

* fix: cart error on first load

* shopify checkout redirect & api handler

* Update get-checkout-id.ts

* Fix: color option

* Update normalize.ts

* changes

* Update next.config.js

* start customer auth & signup

* Update config.ts

* Login, Sign Up, Log Out, and checkout & customer association

* Automatic login after sign-up

* Update handle-login.ts

* changes

* Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic"

This reverts commit 23c8ed7c2d, reversing
changes made to bf50965a39.

* change readme

* Revert "Merge branch 'master' of https://github.com/vercel/commerce into agnostic"

This reverts commit bf50965a39, reversing
changes made to 0dad4ddedb.

* Revert "Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic""

This reverts commit c9a43f1bce.

* align with upstream changes

* query all products for vendors & paths, improve search

* Update use-search.tsx

* fix cart after upstream changes

* fixes after upstream changes

* Moved handler to each hook

* Added initial version of useAddItem

* Updated types

* Update use-add-item.tsx

* Moved auth & cart hooks + several fixes

* Updated cart item, fixed deprecations

* Update next.config.js

* Aligned with upstream changes

* Updates

* Update next.config.js

* Updated the commerce config structure

* Removed @framework imports within framework providers

* Fixed types

* changes

* Adding extra config

* Adding shopify commit

* Adding env templates to the providers

* Ignore some types

* Adding link for Cart

* Adding customCheckout

* multiple changes to fix the wishlist

* Shopify Provier Updates (#212)

* changes

* Adding shopify commit

* Changed to query page by id

* Fixed page query, Changed use-search GraphQl query

* Update use-search.tsx

* remove unused util

* Changed cookie expiration

* Update tsconfig.json

Co-authored-by: okbel <curciobel@gmail.com>

* Bump and adding dependency

* Adding color checks

* Now colors work with lighter colors

* Stable commerce.config.json

* Updated main readme

* Readme changes

* Default to bigcommerce

Co-authored-by: bc <bc@bcs-MacBook-Pro.fibertel.com.ar>
Co-authored-by: Luis Alvarez <luis@vercel.com>
Co-authored-by: cond0r <pinte_catalin@yahoo.com>
Co-authored-by: Peter Mekhaeil <4616064+petermekhaeil@users.noreply.github.com>
This commit is contained in:
B
2021-03-04 07:57:25 -03:00
committed by GitHub
parent b121078151
commit 9b71bd77fc
232 changed files with 20545 additions and 1895 deletions

View File

@@ -1,103 +1,88 @@
import { FC } from 'react'
import cn from 'classnames'
import Link from 'next/link'
import Image from 'next/image'
import type { FC } from 'react'
import type { Product } from '@commerce/types'
import s from './ProductCard.module.css'
import Image, { ImageProps } from 'next/image'
import WishlistButton from '@components/wishlist/WishlistButton'
import usePrice from '@framework/use-price'
import type { ProductNode } from '@framework/api/operations/get-all-products'
interface Props {
className?: string
product: ProductNode
product: Product
variant?: 'slim' | 'simple'
imgWidth: number | string
imgHeight: number | string
imgLayout?: 'fixed' | 'intrinsic' | 'responsive' | undefined
imgPriority?: boolean
imgLoading?: 'eager' | 'lazy'
imgSizes?: string
imgProps?: Omit<ImageProps, 'src'>
}
const placeholderImg = '/product-img-placeholder.svg'
const ProductCard: FC<Props> = ({
className,
product: p,
product,
variant,
imgWidth,
imgHeight,
imgPriority,
imgLoading,
imgSizes,
imgLayout = 'responsive',
}) => {
const src = p.images.edges?.[0]?.node?.urlOriginal!
const placeholderImg = '/product-img-placeholder.svg';
const { price } = usePrice({
amount: p.prices?.price?.value,
baseAmount: p.prices?.retailPrice?.value,
currencyCode: p.prices?.price?.currencyCode!,
})
return (
<Link href={`/product${p.path}`}>
<a
className={cn(s.root, { [s.simple]: variant === 'simple' }, className)}
>
{variant === 'slim' ? (
<div className="relative overflow-hidden box-border">
<div className="absolute inset-0 flex items-center justify-end mr-8 z-20">
<span className="bg-black text-white inline-block p-3 font-bold text-xl break-words">
{p.name}
</span>
</div>
imgProps,
...props
}) => (
<Link href={`/product/${product.slug}`} {...props}>
<a className={cn(s.root, { [s.simple]: variant === 'simple' }, className)}>
{variant === 'slim' ? (
<div className="relative overflow-hidden box-border">
<div className="absolute inset-0 flex items-center justify-end mr-8 z-20">
<span className="bg-black text-white inline-block p-3 font-bold text-xl break-words">
{product.name}
</span>
</div>
{product?.images && (
<Image
quality="85"
width={imgWidth}
sizes={imgSizes}
height={imgHeight}
layout={imgLayout}
loading={imgLoading}
priority={imgPriority}
src={p.images.edges?.[0]?.node.urlOriginal! || placeholderImg}
alt={p.images.edges?.[0]?.node.altText || 'Product Image'}
src={product.images[0].url || placeholderImg}
alt={product.name || 'Product Image'}
height={320}
width={320}
layout="fixed"
{...imgProps}
/>
</div>
) : (
<>
<div className={s.squareBg} />
<div className="flex flex-row justify-between box-border w-full z-20 absolute">
<div className="absolute top-0 left-0 pr-16 max-w-full">
<h3 className={s.productTitle}>
<span>{p.name}</span>
</h3>
<span className={s.productPrice}>{price}</span>
</div>
)}
</div>
) : (
<>
<div className={s.squareBg} />
<div className="flex flex-row justify-between box-border w-full z-20 absolute">
<div className="absolute top-0 left-0 pr-16 max-w-full">
<h3 className={s.productTitle}>
<span>{product.name}</span>
</h3>
<span className={s.productPrice}>
{product.price.value}
&nbsp;
{product.price.currencyCode}
</span>
</div>
{process.env.COMMERCE_WISHLIST_ENABLED && (
<WishlistButton
className={s.wishlistButton}
productId={p.entityId}
variant={p.variants.edges?.[0]!}
productId={product.id}
variant={product.variants[0] as any}
/>
</div>
<div className={s.imageContainer}>
)}
</div>
<div className={s.imageContainer}>
{product?.images && (
<Image
quality="85"
src={src || placeholderImg}
alt={p.name}
alt={product.name || 'Product Image'}
className={s.productImage}
width={imgWidth}
sizes={imgSizes}
height={imgHeight}
layout={imgLayout}
loading={imgLoading}
priority={imgPriority}
src={product.images[0].url || placeholderImg}
height={540}
width={540}
quality="85"
layout="responsive"
{...imgProps}
/>
</div>
</>
)}
</a>
</Link>
)
}
)}
</div>
</>
)}
</a>
</Link>
)
export default ProductCard

View File

@@ -1,5 +1,12 @@
import { useKeenSlider } from 'keen-slider/react'
import React, { Children, FC, isValidElement, useState, useRef, useEffect } from 'react'
import React, {
Children,
FC,
isValidElement,
useState,
useRef,
useEffect,
} from 'react'
import cn from 'classnames'
import s from './ProductSlider.module.css'
@@ -25,7 +32,7 @@ const ProductSlider: FC = ({ children }) => {
const touchXPosition = event.touches[0].pageX
// Size of the touch area
const touchXRadius = event.touches[0].radiusX || 0
// We set a threshold (10px) on both sizes of the screen,
// if the touch area overlaps with the screen edges
// it's likely to trigger the navigation. We prevent the
@@ -33,15 +40,22 @@ const ProductSlider: FC = ({ children }) => {
if (
touchXPosition - touchXRadius < 10 ||
touchXPosition + touchXRadius > window.innerWidth - 10
) event.preventDefault()
)
event.preventDefault()
}
sliderContainerRef.current!
.addEventListener('touchstart', preventNavigation)
sliderContainerRef.current!.addEventListener(
'touchstart',
preventNavigation
)
return () => {
sliderContainerRef.current!
.removeEventListener('touchstart', preventNavigation)
if (sliderContainerRef.current) {
sliderContainerRef.current!.removeEventListener(
'touchstart',
preventNavigation
)
}
}
}, [])

View File

@@ -7,7 +7,7 @@
}
.productDisplay {
@apply relative flex px-0 pb-0 relative box-border col-span-1 bg-violet;
@apply relative flex px-0 pb-0 box-border col-span-1 bg-violet;
min-height: 600px;
@screen md {

View File

@@ -1,51 +1,48 @@
import { FC, useState } from 'react'
import cn from 'classnames'
import Image from 'next/image'
import { NextSeo } from 'next-seo'
import { FC, useState } from 'react'
import s from './ProductView.module.css'
import { useUI } from '@components/ui/context'
import { Swatch, ProductSlider } from '@components/product'
import { Button, Container, Text } from '@components/ui'
import usePrice from '@framework/use-price'
import useAddItem from '@framework/cart/use-add-item'
import type { ProductNode } from '@framework/api/operations/get-product'
import {
getCurrentVariant,
getProductOptions,
SelectedOptions,
} from '../helpers'
import { Swatch, ProductSlider } from '@components/product'
import { Button, Container, Text, useUI } from '@components/ui'
import type { Product } from '@commerce/types'
import usePrice from '@framework/product/use-price'
import { useAddItem } from '@framework/cart'
import { getVariant, SelectedOptions } from '../helpers'
import WishlistButton from '@components/wishlist/WishlistButton'
interface Props {
className?: string
children?: any
product: ProductNode
product: Product
}
const ProductView: FC<Props> = ({ product }) => {
const addItem = useAddItem()
const { price } = usePrice({
amount: product.prices?.price?.value,
baseAmount: product.prices?.retailPrice?.value,
currencyCode: product.prices?.price?.currencyCode!,
amount: product.price.value,
baseAmount: product.price.retailPrice,
currencyCode: product.price.currencyCode!,
})
const { openSidebar } = useUI()
const options = getProductOptions(product)
const [loading, setLoading] = useState(false)
const [choices, setChoices] = useState<SelectedOptions>({
size: null,
color: null,
})
const variant = getCurrentVariant(product, choices)
// Select the correct variant based on choices
const variant = getVariant(product, choices)
const addToCart = async () => {
setLoading(true)
try {
await addItem({
productId: product.entityId,
variantId: variant?.node.entityId!,
productId: String(product.id),
variantId: String(variant ? variant.id : product.variants[0].id),
})
openSidebar()
setLoading(false)
@@ -65,7 +62,7 @@ const ProductView: FC<Props> = ({ product }) => {
description: product.description,
images: [
{
url: product.images.edges?.[0]?.node.urlOriginal!,
url: product.images[0]?.url!,
width: 800,
height: 600,
alt: product.name,
@@ -80,18 +77,18 @@ const ProductView: FC<Props> = ({ product }) => {
<div className={s.price}>
{price}
{` `}
{product.prices?.price.currencyCode}
{product.price?.currencyCode}
</div>
</div>
<div className={s.sliderContainer}>
<ProductSlider key={product.entityId}>
{product.images.edges?.map((image, i) => (
<div key={image?.node.urlOriginal} className={s.imageContainer}>
<ProductSlider key={product.id}>
{product.images.map((image, i) => (
<div key={image.url} className={s.imageContainer}>
<Image
className={s.img}
src={image?.node.urlOriginal!}
alt={image?.node.altText || 'Product Image'}
src={image.url!}
alt={image.alt || 'Product Image'}
width={1050}
height={1050}
priority={i === 0}
@@ -102,20 +99,21 @@ const ProductView: FC<Props> = ({ product }) => {
</ProductSlider>
</div>
</div>
<div className={s.sidebar}>
<section>
{options?.map((opt: any) => (
{product.options?.map((opt) => (
<div className="pb-4" key={opt.displayName}>
<h2 className="uppercase font-medium">{opt.displayName}</h2>
<div className="flex flex-row py-4">
{opt.values.map((v: any, i: number) => {
const active = (choices as any)[opt.displayName]
{opt.values.map((v, i: number) => {
const active = (choices as any)[
opt.displayName.toLowerCase()
]
return (
<Swatch
key={`${v.entityId}-${i}`}
active={v.label === active}
key={`${opt.id}-${i}`}
active={v.label.toLowerCase() === active}
variant={opt.displayName}
color={v.hexColors ? v.hexColors[0] : ''}
label={v.label}
@@ -123,7 +121,7 @@ const ProductView: FC<Props> = ({ product }) => {
setChoices((choices) => {
return {
...choices,
[opt.displayName]: v.label,
[opt.displayName.toLowerCase()]: v.label.toLowerCase(),
}
})
}}
@@ -145,18 +143,19 @@ const ProductView: FC<Props> = ({ product }) => {
className={s.button}
onClick={addToCart}
loading={loading}
disabled={!variant}
disabled={!variant && product.options.length > 0}
>
Add to Cart
</Button>
</div>
</div>
<WishlistButton
className={s.wishlistButton}
productId={product.entityId}
variant={variant!}
/>
{process.env.COMMERCE_WISHLIST_ENABLED && (
<WishlistButton
className={s.wishlistButton}
productId={product.id}
variant={product.variants[0]! as any}
/>
)}
</div>
</Container>
)

View File

@@ -1,4 +1,5 @@
.root {
composes: root from 'components/ui/Button/Button.module.css';
@apply h-12 w-12 bg-primary text-primary rounded-full mr-3 inline-flex
items-center justify-center cursor-pointer transition duration-150 ease-in-out
p-0 shadow-none border-gray-200 border box-border;

View File

@@ -13,7 +13,7 @@ interface Props {
color?: string
}
const Swatch: FC<Props & ButtonProps> = ({
const Swatch: FC<Omit<ButtonProps, 'variant'> & Props> = ({
className,
color = '',
label,

View File

@@ -1,56 +1,22 @@
import type { ProductNode } from '@framework/api/operations/get-product'
import type { Product } from '@commerce/types'
export type SelectedOptions = {
size: string | null
color: string | null
}
export type ProductOption = {
displayName: string
values: any
}
// Returns the available options of a product
export function getProductOptions(product: ProductNode) {
const options = product.productOptions.edges?.reduce<ProductOption[]>(
(arr, edge) => {
if (edge?.node.__typename === 'MultipleChoiceOption') {
arr.push({
displayName: edge.node.displayName.toLowerCase(),
values: edge.node.values.edges?.map((edge) => edge?.node),
})
}
return arr
},
[]
)
return options
}
// Finds a variant in the product that matches the selected options
export function getCurrentVariant(product: ProductNode, opts: SelectedOptions) {
const variant = product.variants.edges?.find((edge) => {
const { node } = edge ?? {}
const numberOfDefinedOpts = Object.values(opts).filter(value => value !== null).length;
const numberOfEdges = node?.productOptions?.edges?.length;
const isEdgeEqualToOption = ([key, value]:[string, string | null]) =>
node?.productOptions.edges?.find((edge) => {
export function getVariant(product: Product, opts: SelectedOptions) {
const variant = product.variants.find((variant) => {
return Object.entries(opts).every(([key, value]) =>
variant.options.find((option) => {
if (
edge?.node.__typename === 'MultipleChoiceOption' &&
edge.node.displayName.toLowerCase() === key
option.__typename === 'MultipleChoiceOption' &&
option.displayName.toLowerCase() === key.toLowerCase()
) {
return edge.node.values.edges?.find(
(valueEdge) => valueEdge?.node.label === value
)
return option.values.find((v) => v.label.toLowerCase() === value)
}
});
return numberOfDefinedOpts === numberOfEdges ?
Object.entries(opts).every(isEdgeEqualToOption)
: Object.entries(opts).some(isEdgeEqualToOption)
})
)
})
return variant ?? product.variants.edges?.[0]
return variant
}