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

Keep entire selected choice object in route state #81

Merged
merged 4 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
45 changes: 26 additions & 19 deletions app/routes/products.$productSlug/route.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { LinksFunction, LoaderFunctionArgs, MetaFunction } from '@remix-run/node';
import { isRouteErrorResponse, json, useLoaderData, useNavigate, useRouteError } from '@remix-run/react';
import type { products } from '@wix/stores';
import classNames from 'classnames';
import { useRef, useState } from 'react';
import { useAddToCart } from '~/api/api-hooks';
Expand All @@ -11,9 +12,16 @@ import { ProductAdditionalInfo } from '~/components/product-additional-info/prod
import { ProductImages } from '~/components/product-images/product-images';
import { ProductOption } from '~/components/product-option/product-option';
import { UnsafeRichText } from '~/components/rich-text/rich-text';
import { getChoiceValue } from '~/components/product-option/product-option-utils';
import { ROUTES } from '~/router/config';
import { getErrorMessage, getPriceData, getSelectedVariant, getSKU, getUrlOriginWithPath, isOutOfStock } from '~/utils';
import {
getErrorMessage,
getPriceData,
selectedChoicesToChoiceValues,
getSelectedVariant,
getSKU,
getUrlOriginWithPath,
isOutOfStock,
} from '~/utils';
import { AddToCartOptions, EcomApiErrorCodes } from '~/api/types';
import styles from './product-details.module.scss';

Expand All @@ -38,40 +46,39 @@ export default function ProductDetailsPage() {
const { trigger: addToCart } = useAddToCart();
const quantityInput = useRef<HTMLInputElement>(null);

const getInitialSelectedOptions = () => {
const result: Record<string, string | undefined> = {};
const getInitialSelectedChoices = () => {
const result: Record<string, products.Choice | undefined> = {};
for (const option of product.productOptions ?? []) {
if (option.name) {
const initialChoice = option?.choices?.length === 1 ? option.choices[0] : undefined;
result[option.name] = getChoiceValue(option, initialChoice);
result[option.name] = option?.choices?.length === 1 ? option.choices[0] : undefined;
}
}

return result;
};

const [selectedOptions, setSelectedOptions] = useState<Record<string, string | undefined>>(
getInitialSelectedOptions()
const [selectedChoices, setSelectedChoices] = useState<Record<string, products.Choice | undefined>>(
getInitialSelectedChoices()
);

const outOfStock = isOutOfStock(product, selectedOptions);
const priceData = getPriceData(product, selectedOptions);
const sku = getSKU(product, selectedOptions);
const outOfStock = isOutOfStock(product, selectedChoices);
const priceData = getPriceData(product, selectedChoices);
const sku = getSKU(product, selectedChoices);

async function addToCartHandler() {
if (!product?._id || outOfStock) {
return;
}

setAddToCartAttempted(true);
if (Object.values(selectedOptions).includes(undefined)) {
if (Object.values(selectedChoices).includes(undefined)) {
return;
}

const quantity = parseInt(quantityInput.current?.value ?? '1', 10);
const selectedVariant = getSelectedVariant(product, selectedOptions);
const selectedVariant = getSelectedVariant(product, selectedChoices);

let options: AddToCartOptions = { options: selectedOptions };
let options: AddToCartOptions = { options: selectedChoicesToChoiceValues(product, selectedChoices) };
if (product.manageVariants && selectedVariant?._id) {
options = { variantId: selectedVariant._id };
}
Expand Down Expand Up @@ -114,16 +121,16 @@ export default function ProductDetailsPage() {
<ProductOption
key={option.name}
error={
addToCartAttempted && selectedOptions[option.name!] === undefined
addToCartAttempted && selectedChoices[option.name!] === undefined
? `Select ${option.name}`
: undefined
}
option={option}
selectedValue={selectedOptions[option.name!]}
onChange={(value) => {
setSelectedOptions((prev) => ({
selectedChoice={selectedChoices[option.name!]}
onChange={(newSelectedChoice) => {
setSelectedChoices((prev) => ({
...prev,
[option.name!]: value,
[option.name!]: newSelectedChoice,
}));
}}
/>
Expand Down
16 changes: 0 additions & 16 deletions src/components/product-option/product-option-utils.ts

This file was deleted.

27 changes: 18 additions & 9 deletions src/components/product-option/product-option.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
import { products } from '@wix/stores';
import { ColorSelect } from '~/components/color-select/color-select';
import { Select } from '~/components/select/select';
import { getChoiceValue } from './product-option-utils';
import styles from './product-option.module.scss';
import { getChoiceValue } from '~/utils';

export interface ProductOptionProps {
option: products.ProductOption;
selectedValue: string | undefined;
selectedChoice: products.Choice | undefined;
error: string | undefined;
onChange: (value: string) => void;
onChange: (value: products.Choice) => void;
}

export const ProductOption = ({ option, selectedValue, error, onChange }: ProductOptionProps) => {
export const ProductOption = ({ option, selectedChoice, error, onChange }: ProductOptionProps) => {
const { name, optionType, choices } = option;

if (name === undefined || choices === undefined) {
return null;
}

const selectedChoice = choices.find((c) => getChoiceValue(option, c) === selectedValue);
const handleChange = (value: string) => {
if (!optionType) {
return;
}

const newSelectedChoice = choices.find((c) => getChoiceValue(optionType, c) === value);
if (newSelectedChoice) {
onChange(newSelectedChoice);
}
};

return (
<div className={styles.root}>
Expand All @@ -36,8 +45,8 @@ export const ProductOption = ({ option, selectedValue, error, onChange }: Produc
name: c.description!,
hexValue: c.value!,
}))}
onChange={onChange}
selectedName={selectedValue}
onChange={handleChange}
selectedName={selectedChoice?.description}
/>
) : (
<Select
Expand All @@ -48,9 +57,9 @@ export const ProductOption = ({ option, selectedValue, error, onChange }: Produc
name: c.description!,
value: c.value!,
}))}
value={selectedValue}
value={selectedChoice?.value}
placeholder={`Select ${name}`}
onChange={onChange}
onChange={handleChange}
/>
)}
{error !== undefined && <div className={styles.error}>{error}</div>}
Expand Down
43 changes: 35 additions & 8 deletions src/utils/product-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { Product } from '~/api/types';

export function isOutOfStock(
product: Product | SerializeFrom<Product>,
selectedOptions: Record<string, string | undefined> = {}
selectedChoices: Record<string, wixStoresProducts.Choice | undefined> = {}
): boolean {
if (product.manageVariants) {
const selectedVariant = getSelectedVariant(product, selectedOptions);
const selectedVariant = getSelectedVariant(product, selectedChoices);
if (selectedVariant?.stock?.trackQuantity === true) {
return selectedVariant?.stock?.quantity === 0;
} else {
Expand All @@ -21,10 +21,10 @@ export function isOutOfStock(

export function getPriceData(
product: Product | SerializeFrom<Product>,
selectedOptions: Record<string, string | undefined> = {}
selectedChoices: Record<string, wixStoresProducts.Choice | undefined> = {}
): Product['priceData'] {
if (product.manageVariants) {
const selectedVariant = getSelectedVariant(product, selectedOptions);
const selectedVariant = getSelectedVariant(product, selectedChoices);
return selectedVariant?.variant?.priceData ?? product.priceData;
}

Expand All @@ -33,10 +33,10 @@ export function getPriceData(

export function getSKU(
product: Product | SerializeFrom<Product>,
selectedOptions: Record<string, string | undefined> = {}
selectedChoices: Record<string, wixStoresProducts.Choice | undefined> = {}
): Product['sku'] {
if (product.manageVariants) {
const selectedVariant = getSelectedVariant(product, selectedOptions);
const selectedVariant = getSelectedVariant(product, selectedChoices);
return selectedVariant?.variant?.sku ?? product.sku;
}

Expand All @@ -45,7 +45,34 @@ export function getSKU(

export function getSelectedVariant(
product: Product | SerializeFrom<Product>,
selectedOptions: Record<string, string | undefined> = {}
selectedChoices: Record<string, wixStoresProducts.Choice | undefined> = {}
): wixStoresProducts.Variant | undefined {
return product.variants?.find((variant) => deepEqual(variant.choices, selectedOptions));
const selectedChoiceValues = selectedChoicesToChoiceValues(product, selectedChoices);
return product.variants?.find((variant) => deepEqual(variant.choices, selectedChoiceValues));
}

export const getChoiceValue = (optionType: wixStoresProducts.OptionType, choice: wixStoresProducts.Choice) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please explicitly define return type as string

// for color options, `description` field contains color name
// and `value` field contains hex color representation
return optionType === wixStoresProducts.OptionType.color ? choice.description : choice.value;
};

export const selectedChoicesToChoiceValues = (
product: Product | SerializeFrom<Product>,
selectedChoices: Record<string, wixStoresProducts.Choice | undefined> = {}
) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return type

const result: Record<string, string | undefined> = {};
for (const [optionName, choice] of Object.entries(selectedChoices)) {
if (!choice) {
result[optionName] = undefined;
continue;
}

const option = product.productOptions?.find((option) => option.name === optionName);
if (!option?.optionType) continue;

result[optionName] = getChoiceValue(option.optionType, choice);
}

return result;
};