diff --git a/.changeset/composable-product-details.md b/.changeset/composable-product-details.md
new file mode 100644
index 00000000..a3ad0cc9
--- /dev/null
+++ b/.changeset/composable-product-details.md
@@ -0,0 +1,5 @@
+---
+'@godaddy/gd-commerce-storefront': minor
+---
+
+Add composable product parts. `ProductDetailsRoot` with display parts (`ProductDetailsGallery`, `ProductDetailsTitle`, `ProductDetailsPrice`, `ProductDetailsDescription`, `ProductDetailsBackLink`) and purchase parts (`ProductDetailsPurchase`, `ProductDetailsOptions`, `ProductDetailsOption`, `ProductDetailsPurchaseStatus`, `ProductDetailsAvailability`, `ProductDetailsQuantity`, `ProductDetailsAddToCart`) build custom product layouts. `useProductDetails` reads product state and `useProductDetailsOption` builds custom option controls. Only server-verified SKUs can be added in any layout. `ProductDetails` is now composed from these parts and is visually unchanged. Its markup gains wrapper elements, and the disabled add button now gets its accessible description from a hidden reason element.
diff --git a/packages/commerce-storefront/README.md b/packages/commerce-storefront/README.md
index 0f8ec793..574c718d 100644
--- a/packages/commerce-storefront/README.md
+++ b/packages/commerce-storefront/README.md
@@ -84,9 +84,9 @@ A connection failure leaves the surrounding application and its state mounted. C
The stylesheet includes all required utilities and scopes them to the package's surfaces. The build removes CSS layer wrappers in their declared order, so the exported CSS can pass through a host Tailwind v3 PostCSS pipeline without `@tailwind` directives. Import it directly; consumers do not need to copy or rewrite the CSS. It does not add a global reset or require dependency scanning by a host Tailwind build. The `theme` prop reaches the drawer even though it is portalled into `document.body`.
-By default, `.commerce-storefront` wrappers do not paint a background and inherit the host's text color. Set page and section backgrounds on the host application's layout elements. `--commerce-surface` colors controls and the opaque cart drawer, and supplies the base for muted colors; it does not color component wrappers. Set `--commerce-surface` and `--commerce-text` together to adapt controls and the drawer to a dark theme. Avoid setting wrapper backgrounds through CSS or the `theme` prop's `background`, `backgroundColor`, or `backgroundImage` properties, which can still override the transparent default. Descendants inherit the surface text and body font instead of global heading styles. Keep text, controls and focus indicators accessible when changing colors. Utility class names and internal markup are not a customization API.
+By default, `.commerce-storefront` wrappers do not paint a background and inherit the host's text color. Set page and section backgrounds on the host application's layout elements. `--commerce-surface` colors controls and the opaque cart drawer, and supplies the base for muted colors; it does not color component wrappers. Set `--commerce-surface` and `--commerce-text` together to adapt controls and the drawer to a dark theme. Avoid setting wrapper backgrounds through CSS or the `theme` prop's `background`, `backgroundColor`, or `backgroundImage` properties, which can still override the transparent default. Descendants inherit the surface text and body font instead of global heading styles. Keep text, controls and focus indicators accessible when changing colors. Internal utility class names and markup are not a customization API; use the [product parts](#custom-product-layouts) to change a product page's layout.
-The first release uses English UI text and `en-US` currency formatting. Catalog title and description are configurable. Full localization and arbitrary component slots are outside this initial API.
+The first release uses English UI text and `en-US` currency formatting. Catalog title and description are configurable. Full localization is outside this initial API.
## Compatibility
@@ -101,6 +101,7 @@ The repository example uses React Router 7. Follow each router version's own Rea
| `CommerceStorefront` | Recommended integration: provider and one drawer |
| `Catalog` | Six products per cursor page, with `title`, `description`, and `showHeader` props |
| `ProductDetails` | Reads `:productId`; validates URL option selections against catalog results |
+| `ProductDetailsRoot` and product parts | Build a [custom product layout](#custom-product-layouts) with the same rules as `ProductDetails` |
| `ProductCard` | Renders one `SKUGroup` with direct add or a product-details link |
| `CartButton` | Opens the shared drawer and displays item count |
| `AddToCartButton` | Adds a verified `sku`, `name`, and optional integer `quantity` |
@@ -112,6 +113,71 @@ The package exports TypeScript catalog/cart response types and selection/summary
`Catalog` renders its `title` as an H1 by default. When the host page owns its semantic heading, render that page H1 and pass `showHeader={false}` so the document still has exactly one H1.
+## Custom product layouts
+
+`ProductDetails` is the recommended product page. When its layout does not fit, compose the same parts inside `ProductDetailsRoot`. The root loads the route's `:productId` and shows the connection, loading, error and not-found states itself, so parts render only once the product exists. This is the packaged layout, written out:
+
+```tsx
+import {
+ ProductDetailsBackLink, ProductDetailsDescription, ProductDetailsGallery, ProductDetailsPrice,
+ ProductDetailsPurchase, ProductDetailsRoot, ProductDetailsTitle,
+} from '@godaddy/gd-commerce-storefront';
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+The grid, spacing and border classes come from your own stylesheet in a custom layout. Without them, the parts stack in one column with no space between them.
+
+Add your own elements between parts, reorder them, or leave out display parts. `ProductDetailsPurchase` renders the purchase parts below in order. Replace it with individual parts to place options apart from the add button:
+
+| Part | Renders |
+| --- | --- |
+| `ProductDetailsOptions` | A select for every attribute, or the SKU list for products without attributes |
+| `ProductDetailsOption` | A select for one attribute, by `attribute` name; nothing when the product lacks it |
+| `ProductDetailsPurchaseStatus` | The one message explaining why the selection is not purchasable yet; nothing when ready |
+| `ProductDetailsAvailability`, `ProductDetailsQuantity` | Stock and quantity for the verified SKU; nothing before verification |
+| `ProductDetailsAddToCart` | Adds the verified SKU and quantity; before a SKU is verified, its accessible description gives the reason |
+
+Every part is named `ProductDetails*` because it works only inside `ProductDetailsRoot`. `AddToCartButton` is the standalone button for a SKU you already have.
+
+Parts read state from the root and take no product, SKU, price or quantity props. Whatever the layout, only a server-verified SKU can be added, and changing a selection resets the quantity and image. Every part throws if it is rendered outside `ProductDetailsRoot`. In development builds, if no control is rendered for an attribute the product requires, a console warning names the missing ones. A control that mounts later, such as one in a closed accordion, can trigger it; the product becomes purchasable once the control renders. Products without attributes but with several SKUs need `ProductDetailsOptions` or `ProductDetailsPurchase`. Parts can be rendered more than once, such as in a sticky mobile purchase bar; each copy gets its own element IDs.
+
+Every part accepts `className`, which is added to the part's outer element, a wrapper the package's CSS reset leaves alone. Host classes there control margin, padding, border, color, width and grid placement, including layered utilities such as Tailwind v4's. The packaged layout sets its spacing and grid placement this way. Elements inside the part, such as the title's `
`, keep the package's own styles: a host font size on `ProductDetailsTitle` does not change the heading's size, but a host color does reach it, because the heading inherits its color.
+
+Two hooks support custom parts inside the root:
+
+- `useProductDetails()` returns read-only `product`, `name`, `selectedSku`, `quantity`, `availableQuantity`, `images` and `status` (`incomplete`, `checking`, `variant-error`, `unavailable`, `not-purchasable` or `ready`). `selectedSku` is set only when `status` is `ready`.
+- `useProductDetailsOption(attribute)` returns `{ name, label, selected, values, select }` for building swatches or buttons, or `null` when the product has no such attribute. `select(value)` accepts only that attribute's value names, or `null` to clear. Other values are ignored. A hook-based control counts toward the layout check.
+
+```tsx
+function ColorSwatches() {
+ const color = useProductDetailsOption('color');
+ if (!color) return null;
+ return (
+
+ {color.values.map((value) => (
+
+ ))}
+
+ );
+}
+```
+
+Parts are flat named exports, not properties such as `ProductDetails.Title`, so each one is an ordinary module export.
+
## How it works
Products are SKU groups. The package purchases only an unambiguous SKU, verifies all selected attributes through the server, uses SKU prices/images, and distinguishes untracked inventory from sold-out inventory. Server-side inventory and pricing checks remain mandatory.
diff --git a/packages/commerce-storefront/src/artifacts.test.ts b/packages/commerce-storefront/src/artifacts.test.ts
index bea80de5..bea3409f 100644
--- a/packages/commerce-storefront/src/artifacts.test.ts
+++ b/packages/commerce-storefront/src/artifacts.test.ts
@@ -57,13 +57,13 @@ it('inherits host text without painting wrappers while retaining opaque themed c
});
expect(controlDeclarations['background-color']).toBe('var(--commerce-surface, #fff)');
const resets: Record = {};
- css.walkRules('.commerce-storefront :where(*)', (rule) => {
+ css.walkRules('.commerce-storefront :where(*:not(.commerce-part))', (rule) => {
rule.walkDecls((declaration) => {
resets[declaration.prop] = declaration.value;
});
});
expect(resets).toMatchObject({ color: 'inherit', 'font-family': 'inherit' });
- expect(css.toString().indexOf('.commerce-storefront :where(*)')).toBeLessThan(
+ expect(css.toString().indexOf('.commerce-storefront :where(*:not(.commerce-part))')).toBeLessThan(
css.toString().indexOf('.commerce-storefront .text-commerce-on-accent'),
);
});
diff --git a/packages/commerce-storefront/src/index.ts b/packages/commerce-storefront/src/index.ts
index 43a74992..0f467289 100644
--- a/packages/commerce-storefront/src/index.ts
+++ b/packages/commerce-storefront/src/index.ts
@@ -20,5 +20,33 @@ export {
useCommerce,
} from './commerce-provider';
export { CommerceStorefront } from './commerce-storefront';
-export { ProductDetails } from './product-details';
+export {
+ ProductDetails,
+ ProductDetailsBackLink,
+ ProductDetailsDescription,
+ ProductDetailsGallery,
+ ProductDetailsPrice,
+ ProductDetailsTitle,
+} from './product-details';
+export {
+ type ProductDetailsOptionState,
+ type ProductDetailsOptionValueState,
+ type ProductDetailsPartProps,
+ ProductDetailsRoot,
+ type ProductDetailsRootProps,
+ type ProductDetailsState,
+ type ProductDetailsStatus,
+ useProductDetails,
+ useProductDetailsOption,
+} from './product-details-context';
+export {
+ ProductDetailsAddToCart,
+ ProductDetailsAvailability,
+ ProductDetailsOption,
+ type ProductDetailsOptionProps,
+ ProductDetailsOptions,
+ ProductDetailsPurchase,
+ ProductDetailsPurchaseStatus,
+ ProductDetailsQuantity,
+} from './product-purchase';
export { CommerceStatus } from './storefront-surface';
diff --git a/packages/commerce-storefront/src/product-details-context.tsx b/packages/commerce-storefront/src/product-details-context.tsx
new file mode 100644
index 00000000..0db97811
--- /dev/null
+++ b/packages/commerce-storefront/src/product-details-context.tsx
@@ -0,0 +1,322 @@
+import { useQuery } from '@tanstack/react-query';
+import {
+ createContext,
+ type ReactElement,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
+import { Link, useParams, useSearchParams } from 'react-router';
+import { ApiError, message, request } from './api';
+import { buttonClass } from './cart';
+import {
+ getAvailableInventoryQuantity,
+ getImageUrls,
+ getLabeledSkuOptions,
+ getProductAttributes,
+ getSingleMatchedSku,
+ type SKU,
+ type SKUGroup,
+ type SKUPrice,
+ type SkuGroupResult,
+ type StorefrontProductAttribute,
+} from './catalog-model';
+import { useCommerce } from './commerce-provider';
+import { CommerceStatus, StorefrontSurface } from './storefront-surface';
+
+/** Where the shopper is in choosing a purchasable SKU. Only `ready` has a verified `selectedSku`. */
+export type ProductDetailsStatus =
+ | 'incomplete'
+ | 'checking'
+ | 'variant-error'
+ | 'unavailable'
+ | 'not-purchasable'
+ | 'ready';
+
+/** Read-only product state for custom parts rendered inside `ProductDetailsRoot`. */
+export interface ProductDetailsState {
+ readonly product: SKUGroup;
+ readonly name: string;
+ /** Set only after the server verifies the full selection. */
+ readonly selectedSku: SKU | null;
+ readonly quantity: number;
+ /** `null` means inventory is not tracked; `0` means sold out. */
+ readonly availableQuantity: number | null;
+ readonly status: ProductDetailsStatus;
+ readonly images: readonly string[];
+}
+
+interface ProductDetailsInternal extends ProductDetailsState {
+ attributes: StorefrontProductAttribute[];
+ selections: string[];
+ skuOptions: SKU[];
+ explicitSkuId: string;
+ price: SKUPrice | null | undefined;
+ imageIndex: number;
+ variantError: unknown;
+ setImageIndex: (index: number) => void;
+ setQuantity: (quantity: number) => void;
+ selectOption: (attribute: string, value: string) => void;
+ selectSku: (skuId: string) => void;
+ retryVariant: () => void;
+ register: (control: string) => () => void;
+}
+
+/** Props shared by every product part. `className` is added to the part's outer element. */
+export interface ProductDetailsPartProps {
+ className?: string;
+}
+
+export const cx = (...classes: Array): string => classes.filter(Boolean).join(' ');
+
+/** Classes for the element that receives a part's `className`. The package CSS reset skips `commerce-part`. */
+export const partClass = (...classes: Array): string => cx('commerce-part', ...classes);
+
+const ProductDetailsContext = createContext(null);
+
+export function useProductDetailsInternal(part: string): ProductDetailsInternal {
+ const context = useContext(ProductDetailsContext);
+ if (!context) throw new Error(`${part} must be rendered inside .`);
+ return context;
+}
+
+/** Read the current product, verified SKU, and purchase status from inside `ProductDetailsRoot`. */
+export function useProductDetails(): ProductDetailsState {
+ const { product, name, selectedSku, quantity, availableQuantity, status, images } =
+ useProductDetailsInternal('useProductDetails');
+ return { product, name, selectedSku, quantity, availableQuantity, status, images };
+}
+
+export interface ProductDetailsOptionValueState {
+ readonly name: string;
+ readonly label: string;
+ readonly selected: boolean;
+}
+
+export interface ProductDetailsOptionState {
+ readonly name: string;
+ readonly label: string;
+ readonly selected: string | null;
+ readonly values: readonly ProductDetailsOptionValueState[];
+ /** Accepts only this attribute's own value names, or `null` to clear. Other values are ignored. */
+ readonly select: (value: string | null) => void;
+}
+
+/**
+ * Build a custom control for one product attribute. Returns `null` when the product has no such attribute.
+ * A selection is never purchasable until the server verifies it.
+ */
+export function useProductDetailsOption(attribute: string): ProductDetailsOptionState | null {
+ const { attributes, selections, selectOption, register } =
+ useProductDetailsInternal('useProductDetailsOption');
+ useEffect(() => register(`attribute:${attribute}`), [attribute, register]);
+ const index: number = attributes.findIndex((candidate) => candidate.name === attribute);
+ const match: StorefrontProductAttribute | undefined = attributes[index];
+ if (!match) return null;
+ const selected: string | null = selections[index] || null;
+ return {
+ name: match.name,
+ label: match.label,
+ selected,
+ values: match.values.map((value) => ({
+ name: value.name,
+ label: value.label,
+ selected: value.name === selected,
+ })),
+ select: (value: string | null): void => {
+ if (value === null) selectOption(attribute, '');
+ else if (match.values.some((candidate) => candidate.name === value)) selectOption(attribute, value);
+ },
+ };
+}
+
+/** Register the explicit SKU control so the layout check knows SKU-list products can be completed. */
+export function useSkuOptionRegistration(): void {
+ const { register } = useProductDetailsInternal('ProductDetailsOptions');
+ useEffect(() => register('sku'), [register]);
+}
+
+export interface ProductDetailsRootProps {
+ children: ReactNode;
+ /** Added to the root ``. */
+ className?: string;
+}
+
+/** Loads the product for the route's `:productId` and provides state to product parts. */
+export function ProductDetailsRoot({ children, className }: ProductDetailsRootProps): ReactElement {
+ const { productId = '' } = useParams();
+ const { connection } = useCommerce();
+ return (
+
+ {connection === 'ready' ? (
+
+ {children}
+
+ ) : (
+
+ )}
+
+ );
+}
+
+function ProductDetailsLoader({
+ productId,
+ className,
+ children,
+}: ProductDetailsRootProps & { productId: string }): ReactElement {
+ const { config } = useCommerce();
+ const [params, setParams] = useSearchParams();
+ const [quantity, setQuantity] = useState(1);
+ const [imageIndex, setImageIndex] = useState(0);
+ const product = useQuery({
+ retry: false,
+ queryKey: ['commerce', config.cartScope, 'product', productId],
+ queryFn: ({ signal }) =>
+ request(`/products/${encodeURIComponent(productId)}`, {
+ signal,
+ headers: { 'X-Commerce-Scope': config.cartScope },
+ }),
+ });
+ const productNotFound: boolean =
+ product.isError && product.error instanceof ApiError && product.error.status === 404;
+ const group = product.data?.skuGroup;
+ const attributes = getProductAttributes(group);
+ const skuOptions: SKU[] = getLabeledSkuOptions(group);
+ const explicitSku: SKU | undefined = skuOptions.find((sku: SKU): boolean => sku.id === params.get('sku'));
+ const selections: string[] = attributes.map((attribute) => params.get(`option.${attribute.name}`) ?? '');
+ const complete: boolean =
+ skuOptions.length > 0
+ ? !!explicitSku
+ : attributes.every((attribute, index) =>
+ attribute.values.some((value) => value.name === selections[index]),
+ );
+ const selectionParams: URLSearchParams = new URLSearchParams();
+ selections.filter(Boolean).forEach((value) => {
+ selectionParams.append('attributeValues', value);
+ });
+ const matched = useQuery({
+ retry: false,
+ queryKey: ['commerce', config.cartScope, 'product-variants', productId, selections],
+ queryFn: ({ signal }) =>
+ request(`/products/${encodeURIComponent(productId)}?${selectionParams}`, {
+ signal,
+ headers: { 'X-Commerce-Scope': config.cartScope },
+ }),
+ enabled: !!group && attributes.length > 0 && complete,
+ });
+ const selectionVerified: boolean =
+ complete &&
+ product.isSuccess &&
+ !product.isFetching &&
+ (attributes.length === 0 || (matched.isSuccess && !matched.isFetching));
+ const selectedSku: SKU | null = selectionVerified
+ ? (explicitSku ?? getSingleMatchedSku(attributes.length ? matched.data?.skuGroup : group))
+ : null;
+ const status: ProductDetailsStatus = !complete
+ ? 'incomplete'
+ : matched.isError && !matched.isFetching
+ ? 'variant-error'
+ : !selectionVerified
+ ? 'checking'
+ : selectedSku
+ ? 'ready'
+ : attributes.length
+ ? 'unavailable'
+ : 'not-purchasable';
+ const selectedImages: string[] = getImageUrls(selectedSku);
+ const images: string[] = [...new Set(selectedImages.length ? selectedImages : getImageUrls(group))];
+ const changeSelection = (key: string, value: string): void => {
+ const next: URLSearchParams = new URLSearchParams(params);
+ if (value) next.set(key, value);
+ else next.delete(key);
+ setParams(next);
+ setQuantity(1);
+ setImageIndex(0);
+ };
+ const registered = useRef