Add React editor project

This commit is contained in:
Rami Bitar
2026-08-09 16:00:10 -04:00
parent 909d99251a
commit 63ecc5e284
212 changed files with 20655 additions and 11571 deletions
-15
View File
@@ -1,15 +0,0 @@
"use client";
import { useParams } from "next/navigation";
/**
* Returns the dynamic handle of the current route, e.g. the `cool-shirt` in
* `/products/cool-shirt` (or its `/products/cool-shirt/editor` editor view).
* Both the public and editor routes share the same `[handle]` segment, so the
* value is identical in either context.
*/
export function useRouteSegment(): string | undefined {
const params = useParams();
const handle = params?.handle;
return typeof handle === "string" ? handle : undefined;
}
+345 -68
View File
@@ -1,15 +1,18 @@
'use client';
import { useContext } from 'react';
import { shopifyFetch, SHOPIFY_STORE_DOMAIN } from '@/services/shopify/client';
import { CartContext } from '@/contexts/shopify-context';
import { create } from 'zustand';
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
import {
CREATE_CART_MUTATION,
ADD_CART_LINES_MUTATION,
UPDATE_CART_LINES_MUTATION,
REMOVE_CART_LINES_MUTATION,
UPDATE_CART_DISCOUNT_CODES_MUTATION,
GET_CART_QUERY,
} from '@/graphql/cart';
import { useEffect } from 'react';
// ─── Types ───────────────────────────────────────────────────────────
export interface CartLineInput {
merchandiseId: string;
@@ -42,12 +45,12 @@ interface CartLine {
currencyCode: string;
};
image?: {
id: string;
id?: string | null;
url: string;
altText?: string;
width: number;
height: number;
};
altText?: string | null;
width?: number | null;
height?: number | null;
} | null;
product: {
id: string;
title: string;
@@ -57,10 +60,16 @@ interface CartLine {
};
}
export interface CartDiscountCode {
code: string;
applicable: boolean;
}
export interface Cart {
id: string;
checkoutUrl: string;
totalQuantity: number;
discountCodes?: CartDiscountCode[];
cost: {
subtotalAmount: {
amount: string;
@@ -73,7 +82,7 @@ export interface Cart {
totalTaxAmount?: {
amount: string;
currencyCode: string;
};
} | null;
};
lines: {
edges: Array<{
@@ -82,84 +91,352 @@ export interface Cart {
};
}
// Create a new cart (optionally with initial items)
export async function createCart(lines: CartLineInput[] = []): Promise<Cart> {
const response = await shopifyFetch({
query: CREATE_CART_MUTATION,
variables: { lines: lines.length > 0 ? lines : null },
});
// ─── Shopify API functions ───────────────────────────────────────────
if (response.data.cartCreate.userErrors.length > 0) {
throw new Error(response.data.cartCreate.userErrors[0].message);
/**
* Every cart mutation returns the same `{ cart, userErrors }` payload, and both
* the payload and the cart inside it are nullable — Shopify returns no cart when
* the mutation could not be applied. Callers want a cart or an exception.
*/
function unwrapCartPayload<T>(
payload:
| {
cart?: T | null;
userErrors: ReadonlyArray<{ message: string }>;
}
| null
| undefined
): T {
if (payload?.userErrors.length) {
throw new Error(payload.userErrors[0].message);
}
return response.data.cartCreate.cart;
}
// Add items to cart
export async function addCartLines(cartId: string, lines: CartLineInput[]): Promise<Cart> {
const response = await shopifyFetch({
query: ADD_CART_LINES_MUTATION,
variables: { cartId, lines },
});
if (response.data.cartLinesAdd.userErrors.length > 0) {
throw new Error(response.data.cartLinesAdd.userErrors[0].message);
if (!payload?.cart) {
throw new Error('Cart update failed. Please try again.');
}
return response.data.cartLinesAdd.cart;
return payload.cart;
}
// Update cart line quantities
export async function updateCartLines(cartId: string, lines: CartLineUpdateInput[]): Promise<Cart> {
const response = await shopifyFetch({
query: UPDATE_CART_LINES_MUTATION,
variables: { cartId, lines },
});
async function createCartApi(lines: CartLineInput[] = []): Promise<Cart> {
const data = unwrapStorefrontResult(
await storefront.graphql(CREATE_CART_MUTATION, {
variables: { lines: lines.length > 0 ? lines : null },
}),
'CreateCart'
);
if (response.data.cartLinesUpdate.userErrors.length > 0) {
throw new Error(response.data.cartLinesUpdate.userErrors[0].message);
}
return response.data.cartLinesUpdate.cart;
return unwrapCartPayload(data.cartCreate);
}
// Remove items from cart
export async function removeCartLines(cartId: string, lineIds: string[]): Promise<Cart> {
const response = await shopifyFetch({
query: REMOVE_CART_LINES_MUTATION,
variables: { cartId, lineIds },
});
async function addCartLinesApi(
cartId: string,
lines: CartLineInput[]
): Promise<Cart> {
const data = unwrapStorefrontResult(
await storefront.graphql(ADD_CART_LINES_MUTATION, {
variables: { cartId, lines },
}),
'AddCartLines'
);
if (response.data.cartLinesRemove.userErrors.length > 0) {
throw new Error(response.data.cartLinesRemove.userErrors[0].message);
}
return response.data.cartLinesRemove.cart;
return unwrapCartPayload(data.cartLinesAdd);
}
// Get cart by ID
export async function getCart(cartId: string): Promise<Cart | null> {
const response = await shopifyFetch({
query: GET_CART_QUERY,
variables: { cartId },
});
async function updateCartLinesApi(
cartId: string,
lines: CartLineUpdateInput[]
): Promise<Cart> {
const data = unwrapStorefrontResult(
await storefront.graphql(UPDATE_CART_LINES_MUTATION, {
variables: { cartId, lines },
}),
'UpdateCartLines'
);
return response.data.cart;
return unwrapCartPayload(data.cartLinesUpdate);
}
async function removeCartLinesApi(
cartId: string,
lineIds: string[]
): Promise<Cart> {
const data = unwrapStorefrontResult(
await storefront.graphql(REMOVE_CART_LINES_MUTATION, {
variables: { cartId, lineIds },
}),
'RemoveCartLines'
);
return unwrapCartPayload(data.cartLinesRemove);
}
async function updateCartDiscountCodesApi(
cartId: string,
discountCodes: string[]
): Promise<Cart> {
const data = unwrapStorefrontResult(
await storefront.graphql(UPDATE_CART_DISCOUNT_CODES_MUTATION, {
variables: { cartId, discountCodes },
}),
'UpdateCartDiscountCodes'
);
return unwrapCartPayload(data.cartDiscountCodesUpdate);
}
async function getCartApi(cartId: string): Promise<Cart | null> {
const data = unwrapStorefrontResult(
await storefront.graphql(GET_CART_QUERY, { variables: { cartId } }),
'GetCart'
);
return data.cart;
}
// Redirect to Shopify checkout
export function redirectToCheckout(checkoutUrl: string): void {
if (checkoutUrl) {
window.location.href = checkoutUrl;
}
}
// Hook to access cart context
export const useShopifyCart = () => {
const context = useContext(CartContext);
if (!context) {
throw new Error('useShopifyCart must be used within a ShopifyProvider');
}
return context;
};
// ─── Zustand Store ───────────────────────────────────────────────────
const CART_ID_KEY = 'cartId';
interface CartState {
// State
isOpen: boolean;
cartId: string | null;
cart: Cart | null;
loading: boolean;
error: string | null;
_initialized: boolean;
// Computed (derived in the hook)
// items, itemCount, totalAmount, checkoutUrl
// Actions
openCart: () => void;
closeCart: () => void;
toggleCart: () => void;
initCart: () => void;
addItem: (variantId: string, quantity?: number) => Promise<Cart>;
removeItem: (lineId: string) => Promise<Cart>;
updateItemQuantity: (lineId: string, quantity: number) => Promise<Cart>;
applyDiscountCode: (code: string) => Promise<Cart>;
refreshCart: () => Promise<void>;
}
export const useCartStore = create<CartState>((set, get) => ({
// Initial state
isOpen: false,
cartId: null,
cart: null,
loading: true,
error: null,
_initialized: false,
// UI actions
openCart: () => set({ isOpen: true }),
closeCart: () => set({ isOpen: false }),
toggleCart: () => set((s) => ({ isOpen: !s.isOpen })),
// Initialize cart from localStorage
initCart: () => {
if (get()._initialized) return;
set({ _initialized: true });
if (typeof window === 'undefined') return;
const storedCartId = localStorage.getItem(CART_ID_KEY);
if (!storedCartId) {
set({ loading: false });
return;
}
set({ loading: true });
getCartApi(storedCartId)
.then((fetchedCart) => {
if (fetchedCart) {
set({ cart: fetchedCart, cartId: storedCartId, loading: false });
} else {
localStorage.removeItem(CART_ID_KEY);
set({ cartId: null, cart: null, loading: false });
}
})
.catch(() => {
localStorage.removeItem(CART_ID_KEY);
set({
cartId: null,
cart: null,
loading: false,
error: 'Failed to fetch cart',
});
});
},
// Add item to cart (creates cart if needed)
addItem: async (variantId: string, quantity: number = 1) => {
try {
set({ loading: true, error: null });
// Get or create cart
let currentCartId = get().cartId;
if (!currentCartId) {
const storedCartId = localStorage.getItem(CART_ID_KEY);
if (storedCartId) {
currentCartId = storedCartId;
set({ cartId: storedCartId });
} else {
const newCart = await createCartApi();
localStorage.setItem(CART_ID_KEY, newCart.id);
set({ cart: newCart, cartId: newCart.id });
currentCartId = newCart.id;
}
}
const updatedCart = await addCartLinesApi(currentCartId, [
{ merchandiseId: variantId, quantity },
]);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to add item to cart';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Remove item from cart
removeItem: async (lineId: string) => {
const { cartId } = get();
if (!cartId) throw new Error('No cart exists');
try {
set({ loading: true, error: null });
const updatedCart = await removeCartLinesApi(cartId, [lineId]);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to remove item from cart';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Update item quantity
updateItemQuantity: async (lineId: string, quantity: number) => {
const { cartId, removeItem } = get();
if (!cartId) throw new Error('No cart exists');
if (quantity <= 0) {
return removeItem(lineId);
}
try {
set({ loading: true, error: null });
const updatedCart = await updateCartLinesApi(cartId, [
{ id: lineId, quantity },
]);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to update item quantity';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Apply a discount code. Shopify accepts unknown codes and reports them back
// as `applicable: false`, so callers should check the returned cart.
applyDiscountCode: async (code: string) => {
const { cartId } = get();
if (!cartId) throw new Error('No cart exists');
try {
set({ loading: true, error: null });
const trimmed = code.trim();
const updatedCart = await updateCartDiscountCodesApi(
cartId,
trimmed ? [trimmed] : []
);
set({ cart: updatedCart, loading: false });
return updatedCart;
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Failed to apply discount code';
set({ error: errorMessage, loading: false });
throw err;
}
},
// Refresh cart from Shopify
refreshCart: async () => {
const storedCartId = localStorage.getItem(CART_ID_KEY);
if (!storedCartId) {
set({ loading: false });
return;
}
try {
set({ loading: true, error: null });
const fetchedCart = await getCartApi(storedCartId);
if (fetchedCart) {
set({ cart: fetchedCart, cartId: storedCartId, loading: false });
} else {
localStorage.removeItem(CART_ID_KEY);
set({ cartId: null, cart: null, loading: false });
}
} catch (err) {
localStorage.removeItem(CART_ID_KEY);
set({
cartId: null,
cart: null,
loading: false,
error: 'Failed to fetch cart',
});
}
},
}));
// ─── Hook (backwards-compatible API) ─────────────────────────────────
export function useShopifyCart() {
const store = useCartStore();
// Initialize cart safely in an effect, not during render
useEffect(() => {
if (!store._initialized) {
store.initCart();
}
}, []);
const items = store.cart?.lines?.edges?.map((edge) => edge.node) ?? [];
const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
const totalAmount = parseFloat(store.cart?.cost?.totalAmount?.amount ?? '0');
const checkoutUrl = store.cart?.checkoutUrl ?? null;
return {
isOpen: store.isOpen,
openCart: store.openCart,
closeCart: store.closeCart,
toggleCart: store.toggleCart,
cartId: store.cartId,
cart: store.cart,
items,
itemCount,
totalAmount,
checkoutUrl,
loading: store.loading,
error: store.error,
addItem: store.addItem,
removeItem: store.removeItem,
updateItemQuantity: store.updateItemQuantity,
applyDiscountCode: store.applyDiscountCode,
refreshCart: store.refreshCart,
};
}
+58 -103
View File
@@ -1,82 +1,36 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { shopifyFetch } from '@/services/shopify/client';
import { useState, useEffect, useCallback, useRef } from 'react';
import {
GET_COLLECTIONS_QUERY,
GET_COLLECTION_PRODUCTS_QUERY,
} from '@/graphql/collections';
import type { Product } from './use-shopify-products';
getCollections,
getCollectionProducts,
} from '@/services/shopify/catalog';
interface CollectionImage {
url: string;
altText?: string;
}
export {
getCollections,
getCollectionProducts,
getCollectionProductsPage,
} from '@/services/shopify/catalog';
export type {
Collection,
CollectionWithProducts,
CollectionSortKey,
CollectionProductsPage,
ProductFilterFacet,
} from '@/services/shopify/catalog';
export interface Collection {
id: string;
title: string;
handle: string;
description?: string;
descriptionHtml?: string;
image?: CollectionImage;
}
export interface CollectionWithProducts extends Collection {
products: Product[];
}
export type CollectionSortKey = 'BEST_SELLING' | 'CREATED' | 'PRICE' | 'TITLE';
export interface ProductFilter {
available?: boolean;
price?: { min?: number; max?: number };
productType?: string;
productVendor?: string;
tag?: string;
variantOption?: { name: string; value: string };
productMetafield?: { namespace: string; key: string; value: string };
}
import type {
Collection,
CollectionWithProducts,
CollectionSortKey,
} from '@/services/shopify/catalog';
interface UseCollectionProductsOptions {
first?: number;
after?: string | null;
sortKey?: CollectionSortKey;
reverse?: boolean;
filters?: ProductFilter[];
}
// Fetch all collections
export async function getCollections(first = 50): Promise<Collection[]> {
const response = await shopifyFetch({
query: GET_COLLECTIONS_QUERY,
variables: { first },
});
return response.data.collections.edges.map((edge: { node: Collection }) => edge.node);
}
// Fetch products in a collection by handle
export async function getCollectionProducts(
handle: string,
{ first = 50, sortKey = 'BEST_SELLING', reverse = false, filters }: UseCollectionProductsOptions = {},
after?: string | null,
): Promise<{ collection: CollectionWithProducts; hasNextPage: boolean; endCursor: string | null } | null> {
const response = await shopifyFetch({
query: GET_COLLECTION_PRODUCTS_QUERY,
variables: { handle, first, sortKey, reverse, filters: filters?.length ? filters : undefined, after: after ?? null },
});
const collection = response.data.collection;
if (!collection) return null;
return {
collection: {
...collection,
products: collection.products.edges.map((edge: { node: Product }) => edge.node),
},
hasNextPage: collection.products.pageInfo.hasNextPage,
endCursor: collection.products.pageInfo.endCursor,
};
filterInputs?: string[];
}
// Hook for fetching all collections
@@ -106,6 +60,36 @@ export function useCollections(first = 50) {
return { collections, loading, error, refetch: fetchCollections };
}
// Deferred variant of useCollections: nothing is requested until `load` runs,
// so a menu can hold off until it's actually opened. The fetch happens once —
// re-opening reuses what's already in state.
export function useCollectionsOnDemand(first = 50) {
const [collections, setCollections] = useState<Collection[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const requested = useRef(false);
const load = useCallback(async () => {
if (requested.current) return;
requested.current = true;
try {
setLoading(true);
setError(null);
setCollections(await getCollections(first));
} catch (err) {
console.error('Error fetching collections:', err);
// Let the next open (or a retry) try again.
requested.current = false;
setError(err instanceof Error ? err.message : 'Failed to load collections');
} finally {
setLoading(false);
}
}, [first]);
return { collections, loading, error, load };
}
// Hook for fetching products in a collection
export function useCollectionProducts(
handle: string | null,
@@ -114,10 +98,6 @@ export function useCollectionProducts(
const [collection, setCollection] = useState<CollectionWithProducts | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [hasNextPage, setHasNextPage] = useState(false);
const [cursor, setCursor] = useState<string | null>(null);
const filtersKey = JSON.stringify(options.filters ?? []);
const fetchCollection = useCallback(async () => {
if (!handle) {
@@ -128,14 +108,10 @@ export function useCollectionProducts(
try {
setLoading(true);
setError(null);
const result = await getCollectionProducts(handle, options);
if (!result) {
setCollection(null);
const data = await getCollectionProducts(handle, options);
setCollection(data);
if (!data) {
setError('Collection not found');
} else {
setCollection(result.collection);
setHasNextPage(result.hasNextPage);
setCursor(result.endCursor);
}
} catch (err) {
console.error('Error fetching collection products:', err);
@@ -143,32 +119,11 @@ export function useCollectionProducts(
} finally {
setLoading(false);
}
}, [handle, options.first, options.sortKey, options.reverse, filtersKey]);
}, [handle, options.first, options.sortKey, options.reverse]);
useEffect(() => {
fetchCollection();
}, [fetchCollection]);
const fetchMore = useCallback(async () => {
if (!handle || !cursor || !hasNextPage || loading) return;
setLoading(true);
try {
const result = await getCollectionProducts(handle, options, cursor);
if (result) {
setCollection((prev) =>
prev
? { ...prev, products: [...prev.products, ...result.collection.products] }
: result.collection
);
setHasNextPage(result.hasNextPage);
setCursor(result.endCursor);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Load more failed');
} finally {
setLoading(false);
}
}, [handle, cursor, hasNextPage, loading, options.first, options.sortKey, options.reverse, filtersKey]);
return { collection, loading, error, hasNextPage, fetchMore, refetch: fetchCollection };
return { collection, loading, error, refetch: fetchCollection };
}
+48
View File
@@ -0,0 +1,48 @@
import {
cachedStorefront,
unwrapStorefrontResult,
} from '@/services/shopify/client';
import { GET_SHOP_POLICIES_QUERY } from '@/graphql/policies';
export interface ShopPolicy {
id: string;
title: string;
handle: string;
body: string;
url: string;
}
// Handles Shopify uses for each policy — also the routes under /policies/[handle].
export const POLICY_HANDLES = [
'terms-of-service',
'privacy-policy',
'refund-policy',
'shipping-policy',
'subscription-policy',
] as const;
// Policies change rarely, so this reads through the cached client (revalidated
// hourly) rather than the no-store one used for carts and products.
export async function getShopPolicies(): Promise<ShopPolicy[]> {
try {
const data = unwrapStorefrontResult(
await cachedStorefront.graphql(GET_SHOP_POLICIES_QUERY),
'GetShopPolicies'
);
return Object.values(data.shop ?? {}).filter(
(policy): policy is ShopPolicy => Boolean(policy?.handle)
);
} catch (err) {
// A storefront without policies configured shouldn't break the footer.
console.error('Failed to load shop policies:', err);
return [];
}
}
export async function getShopPolicy(
handle: string
): Promise<ShopPolicy | null> {
const policies = await getShopPolicies();
return policies.find((policy) => policy.handle === handle) ?? null;
}
+20 -95
View File
@@ -1,72 +1,32 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { shopifyFetch } from '@/services/shopify/client';
import {
GET_PRODUCTS_QUERY,
GET_PRODUCT_QUERY,
QUERY_PRODUCT_RECOMMENDATIONS,
} from '@/graphql/products';
getProducts,
getProduct,
getProductRecommendations,
} from '@/services/shopify/catalog';
interface ProductImage {
url: string;
altText?: string;
}
// Pure fetchers live in services/shopify/catalog so server code can use them
// too; re-exported here so existing imports keep working.
export {
getProducts,
getProductsPage,
getProduct,
getProductRecommendations,
} from '@/services/shopify/catalog';
export type {
Product,
ProductOption,
ProductOptionValue,
ProductsPage,
} from '@/services/shopify/catalog';
interface ProductPrice {
amount: string;
currencyCode: string;
}
interface ProductVariant {
id: string;
title: string;
price: ProductPrice;
availableForSale: boolean;
selectedOptions: Array<{
name: string;
value: string;
}>;
image?: ProductImage;
}
interface ProductOption {
id: string;
name: string;
values: string[];
}
export interface Product {
id: string;
title: string;
description?: string;
descriptionHtml?: string;
handle: string;
vendor?: string;
productType?: string;
tags?: string[];
availableForSale?: boolean;
images: {
edges: Array<{
node: ProductImage;
}>;
};
priceRange: {
minVariantPrice: ProductPrice;
};
compareAtPriceRange?: {
minVariantPrice: ProductPrice;
};
variants: {
edges: Array<{
node: ProductVariant;
}>;
};
options: ProductOption[];
}
import type { Product } from '@/services/shopify/catalog';
interface UseProductsOptions {
first?: number;
after?: string | null;
query?: string;
sortKey?: 'BEST_SELLING' | 'CREATED_AT' | 'PRICE' | 'TITLE';
reverse?: boolean;
@@ -79,41 +39,6 @@ interface UseProductsReturn {
refetch: () => Promise<void>;
}
// Fetch multiple products
export async function getProducts({
first = 20,
query = '',
sortKey = 'BEST_SELLING',
reverse = false,
}: UseProductsOptions = {}): Promise<Product[]> {
const response = await shopifyFetch({
query: GET_PRODUCTS_QUERY,
variables: { first, query, sortKey, reverse },
});
return response.data.products.edges.map((edge: { node: Product }) => edge.node);
}
// Fetch a single product by handle
export async function getProduct(handle: string): Promise<Product | null> {
const response = await shopifyFetch({
query: GET_PRODUCT_QUERY,
variables: { handle },
});
return response.data.product;
}
// Fetch product recommendations
export async function getProductRecommendations(productId: string): Promise<Product[]> {
const response = await shopifyFetch({
query: QUERY_PRODUCT_RECOMMENDATIONS,
variables: { productId },
});
return response.data.productRecommendations || [];
}
// Hook for fetching multiple products
export function useProducts(options: UseProductsOptions = {}): UseProductsReturn {
const [products, setProducts] = useState<Product[]>([]);
+10 -178
View File
@@ -1,178 +1,10 @@
'use client';
import { useState, useEffect } from 'react';
import { shopifyFetch } from '@/services/shopify/client';
import { GET_SEARCH_QUERY } from '@/graphql/products';
import type { Product } from '@/hooks/use-shopify-products';
export type SortOption =
| 'RELEVANCE'
| 'BEST_SELLING'
| 'NEWEST'
| 'PRICE_ASC'
| 'PRICE_DESC'
| 'TITLE_ASC';
export interface SearchFilters {
q?: string;
availability?: boolean;
productTypes?: string[];
vendors?: string[];
tags?: string[];
colors?: string[];
styles?: string[];
sizes?: string[];
materials?: string[];
minPrice?: number | null;
maxPrice?: number | null;
metafields?: { namespace: string; key: string; value: string }[];
sort?: SortOption;
}
export interface SearchFacets {
productTypes: string[];
vendors: string[];
tags: string[];
}
function resolveSortKey(sort: SortOption): { sortKey: string; reverse: boolean } {
switch (sort) {
case 'BEST_SELLING': return { sortKey: 'BEST_SELLING', reverse: false };
case 'NEWEST': return { sortKey: 'CREATED_AT', reverse: true };
case 'PRICE_ASC': return { sortKey: 'PRICE', reverse: false };
case 'PRICE_DESC': return { sortKey: 'PRICE', reverse: true };
case 'TITLE_ASC': return { sortKey: 'TITLE', reverse: false };
default: return { sortKey: 'RELEVANCE', reverse: false };
}
}
export function buildShopifyQuery(filters: SearchFilters): string {
const parts: string[] = [];
if (filters.q?.trim()) parts.push(filters.q.trim());
if (filters.availability === true) parts.push('available_for_sale:true');
if (filters.productTypes?.length) {
const clause = filters.productTypes.map((t) => `product_type:"${t}"`).join(' OR ');
parts.push(filters.productTypes.length > 1 ? `(${clause})` : clause);
}
if (filters.vendors?.length) {
const clause = filters.vendors.map((v) => `vendor:"${v}"`).join(' OR ');
parts.push(filters.vendors.length > 1 ? `(${clause})` : clause);
}
if (filters.tags?.length) {
const clause = filters.tags.map((t) => `tag:"${t}"`).join(' OR ');
parts.push(filters.tags.length > 1 ? `(${clause})` : clause);
}
for (const [option, values] of [
['color', filters.colors],
['style', filters.styles],
['size', filters.sizes],
['material', filters.materials],
] as const) {
if (values?.length) {
const clause = values.map((v) => `variant.option.${option}:"${v}"`).join(' OR ');
parts.push(values.length > 1 ? `(${clause})` : clause);
}
}
if (filters.minPrice != null) parts.push(`variants.price:>=${filters.minPrice}`);
if (filters.maxPrice != null) parts.push(`variants.price:<=${filters.maxPrice}`);
if (filters.metafields?.length) {
for (const mf of filters.metafields) {
parts.push(`metafield.${mf.namespace}.${mf.key}:"${mf.value}"`);
}
}
return parts.join(' ');
}
async function fetchProducts(vars: {
first: number;
query: string;
sortKey: string;
reverse: boolean;
after?: string | null;
}) {
const res = await shopifyFetch({
query: GET_SEARCH_QUERY,
variables: { first: vars.first, query: vars.query, sortKey: vars.sortKey, reverse: vars.reverse, after: vars.after ?? null },
});
return {
products: res.data.products.edges.map((e: { node: Product }) => e.node) as Product[],
hasNextPage: res.data.products.pageInfo.hasNextPage as boolean,
endCursor: res.data.products.pageInfo.endCursor as string | null,
};
}
export function useShopifySearch(filters: SearchFilters, { first = 24 }: { first?: number } = {}) {
const [products, setProducts] = useState<Product[]>([]);
const [facets, setFacets] = useState<SearchFacets>({ productTypes: [], vendors: [], tags: [] });
const [loading, setLoading] = useState(true);
const [hasNextPage, setHasNextPage] = useState(false);
const [cursor, setCursor] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const textQuery = filters.q?.trim() ?? '';
const productQuery = buildShopifyQuery(filters);
const { sortKey, reverse } = resolveSortKey(filters.sort ?? 'RELEVANCE');
// Fetch facets from unfiltered (text-only) result so sidebar options don't narrow
useEffect(() => {
let cancelled = false;
fetchProducts({ first: 100, query: textQuery, sortKey: 'RELEVANCE', reverse: false })
.then(({ products: p }) => {
if (cancelled) return;
setFacets({
productTypes: [...new Set(p.map((x) => x.productType).filter(Boolean))].sort() as string[],
vendors: [...new Set(p.map((x) => x.vendor).filter(Boolean))].sort() as string[],
tags: [...new Set(p.flatMap((x) => x.tags ?? []))].sort() as string[],
});
})
.catch(() => {});
return () => { cancelled = true; };
}, [textQuery]);
// Fetch products with all active filters
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(null);
fetchProducts({ first, query: productQuery, sortKey, reverse })
.then(({ products: p, hasNextPage: hnp, endCursor: ec }) => {
if (cancelled) return;
setProducts(p);
setHasNextPage(hnp);
setCursor(ec);
})
.catch((e) => {
if (!cancelled) setError(e instanceof Error ? e.message : 'Search failed');
})
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [productQuery, sortKey, reverse, first]);
const fetchMore = async () => {
if (!cursor || !hasNextPage || loading) return;
setLoading(true);
try {
const { products: more, hasNextPage: hnp, endCursor: ec } = await fetchProducts({
first, query: productQuery, sortKey, reverse, after: cursor,
});
setProducts((prev) => [...prev, ...more]);
setHasNextPage(hnp);
setCursor(ec);
} catch (e) {
setError(e instanceof Error ? e.message : 'Load more failed');
} finally {
setLoading(false);
}
};
return { products, facets, loading, error, hasNextPage, fetchMore };
}
// Re-exported from the server-safe catalogue module so both client components
// and Route Handlers can search the storefront.
export { searchProducts, searchSuggestions } from '@/services/shopify/catalog';
export type {
SearchSortKey,
SearchFilter,
SearchFilterValue,
SearchProductsResult,
SearchSuggestion,
} from '@/services/shopify/catalog';