Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sku matrix ui and components #2503

Open
wants to merge 3 commits into
base: feat/sku-matrix-cubos
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions packages/components/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export { default as UIProvider, Toast as ToastProps, useUI } from './UIProvider'
export { useFadeEffect } from './useFadeEffect'
export { useTrapFocus } from './useTrapFocus'
export { useSearch } from './useSearch'
export { useSKUMatrix } from './useSKUMatrix'
export { useScrollDirection } from './useScrollDirection'
export { useSlider } from './useSlider'
export type {
Expand All @@ -11,5 +12,3 @@ export type {
SlideDirection,
} from './useSlider'
export { useSlideVisibility } from './useSlideVisibility'


14 changes: 14 additions & 0 deletions packages/components/src/hooks/useSKUMatrix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useContext } from 'react'
import { SKUMatrixContext } from '../organisms/SKUMatrix/provider/SKUMatrixProvider'

export function useSKUMatrix() {
const context = useContext(SKUMatrixContext)

if (!context) {
throw new Error(
'Do not use SKUMatrix components outside the SKUMatrix context'
)
}

return context
}
11 changes: 11 additions & 0 deletions packages/components/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,14 @@ export type {
SlideOverProps,
SlideOverHeaderProps,
} from './organisms/SlideOver'

export {
default as SKUMatrix,
SKUMatrixTrigger,
SKUMatrixSidebar,
} from './organisms/SKUMatrix'
export type {
SKUMatrixTriggerProps,
SKUMatrixSidebarProps,
SKUMatrixProps,
} from './organisms/SKUMatrix'
17 changes: 17 additions & 0 deletions packages/components/src/organisms/SKUMatrix/SKUMatrix.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React, { forwardRef, HTMLAttributes } from 'react'
import SKUMatrixProvider from './provider/SKUMatrixProvider'

export type SKUMatrixProps = HTMLAttributes<HTMLDivElement>

const SKUMatrix = forwardRef<HTMLDivElement, SKUMatrixProps>(function SKUMatrix(
{ children, ...otherProps },
ref
) {
return (
<div data-fs-sku-matrix ref={ref} {...otherProps}>
<SKUMatrixProvider>{children}</SKUMatrixProvider>
</div>
)
})

export default SKUMatrix
323 changes: 323 additions & 0 deletions packages/components/src/organisms/SKUMatrix/SKUMatrixSidebar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,323 @@
import Image from 'next/image'
import type { HTMLAttributes } from 'react'
import React, { useMemo } from 'react'
import { Badge, Button, OverlayProps, QuantitySelector, Skeleton } from '../..'
import Price, { PriceFormatter } from '../../atoms/Price'
import Icon from '../../atoms/Icon'
import { useFadeEffect, useSKUMatrix, useUI } from '../../hooks'
import {
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from '../../molecules/Table'
import SlideOver, {
SlideOverDirection,
SlideOverHeader,
SlideOverWidthSize,
} from '../SlideOver'

export interface SKUMatrixSidebarProps extends HTMLAttributes<HTMLDivElement> {
/**
* ID to find this component in testing tools (e.g.: cypress,
* testing-library, and jest).
*/
testId?: string
/**
* Title for the SKUMatrixSidebar component.
*/
title?: string
/**
* Represents the side that the SKUMatrixSidebar comes from.
*/
direction?: SlideOverDirection
/**
* Represents the size of the SKUMatrixSidebar.
*/
size?: SlideOverWidthSize
/**
* Props forwarded to the `Overlay` component.
*/
overlayProps?: OverlayProps
/**
* Columns.
*/
columns: {
name: string
additionalColumns: Array<{ label: string; value: string }>
availability: {
label: string
stockDisplaySettings: 'showStockQuantity' | 'showAvailability'
}
price: number
quantitySelector: number
}

/**
* Properties related to the 'add to cart' button
*/
buyProps: {
'data-testid': string
'data-sku': string
'data-seller': string
onClick(e: React.MouseEvent<HTMLButtonElement>): void
}
/**
* Formatter function that transforms the raw price value and render the result.
*/
formatter?: PriceFormatter

/**
* Check if some result is still loading before render the result.
*/
loading?: boolean
}

function SKUMatrixSidebar({
direction = 'rightSide',
title,
overlayProps,
size = 'partial',
children,
columns,
buyProps: { onClick: buyButtonOnClick, ...buyProps },
loading,
formatter,
...otherProps
}: SKUMatrixSidebarProps) {
const { fade } = useFadeEffect()
const {
open,
setOpen,
setAllVariantProducts,
allVariantProducts,
handleChangeQuantityItem,
} = useSKUMatrix()
const { pushToast } = useUI()

const cartDetails = useMemo(() => {
return allVariantProducts.reduce(
(acc, product) => ({
amount: acc.amount + product.selectedCount,
subtotal: acc.subtotal + product.selectedCount * product.price,
}),
{ amount: 0, subtotal: 0 }
)
}, [allVariantProducts])

function resetQuantityItems() {
setAllVariantProducts((prev) =>
prev.map((item) => ({ ...item, quantity: 0 }))
)
}

function handleQuantitySelectorChange(id: string, value: number) {
handleChangeQuantityItem(id, value)
}

function onClose() {
resetQuantityItems()
setOpen(false)
}

function handleAddToCart(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
buyButtonOnClick(e)
onClose()
}

const totalColumnsSkeletonLength =
Object.keys(columns).length - 1 + (columns.additionalColumns?.length ?? 0)

return (
<SlideOver
data-fs-sku-matrix-sidebar
isOpen={open}
fade={fade}
size={size}
direction={direction}
overlayProps={overlayProps}
{...otherProps}
>
<SlideOverHeader onClose={onClose}>
<h2 data-fs-sku-matrix-sidebar-title>{title}</h2>
</SlideOverHeader>

{children}

<Table variant="bordered">
<TableHead>
<TableRow>
<TableCell align="left" variant="header" scope="col">
{columns.name}
</TableCell>

{columns.additionalColumns?.map(({ label, value }) => (
<TableCell key={value} align="left" variant="header" scope="col">
{label}
</TableCell>
))}

<TableCell align="left" variant="header" scope="col">
{columns.availability.label}
</TableCell>

<TableCell align="right" variant="header" scope="col">
{columns.price}
</TableCell>

<TableCell align="left" variant="header" scope="col">
{columns.quantitySelector}
</TableCell>
</TableRow>
</TableHead>

<TableBody>
{loading ? (
<>
{Array.from({ length: 5 }).map((_, index) => {
return (
<TableRow key={`table-row-${index}`}>
{Array.from({
length: totalColumnsSkeletonLength,
}).map((_, index) => {
return (
<TableCell key={`table-cell-${index}`}>
<span>
<Skeleton
key={index}
size={{ width: '100%', height: '30px' }}
/>
</span>
</TableCell>
)
})}
</TableRow>
)
})}
</>
) : (
<>
{allVariantProducts.map((variantProduct) => (
<TableRow key={`${variantProduct.name}-${variantProduct.id}`}>
<TableCell data-fs-sku-matrix-sidebar-cell-image align="left">
<div>
<Image
src={variantProduct.image.url}
alt={variantProduct.image.alternateName}
width={48}
height={48}
/>
</div>
{variantProduct.name}
</TableCell>

{columns.additionalColumns?.map(({ value }) => (
<TableCell
key={`${variantProduct.name}-${variantProduct.id}-${value}`}
align="left"
>
{variantProduct.specifications[value.toLowerCase()]}
</TableCell>
))}

<TableCell align="left">
{columns.availability.stockDisplaySettings ===
'showAvailability' && (
<Badge
variant={
variantProduct.availability === 'outofstock'
? 'warning'
: 'success'
}
>
{variantProduct.availability === 'outofstock'
? 'Out of stock'
: 'Available'}
</Badge>
)}

{columns.availability.stockDisplaySettings ===
'showStockQuantity' && variantProduct.inventory}
</TableCell>

<TableCell align="right">
<div data-fs-sku-matrix-sidebar-table-price>
<Price
value={variantProduct.price}
variant="spot"
formatter={formatter}
/>
</div>
</TableCell>

<TableCell
align="right"
data-fs-sku-matrix-sidebar-table-cell-quantity-selector
>
<div data-fs-sku-matrix-sidebar-table-action>
<QuantitySelector
min={0}
max={variantProduct.inventory}
disabled={
!variantProduct.inventory ||
variantProduct.availability === 'outOfStock'
}
initial={variantProduct.selectedCount}
onChange={(value) =>
handleQuantitySelectorChange(variantProduct.id, value)
}
onValidateBlur={(
min: number,
maxValue: number,
quantity: number
) => {
pushToast({
title: 'Invalid quantity!',
message: `The quantity you entered is outside the range of ${min} to ${maxValue}. The quantity was set to ${quantity}.`,
status: 'INFO',
icon: (
<Icon
name="CircleWavyWarning"
width={30}
height={30}
/>
),
})
}}
/>
</div>
</TableCell>
</TableRow>
))}
</>
)}
</TableBody>
</Table>

<footer data-fs-sku-matrix-sidebar-footer>
<div>
<p>
{cartDetails.amount} {cartDetails.amount !== 1 ? 'Items' : 'Item'}
</p>
<Price
value={cartDetails.subtotal}
variant="spot"
formatter={formatter}
/>
</div>

<Button
variant="primary"
disabled={!cartDetails.amount}
onClick={handleAddToCart}
{...buyProps}
>
Add to Cart
</Button>
</footer>
</SlideOver>
)
}

export default SKUMatrixSidebar
Loading