Compare commits

...

3 Commits

Author SHA1 Message Date
Rami Bitar
4f95e56513 update 2026-05-08 15:06:54 -04:00
Rami Bitar
6706a11f7b update css vars 2026-05-08 14:55:17 -04:00
Rami Bitar
564c98c805 Consolidate theme radius/shadow props and make rounded utilities responsive
- Remove duplicate roundedness/shadowLevel props (keep radius/shadow)
- Switch globals.css radius scale to proportional (square→pill works)
- Replace rounded-full with rounded-md on theme-driven elements
- Remove banner props from Navigation, drop publishing overlay

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 10:01:55 -04:00
26 changed files with 2531 additions and 211 deletions

View File

@@ -11,9 +11,8 @@
"bgColor": "#ffffff", "bgColor": "#ffffff",
"fgColor": "#0a0a0a", "fgColor": "#0a0a0a",
"mutedColor": "#f5f5f5", "mutedColor": "#f5f5f5",
"roundedness": "md", "radius": "sm",
"radius": "md", "buttonRadius": "md",
"shadowLevel": "sm",
"shadow": "sm", "shadow": "sm",
"maxWidth": "xl" "maxWidth": "xl"
} }
@@ -25,10 +24,22 @@
"id": "nav-home", "id": "nav-home",
"brand": "Maison", "brand": "Maison",
"links": [ "links": [
{ "label": "Shop", "href": "/collections" }, {
{ "label": "Lookbook", "href": "/lookbook" }, "label": "Shop",
{ "label": "Journal", "href": "/journal" }, "href": "/search"
{ "label": "About", "href": "/about" } },
{
"label": "Mens",
"href": "/collections/mens"
},
{
"label": "Womens",
"href": "/collections/womens"
},
{
"label": "About",
"href": "/about"
}
], ],
"showSearch": "yes", "showSearch": "yes",
"showAccount": "yes", "showAccount": "yes",
@@ -44,8 +55,14 @@
"tagline": "Spring 2026", "tagline": "Spring 2026",
"heading": "Made for the way you move", "heading": "Made for the way you move",
"subheading": "A considered wardrobe of essentials, cut from natural fibers and designed to last.", "subheading": "A considered wardrobe of essentials, cut from natural fibers and designed to last.",
"primaryCta": { "label": "Shop the collection", "href": "/collections" }, "primaryCta": {
"secondaryCta": { "label": "Our story", "href": "/about" }, "label": "Shop the collection",
"href": "/collections"
},
"secondaryCta": {
"label": "Our story",
"href": "/about"
},
"imageUrl": "https://images.unsplash.com/photo-1490481651871-ab68de25d43d?auto=format&fit=crop&w=2400&q=80", "imageUrl": "https://images.unsplash.com/photo-1490481651871-ab68de25d43d?auto=format&fit=crop&w=2400&q=80",
"align": "left", "align": "left",
"height": "lg", "height": "lg",
@@ -96,9 +113,18 @@
"subheading": "A small set of values that shape every piece we make.", "subheading": "A small set of values that shape every piece we make.",
"columns": "3", "columns": "3",
"items": [ "items": [
{ "title": "Natural fibers", "body": "Linen, organic cotton, and merino — sourced from mills with traceable supply chains." }, {
{ "title": "Small batches", "body": "Made in considered quantities so nothing goes to waste." }, "title": "Natural fibers",
{ "title": "Built to last", "body": "Reinforced seams and finishes that age into something better." } "body": "Linen, organic cotton, and merino — sourced from mills with traceable supply chains."
},
{
"title": "Small batches",
"body": "Made in considered quantities so nothing goes to waste."
},
{
"title": "Built to last",
"body": "Reinforced seams and finishes that age into something better."
}
] ]
} }
}, },
@@ -147,39 +173,81 @@
{ {
"title": "Shop", "title": "Shop",
"links": [ "links": [
{ "label": "All", "href": "/collections" }, {
{ "label": "New", "href": "/collections/new" }, "label": "All",
{ "label": "Best sellers", "href": "/collections/best" } "href": "/search"
},
{
"label": "New",
"href": "/collections/new"
},
{
"label": "Best sellers",
"href": "/collections/best"
}
] ]
}, },
{ {
"title": "About", "title": "About",
"links": [ "links": [
{ "label": "Our story", "href": "/about" }, {
{ "label": "Materials", "href": "/materials" }, "label": "Our story",
{ "label": "Journal", "href": "/journal" } "href": "/about"
},
{
"label": "Materials",
"href": "/materials"
},
{
"label": "Journal",
"href": "/journal"
}
] ]
}, },
{ {
"title": "Help", "title": "Help",
"links": [ "links": [
{ "label": "Shipping", "href": "/help/shipping" }, {
{ "label": "Returns", "href": "/help/returns" }, "label": "Shipping",
{ "label": "Contact", "href": "/contact" } "href": "/help/shipping"
},
{
"label": "Returns",
"href": "/help/returns"
},
{
"label": "Contact",
"href": "/contact"
}
] ]
}, },
{ {
"title": "Legal", "title": "Legal",
"links": [ "links": [
{ "label": "Terms", "href": "/terms" }, {
{ "label": "Privacy", "href": "/privacy" } "label": "Terms",
"href": "/terms"
},
{
"label": "Privacy",
"href": "/privacy"
}
] ]
} }
], ],
"social": [ "social": [
{ "label": "Instagram", "href": "#" }, {
{ "label": "Pinterest", "href": "#" }, "label": "Instagram",
{ "label": "TikTok", "href": "#" } "href": "#"
},
{
"label": "Pinterest",
"href": "#"
},
{
"label": "TikTok",
"href": "#"
}
], ],
"showNewsletter": "no", "showNewsletter": "no",
"newsletterHeading": "Stay in touch", "newsletterHeading": "Stay in touch",
@@ -189,7 +257,7 @@
} }
] ]
}, },
"/products/:handle": { "/products/:handle": {
"root": { "root": {
"props": { "props": {
"title": "Default product", "title": "Default product",
@@ -201,9 +269,8 @@
"bgColor": "#ffffff", "bgColor": "#ffffff",
"fgColor": "#0a0a0a", "fgColor": "#0a0a0a",
"mutedColor": "#f5f5f5", "mutedColor": "#f5f5f5",
"roundedness": "md", "radius": "sm",
"radius": "md", "buttonRadius": "md",
"shadowLevel": "sm",
"shadow": "sm", "shadow": "sm",
"maxWidth": "xl" "maxWidth": "xl"
} }
@@ -215,10 +282,22 @@
"id": "nav-product", "id": "nav-product",
"brand": "Maison", "brand": "Maison",
"links": [ "links": [
{ "label": "Shop", "href": "/collections" }, {
{ "label": "Lookbook", "href": "/lookbook" }, "label": "Shop",
{ "label": "Journal", "href": "/journal" }, "href": "/search"
{ "label": "About", "href": "/about" } },
{
"label": "Mens",
"href": "/collections/mens"
},
{
"label": "Womens",
"href": "/collections/womens"
},
{
"label": "About",
"href": "/about"
}
], ],
"showSearch": "yes", "showSearch": "yes",
"showAccount": "yes", "showAccount": "yes",
@@ -256,21 +335,532 @@
{ {
"title": "Shop", "title": "Shop",
"links": [ "links": [
{ "label": "All", "href": "/collections" }, {
{ "label": "New", "href": "/collections/new" } "label": "All",
"href": "/search"
},
{
"label": "New",
"href": "/collections/new"
}
] ]
}, },
{ {
"title": "Help", "title": "Help",
"links": [ "links": [
{ "label": "Shipping", "href": "/help/shipping" }, {
{ "label": "Returns", "href": "/help/returns" } "label": "Shipping",
"href": "/help/shipping"
},
{
"label": "Returns",
"href": "/help/returns"
}
] ]
} }
], ],
"social": [ "social": [
{ "label": "Instagram", "href": "#" }, {
{ "label": "Pinterest", "href": "#" } "label": "Instagram",
"href": "#"
},
{
"label": "Pinterest",
"href": "#"
}
],
"showNewsletter": "no",
"newsletterHeading": "Stay in touch",
"newsletterEndpoint": "",
"copyright": "© 2026 Maison. All rights reserved."
}
}
]
},
"/collections/:handle": {
"root": {
"props": {
"title": "Collection",
"headerFont": "Playfair Display",
"bodyFont": "Inter",
"primaryColor": "#0a0a0a",
"secondaryColor": "#64748B",
"accentColor": "#f5f5f5",
"bgColor": "#ffffff",
"fgColor": "#0a0a0a",
"mutedColor": "#f5f5f5",
"radius": "sm",
"buttonRadius": "md",
"shadow": "sm",
"maxWidth": "xl"
}
},
"content": [
{
"type": "navigation",
"props": {
"id": "nav-collection",
"brand": "Maison",
"links": [
{
"label": "Shop",
"href": "/search"
},
{
"label": "Mens",
"href": "/collections/mens"
},
{
"label": "Womens",
"href": "/collections/womens"
},
{
"label": "About",
"href": "/about"
}
],
"showSearch": "yes",
"showAccount": "yes",
"showCart": "yes",
"sticky": "yes",
"tone": "default"
}
},
{
"type": "collection",
"props": {
"id": "collection-detail",
"collection": null,
"showDescription": "yes",
"showCoverImage": "yes",
"customCoverImage": "",
"columns": "4",
"limit": 24,
"defaultSort": "BEST_SELLING",
"showAvailability": "yes",
"showPriceRange": "yes",
"showProductType": "no",
"productTypeOptions": [],
"showVendor": "no",
"vendorOptions": [],
"showTags": "no",
"tagOptions": [],
"showColor": "yes",
"colorOptions": [
{ "label": "Black", "color": "#000000" },
{ "label": "White", "color": "#FFFFFF" },
{ "label": "Navy", "color": "#1e3a5f" }
],
"showStyle": "no",
"styleOptions": [],
"showSize": "yes",
"sizeOptions": [
{ "label": "XS" },
{ "label": "S" },
{ "label": "M" },
{ "label": "L" },
{ "label": "XL" }
],
"showMaterial": "no",
"materialOptions": [],
"metafieldFilters": []
}
},
{
"type": "footer",
"props": {
"id": "footer-collection",
"brand": "Maison",
"tagline": "Considered essentials, made in small batches.",
"columns": [
{
"title": "Shop",
"links": [
{
"label": "All",
"href": "/search"
},
{
"label": "New",
"href": "/collections/new"
}
]
},
{
"title": "Help",
"links": [
{
"label": "Shipping",
"href": "/help/shipping"
},
{
"label": "Returns",
"href": "/help/returns"
}
]
}
],
"social": [
{
"label": "Instagram",
"href": "#"
},
{
"label": "Pinterest",
"href": "#"
}
],
"showNewsletter": "no",
"newsletterHeading": "Stay in touch",
"newsletterEndpoint": "",
"copyright": "© 2026 Maison. All rights reserved."
}
}
]
},
"/search": {
"root": {
"props": {
"title": "Shop",
"headerFont": "Playfair Display",
"bodyFont": "Inter",
"primaryColor": "#0a0a0a",
"secondaryColor": "#64748B",
"accentColor": "#f5f5f5",
"bgColor": "#ffffff",
"fgColor": "#0a0a0a",
"mutedColor": "#f5f5f5",
"radius": "sm",
"buttonRadius": "md",
"shadow": "sm",
"maxWidth": "xl"
}
},
"content": [
{
"type": "navigation",
"props": {
"id": "nav-search",
"brand": "Maison",
"links": [
{
"label": "Shop",
"href": "/search"
},
{
"label": "Mens",
"href": "/collections/mens"
},
{
"label": "Womens",
"href": "/collections/womens"
},
{
"label": "About",
"href": "/about"
}
],
"showSearch": "yes",
"showAccount": "yes",
"showCart": "yes",
"sticky": "yes",
"tone": "default"
}
},
{
"type": "search-products",
"props": {
"id": "search-products",
"heading": "Shop",
"subheading": "Browse our full collection.",
"columns": "4",
"limit": 24,
"showAvailability": "yes",
"showPriceRange": "yes",
"showProductType": "yes",
"showVendor": "yes",
"showTags": "yes",
"metafieldFilters": [],
"defaultSort": "BEST_SELLING",
"productTypeOptions": [
{
"label": "T-Shirts"
},
{
"label": "Pants"
},
{
"label": "Outerwear"
},
{
"label": "Accessories"
},
{
"label": "Shoes"
}
],
"vendorOptions": [
{
"label": "Maison"
},
{
"label": "Atelier"
},
{
"label": "Studio"
}
],
"tagOptions": [
{
"label": "New"
},
{
"label": "Sale"
},
{
"label": "Bestseller"
},
{
"label": "Limited Edition"
}
]
}
},
{
"type": "footer",
"props": {
"id": "footer-search",
"brand": "Maison",
"tagline": "Considered essentials, made in small batches.",
"columns": [
{
"title": "Shop",
"links": [
{
"label": "All",
"href": "/search"
},
{
"label": "Mens",
"href": "/collections/mens"
},
{
"label": "Womens",
"href": "/collections/womens"
}
]
},
{
"title": "Help",
"links": [
{
"label": "Shipping",
"href": "/help/shipping"
},
{
"label": "Returns",
"href": "/help/returns"
}
]
}
],
"social": [
{
"label": "Instagram",
"href": "#"
},
{
"label": "Pinterest",
"href": "#"
}
],
"showNewsletter": "no",
"newsletterHeading": "Stay in touch",
"newsletterEndpoint": "",
"copyright": "© 2026 Maison. All rights reserved."
}
}
]
},
"/about": {
"root": {
"props": {
"title": "About — Maison",
"headerFont": "Playfair Display",
"bodyFont": "Inter",
"primaryColor": "#0a0a0a",
"secondaryColor": "#64748B",
"accentColor": "#f5f5f5",
"bgColor": "#ffffff",
"fgColor": "#0a0a0a",
"mutedColor": "#f5f5f5",
"radius": "sm",
"buttonRadius": "md",
"shadow": "sm",
"maxWidth": "xl"
}
},
"content": [
{
"type": "navigation",
"props": {
"id": "nav-about",
"brand": "Maison",
"links": [
{
"label": "Shop",
"href": "/search"
},
{
"label": "Mens",
"href": "/collections/mens"
},
{
"label": "Womens",
"href": "/collections/womens"
},
{
"label": "About",
"href": "/about"
}
],
"showSearch": "yes",
"showAccount": "yes",
"showCart": "yes",
"sticky": "yes",
"tone": "default"
}
},
{
"type": "hero",
"props": {
"id": "hero-about",
"tagline": "Our Story",
"heading": "Built on intention, not trend",
"subheading": "We started Maison with a simple belief: clothing should be made slowly, from honest materials, and designed to outlast the season it was born in.",
"primaryCta": {
"label": "Shop the collection",
"href": "/search"
},
"secondaryCta": {
"label": "",
"href": ""
},
"imageUrl": "https://images.unsplash.com/photo-1441986300917-64674bd600d8?auto=format&fit=crop&w=2400&q=80",
"align": "left",
"height": "md",
"tone": "dark"
}
},
{
"type": "features",
"props": {
"id": "features-about",
"tagline": "What we believe",
"heading": "The principles behind every piece",
"subheading": "",
"columns": "3",
"items": [
{
"title": "Traceable materials",
"body": "Every fiber we use — linen, organic cotton, merino — comes from mills with transparent, auditable supply chains."
},
{
"title": "Small-batch production",
"body": "We produce in considered quantities. Nothing sits in a warehouse, nothing ends up in landfill."
},
{
"title": "Designed to age well",
"body": "Reinforced construction and natural finishes that soften and improve with every wear and wash."
}
]
}
},
{
"type": "newsletter-cta",
"props": {
"id": "newsletter-about",
"tagline": "Stay in the loop",
"heading": "Letters from the studio",
"subheading": "New collections, mill stories, and the occasional invitation. Twice a month.",
"buttonLabel": "Subscribe",
"endpoint": "",
"imageUrl": "https://images.unsplash.com/photo-1469334031218-e382a71b716b?auto=format&fit=crop&w=1800&q=80",
"layout": "split"
}
},
{
"type": "footer",
"props": {
"id": "footer-about",
"brand": "Maison",
"tagline": "Considered essentials, made in small batches and built to last beyond the season.",
"columns": [
{
"title": "Shop",
"links": [
{
"label": "All",
"href": "/search"
},
{
"label": "New",
"href": "/collections/new"
},
{
"label": "Best sellers",
"href": "/collections/best"
}
]
},
{
"title": "About",
"links": [
{
"label": "Our story",
"href": "/about"
},
{
"label": "Materials",
"href": "/materials"
},
{
"label": "Journal",
"href": "/journal"
}
]
},
{
"title": "Help",
"links": [
{
"label": "Shipping",
"href": "/help/shipping"
},
{
"label": "Returns",
"href": "/help/returns"
},
{
"label": "Contact",
"href": "/contact"
}
]
}
],
"social": [
{
"label": "Instagram",
"href": "#"
},
{
"label": "Pinterest",
"href": "#"
},
{
"label": "TikTok",
"href": "#"
}
], ],
"showNewsletter": "no", "showNewsletter": "no",
"newsletterHeading": "Stay in touch", "newsletterHeading": "Stay in touch",
@@ -280,4 +870,4 @@
} }
] ]
} }
} }

View File

@@ -13,31 +13,29 @@ export type ThemeProps = {
mutedColor?: string; mutedColor?: string;
mutedForegroundColor?: string; mutedForegroundColor?: string;
borderColor?: string; borderColor?: string;
roundedness?: "none" | "sm" | "md" | "lg" | "xl" | "full"; radius?: "none" | "sm" | "md" | "lg" | "xl";
radius?: "none" | "xs" | "sm" | "md" | "lg"; buttonRadius?: "none" | "sm" | "md" | "lg" | "xl";
shadowLevel?: "none" | "sm" | "md" | "lg" | "xl"; shadow?: "none" | "sm" | "md" | "lg" | "xl";
shadow?: "none" | "sm" | "md" | "lg";
maxWidth?: "sm" | "md" | "lg" | "xl" | "2xl" | "full"; maxWidth?: "sm" | "md" | "lg" | "xl" | "2xl" | "full";
}; };
const radiusMap: Record<NonNullable<ThemeProps["roundedness"]>, string> = { const radiusMap: Record<NonNullable<ThemeProps["radius"]>, string> = {
none: "0px", none: "0px",
sm: "0.25rem", sm: "0.25rem",
md: "0.5rem", md: "0.5rem",
lg: "0.75rem", lg: "0.75rem",
xl: "1rem", xl: "1rem",
full: "9999px",
}; };
const radiusEnumMap: Record<NonNullable<ThemeProps["radius"]>, string> = { const buttonRadiusMap: Record<NonNullable<ThemeProps["buttonRadius"]>, string> = {
none: "0px", none: "0px",
xs: "0.125rem",
sm: "0.25rem", sm: "0.25rem",
md: "0.5rem", md: "0.5rem",
lg: "0.75rem", lg: "0.75rem",
xl: "1rem",
}; };
const shadowMap: Record<NonNullable<ThemeProps["shadowLevel"]>, string> = { const shadowMap: Record<NonNullable<ThemeProps["shadow"]>, string> = {
none: "0 0 #0000", none: "0 0 #0000",
sm: "0 1px 2px 0 rgb(0 0 0 / 0.05)", sm: "0 1px 2px 0 rgb(0 0 0 / 0.05)",
md: "0 4px 6px -1px rgb(0 0 0 / 0.10), 0 2px 4px -2px rgb(0 0 0 / 0.10)", md: "0 4px 6px -1px rgb(0 0 0 / 0.10), 0 2px 4px -2px rgb(0 0 0 / 0.10)",
@@ -45,13 +43,6 @@ const shadowMap: Record<NonNullable<ThemeProps["shadowLevel"]>, string> = {
xl: "0 20px 25px -5px rgb(0 0 0 / 0.10), 0 8px 10px -6px rgb(0 0 0 / 0.10)", xl: "0 20px 25px -5px rgb(0 0 0 / 0.10), 0 8px 10px -6px rgb(0 0 0 / 0.10)",
}; };
const shadowEnumMap: Record<NonNullable<ThemeProps["shadow"]>, string> = {
none: "0 0 #0000",
sm: "0 1px 2px 0 rgb(0 0 0 / 0.05)",
md: "0 4px 6px -1px rgb(0 0 0 / 0.10), 0 2px 4px -2px rgb(0 0 0 / 0.10)",
lg: "0 10px 15px -3px rgb(0 0 0 / 0.10), 0 4px 6px -4px rgb(0 0 0 / 0.10)",
};
function googleFontsHref(headerFont?: string, bodyFont?: string): string | null { function googleFontsHref(headerFont?: string, bodyFont?: string): string | null {
const fonts = [headerFont, bodyFont].filter( const fonts = [headerFont, bodyFont].filter(
(f): f is string => !!f && f !== "system-ui" (f): f is string => !!f && f !== "system-ui"
@@ -75,9 +66,8 @@ export function ThemeProvider({
mutedColor, mutedColor,
mutedForegroundColor, mutedForegroundColor,
borderColor, borderColor,
roundedness,
radius, radius,
shadowLevel, buttonRadius,
shadow, shadow,
children, children,
}: ThemeProps & { children?: React.ReactNode }) { }: ThemeProps & { children?: React.ReactNode }) {
@@ -93,10 +83,9 @@ export function ThemeProvider({
if (mutedColor) vars["--muted"] = mutedColor; if (mutedColor) vars["--muted"] = mutedColor;
if (mutedForegroundColor) vars["--muted-foreground"] = mutedForegroundColor; if (mutedForegroundColor) vars["--muted-foreground"] = mutedForegroundColor;
if (borderColor) vars["--border"] = borderColor; if (borderColor) vars["--border"] = borderColor;
if (radius) vars["--radius"] = radiusEnumMap[radius]; if (radius) vars["--radius"] = radiusMap[radius];
else if (roundedness) vars["--radius"] = radiusMap[roundedness]; if (buttonRadius) vars["--button-radius"] = buttonRadiusMap[buttonRadius];
if (shadow) vars["--shadow"] = shadowEnumMap[shadow]; if (shadow) vars["--shadow"] = shadowMap[shadow];
else if (shadowLevel) vars["--shadow"] = shadowMap[shadowLevel];
if (headerFont) vars["--font-header"] = `"${headerFont}", system-ui, sans-serif`; if (headerFont) vars["--font-header"] = `"${headerFont}", system-ui, sans-serif`;
if (bodyFont) vars["--font-body"] = `"${bodyFont}", system-ui, sans-serif`; if (bodyFont) vars["--font-body"] = `"${bodyFont}", system-ui, sans-serif`;
return vars; return vars;
@@ -112,9 +101,8 @@ export function ThemeProvider({
mutedColor, mutedColor,
mutedForegroundColor, mutedForegroundColor,
borderColor, borderColor,
roundedness,
radius, radius,
shadowLevel, buttonRadius,
shadow, shadow,
]); ]);

View File

@@ -84,7 +84,6 @@ const CartDrawer: React.FC = () => {
<Button <Button
onClick={closeCart} onClick={closeCart}
variant="outline" variant="outline"
className="rounded-full"
> >
Continue Shopping Continue Shopping
</Button> </Button>

View File

@@ -1,5 +1,7 @@
import { ComponentConfig } from "@reacteditor/core"; import { ComponentConfig } from "@reacteditor/core";
import { FolderOpen } from "lucide-react"; import { FolderOpen } from "lucide-react";
import { imageField } from "@reacteditor/plugin-media/field";
import { frontendAiMediaAdapter } from "@/services/media-adapter";
import { CollectionView, type CollectionProps } from "@/components/commerce/collection"; import { CollectionView, type CollectionProps } from "@/components/commerce/collection";
export function createCollectionEditor(opts: { export function createCollectionEditor(opts: {
@@ -9,17 +11,240 @@ export function createCollectionEditor(opts: {
label: "Collection page", label: "Collection page",
icon: <FolderOpen size={16} />, icon: <FolderOpen size={16} />,
category: "commerce", category: "commerce",
defaultProps: { collection: null, showDescription: "no" }, defaultProps: {
collection: null,
showDescription: "yes",
showCoverImage: "yes",
customCoverImage: "",
columns: "4",
limit: 24,
defaultSort: "BEST_SELLING",
showAvailability: "yes",
showPriceRange: "yes",
showProductType: "no",
productTypeOptions: [],
showVendor: "no",
vendorOptions: [],
showTags: "no",
tagOptions: [],
showColor: "yes",
colorOptions: [
{ label: "Black", color: "#000000" },
{ label: "White", color: "#FFFFFF" },
{ label: "Navy", color: "#1e3a5f" },
],
showStyle: "no",
styleOptions: [],
showSize: "yes",
sizeOptions: [
{ label: "XS" },
{ label: "S" },
{ label: "M" },
{ label: "L" },
{ label: "XL" },
],
showMaterial: "no",
materialOptions: [],
metafieldFilters: [],
},
fields: { fields: {
collection: { label: "Collection", ...opts.collectionField }, collection: { label: "Collection", ...opts.collectionField },
showDescription: { showDescription: {
label: "Description", label: "Description",
type: "radio", type: "radio",
options: [ options: [
{ label: "Hide description", value: "no" }, { label: "Show", value: "yes" },
{ label: "Show description", value: "yes" }, { label: "Hide", value: "no" },
], ],
}, },
showCoverImage: {
label: "Cover image",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
customCoverImage: {
label: "Custom cover image",
...imageField({ adapter: frontendAiMediaAdapter }),
},
columns: {
label: "Columns",
type: "radio",
options: [
{ label: "2", value: "2" },
{ label: "3", value: "3" },
{ label: "4", value: "4" },
],
},
limit: { label: "Products per page", type: "number", min: 4, max: 48 },
defaultSort: {
label: "Default sort",
type: "select",
options: [
{ label: "Best Selling", value: "BEST_SELLING" },
{ label: "Newest", value: "CREATED" },
{ label: "Price: Low to High", value: "PRICE" },
{ label: "Alphabetical", value: "TITLE" },
],
},
showAvailability: {
label: "Availability filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
showPriceRange: {
label: "Price range filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
showColor: {
label: "Color filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
colorOptions: {
label: "Colors",
type: "array",
defaultItemProps: { label: "", color: "#000000" },
getItemSummary: (it: any) => it?.label || "Color",
arrayFields: {
label: { label: "Color name", type: "text" },
color: { label: "Color", type: "color" },
},
},
showStyle: {
label: "Style filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
styleOptions: {
label: "Styles",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (it: any) => it?.label || "Style",
arrayFields: {
label: { label: "Style name", type: "text" },
},
},
showSize: {
label: "Size filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
sizeOptions: {
label: "Sizes",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (it: any) => it?.label || "Size",
arrayFields: {
label: { label: "Size name", type: "text" },
},
},
showMaterial: {
label: "Material filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
materialOptions: {
label: "Materials",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (it: any) => it?.label || "Material",
arrayFields: {
label: { label: "Material name", type: "text" },
},
},
showVendor: {
label: "Brand / vendor filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
vendorOptions: {
label: "Brands",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (it: any) => it?.label || "Brand",
arrayFields: {
label: { label: "Brand name", type: "text" },
},
},
showProductType: {
label: "Product type filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
productTypeOptions: {
label: "Product types",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (it: any) => it?.label || "Type",
arrayFields: {
label: { label: "Type name", type: "text" },
},
},
showTags: {
label: "Tags filter",
type: "radio",
options: [
{ label: "Show", value: "yes" },
{ label: "Hide", value: "no" },
],
},
tagOptions: {
label: "Tags",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (it: any) => it?.label || "Tag",
arrayFields: {
label: { label: "Tag name", type: "text" },
},
},
metafieldFilters: {
label: "Metafield filters",
type: "array",
defaultItemProps: { namespace: "", key: "", label: "", values: [{ label: "" }] },
getItemSummary: (it: any) => it?.label || it?.key || "Metafield",
arrayFields: {
namespace: { label: "Namespace", type: "text" },
key: { label: "Key", type: "text" },
label: { label: "Label", type: "text" },
values: {
label: "Values",
type: "array",
defaultItemProps: { label: "" },
getItemSummary: (v: any) => v?.label || "Value",
arrayFields: {
label: { label: "Value", type: "text" },
},
},
},
},
}, },
render: (props) => <CollectionView {...props} />, render: (props) => <CollectionView {...props} />,
}; };

View File

@@ -1,31 +1,456 @@
import type { ShopifyCollection } from "@reacteditor/field-shopify"; import { useState, useCallback } from 'react';
import { useCollectionProducts } from "@/hooks/use-shopify-collections"; import { useParams } from 'react-router';
import { ProductCard } from "./product-card"; import { ChevronDown, SlidersHorizontal, X } from 'lucide-react';
import { Typography } from "@/components/Typography"; import type { ShopifyCollection } from '@reacteditor/field-shopify';
import { Skeleton } from "@/components/ui/skeleton"; import {
useCollectionProducts,
type CollectionSortKey,
type ProductFilter,
} from '@/hooks/use-shopify-collections';
import { ProductCard } from './product-card';
import { Typography } from '@/components/Typography';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import { cn } from '@/lib/utils';
type FilterOption = { label: string };
type ColorOption = { label: string; color: string };
export type CollectionProps = { export type CollectionProps = {
collection: ShopifyCollection | null; collection: ShopifyCollection | null;
showDescription: "yes" | "no"; showDescription: 'yes' | 'no';
showCoverImage: 'yes' | 'no';
customCoverImage: string;
columns: '2' | '3' | '4';
limit: number;
defaultSort: CollectionSortKey;
showAvailability: 'yes' | 'no';
showPriceRange: 'yes' | 'no';
showProductType: 'yes' | 'no';
productTypeOptions: FilterOption[];
showVendor: 'yes' | 'no';
vendorOptions: FilterOption[];
showTags: 'yes' | 'no';
tagOptions: FilterOption[];
showColor: 'yes' | 'no';
colorOptions: ColorOption[];
showStyle: 'yes' | 'no';
styleOptions: FilterOption[];
showSize: 'yes' | 'no';
sizeOptions: FilterOption[];
showMaterial: 'yes' | 'no';
materialOptions: FilterOption[];
metafieldFilters: { namespace: string; key: string; label: string; values: { label: string }[] }[];
}; };
export function CollectionView({ const SORT_OPTIONS: { label: string; value: CollectionSortKey }[] = [
collection: selected, { label: 'Best Selling', value: 'BEST_SELLING' },
showDescription, { label: 'Newest', value: 'CREATED' },
}: CollectionProps) { { label: 'Price: Low to High', value: 'PRICE' },
const handle = selected?.handle ?? ""; { label: 'Alphabetical', value: 'TITLE' },
const { collection, loading } = useCollectionProducts(handle, { first: 24 }); ];
if (!selected) { const colClass: Record<CollectionProps['columns'], string> = {
'2': 'grid-cols-2',
'3': 'grid-cols-2 md:grid-cols-3',
'4': 'grid-cols-2 md:grid-cols-3 lg:grid-cols-4',
};
// ─── Filter group (collapsible) ────────────────────────────────────────────────
function FilterGroup({ label, children, defaultOpen = true }: {
label: string;
children: React.ReactNode;
defaultOpen?: boolean;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<div className="border-b border-border py-4">
<button
type="button"
onClick={() => setOpen((o) => !o)}
className="flex w-full items-center justify-between text-xs font-semibold uppercase tracking-[0.15em] text-foreground"
>
{label}
<ChevronDown
size={14}
className={cn('transition-transform', open ? 'rotate-180' : '')}
/>
</button>
{open && <div className="mt-3 space-y-2">{children}</div>}
</div>
);
}
function Checkbox({ checked, onChange, label }: {
checked: boolean;
onChange: (v: boolean) => void;
label: string;
}) {
return (
<label className="flex cursor-pointer items-center gap-2.5 text-sm text-foreground/80 hover:text-foreground">
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
className="sr-only"
/>
<span
className={cn(
'flex h-4 w-4 shrink-0 items-center justify-center rounded border',
checked ? 'border-foreground bg-foreground' : 'border-border',
)}
>
{checked && (
<svg viewBox="0 0 10 8" className="h-2.5 w-2.5 fill-background" aria-hidden>
<path d="M1 4l3 3 5-6" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)}
</span>
{label}
</label>
);
}
// ─── Sidebar ────────────────────────────────────────────────────────────────────
type ActiveFilters = {
availability: boolean;
productTypes: string[];
vendors: string[];
tags: string[];
colors: string[];
styles: string[];
sizes: string[];
materials: string[];
minPrice: string;
maxPrice: string;
metafieldValues: Record<string, string[]>;
};
function Sidebar({
props,
active,
onChange,
}: {
props: CollectionProps;
active: ActiveFilters;
onChange: (patch: Partial<ActiveFilters>) => void;
}) {
const productTypes = (props.productTypeOptions ?? []).map((o) => o.label).filter(Boolean);
const vendors = (props.vendorOptions ?? []).map((o) => o.label).filter(Boolean);
const tags = (props.tagOptions ?? []).map((o) => o.label).filter(Boolean);
const colors = (props.colorOptions ?? []) as ColorOption[];
const styles = (props.styleOptions ?? []).map((o) => o.label).filter(Boolean);
const sizes = (props.sizeOptions ?? []).map((o) => o.label).filter(Boolean);
const materials = (props.materialOptions ?? []).map((o) => o.label).filter(Boolean);
const metafieldFilters = (props.metafieldFilters ?? []).filter((mf) => mf.namespace && mf.key);
function toggle(key: 'productTypes' | 'vendors' | 'tags' | 'colors' | 'styles' | 'sizes' | 'materials', value: string) {
const arr = active[key];
onChange({ [key]: arr.includes(value) ? arr.filter((v) => v !== value) : [...arr, value] });
}
const hasActiveFilters =
active.availability ||
active.productTypes.length > 0 ||
active.vendors.length > 0 ||
active.tags.length > 0 ||
active.colors.length > 0 ||
active.styles.length > 0 ||
active.sizes.length > 0 ||
active.materials.length > 0 ||
active.minPrice !== '' ||
active.maxPrice !== '' ||
Object.values(active.metafieldValues).some((arr) => arr.length > 0);
return (
<aside className="w-full shrink-0 md:w-52 lg:w-56">
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="text-xs font-semibold uppercase tracking-[0.15em]">Filters</span>
{hasActiveFilters && (
<button
type="button"
onClick={() =>
onChange({
availability: false,
productTypes: [],
vendors: [],
tags: [],
colors: [],
styles: [],
sizes: [],
materials: [],
minPrice: '',
maxPrice: '',
metafieldValues: {},
})
}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
<X size={12} /> Clear all
</button>
)}
</div>
{props.showAvailability === 'yes' && (
<FilterGroup label="Availability">
<Checkbox
checked={active.availability}
onChange={(v) => onChange({ availability: v })}
label="In stock"
/>
</FilterGroup>
)}
{props.showPriceRange === 'yes' && (
<FilterGroup label="Price">
<div className="flex items-center gap-2">
<input
type="number"
min={0}
placeholder="Min"
value={active.minPrice}
onChange={(e) => onChange({ minPrice: e.target.value })}
className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm"
/>
<span className="text-muted-foreground"></span>
<input
type="number"
min={0}
placeholder="Max"
value={active.maxPrice}
onChange={(e) => onChange({ maxPrice: e.target.value })}
className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm"
/>
</div>
</FilterGroup>
)}
{props.showVendor === 'yes' && vendors.length > 0 && (
<FilterGroup label="Brand">
{vendors.map((v) => (
<Checkbox
key={v}
checked={active.vendors.includes(v)}
onChange={() => toggle('vendors', v)}
label={v}
/>
))}
</FilterGroup>
)}
{props.showColor === 'yes' && colors.length > 0 && (
<FilterGroup label="Color">
{colors.filter((c) => c.label).map((c) => (
<label
key={c.label}
className="flex cursor-pointer items-center gap-2.5 text-sm text-foreground/80 hover:text-foreground"
>
<input
type="checkbox"
checked={active.colors.includes(c.label)}
onChange={() => toggle('colors', c.label)}
className="sr-only"
/>
<span
className={cn(
'flex h-5 w-5 shrink-0 rounded-full border-2',
active.colors.includes(c.label) ? 'border-foreground' : 'border-transparent',
)}
style={{ backgroundColor: c.color || undefined }}
/>
{c.label}
</label>
))}
</FilterGroup>
)}
{props.showStyle === 'yes' && styles.length > 0 && (
<FilterGroup label="Style">
{styles.map((s) => (
<Checkbox
key={s}
checked={active.styles.includes(s)}
onChange={() => toggle('styles', s)}
label={s}
/>
))}
</FilterGroup>
)}
{props.showSize === 'yes' && sizes.length > 0 && (
<FilterGroup label="Size">
{sizes.map((s) => (
<Checkbox
key={s}
checked={active.sizes.includes(s)}
onChange={() => toggle('sizes', s)}
label={s}
/>
))}
</FilterGroup>
)}
{props.showMaterial === 'yes' && materials.length > 0 && (
<FilterGroup label="Material">
{materials.map((m) => (
<Checkbox
key={m}
checked={active.materials.includes(m)}
onChange={() => toggle('materials', m)}
label={m}
/>
))}
</FilterGroup>
)}
{props.showProductType === 'yes' && productTypes.length > 0 && (
<FilterGroup label="Product type">
{productTypes.map((pt) => (
<Checkbox
key={pt}
checked={active.productTypes.includes(pt)}
onChange={() => toggle('productTypes', pt)}
label={pt}
/>
))}
</FilterGroup>
)}
{props.showTags === 'yes' && tags.length > 0 && (
<FilterGroup label="Tags">
{tags.map((t) => (
<Checkbox
key={t}
checked={active.tags.includes(t)}
onChange={() => toggle('tags', t)}
label={t}
/>
))}
</FilterGroup>
)}
{metafieldFilters.map((mf, i) => {
const mfKey = `${mf.namespace}.${mf.key}`;
const selected = active.metafieldValues[mfKey] ?? [];
return (
<FilterGroup key={mfKey + i} label={mf.label || mfKey}>
{mf.values.map((v) => v.label).filter(Boolean).map((val) => (
<Checkbox
key={val}
checked={selected.includes(val)}
onChange={(checked) => {
const next = checked
? [...selected, val]
: selected.filter((v) => v !== val);
onChange({ metafieldValues: { ...active.metafieldValues, [mfKey]: next } });
}}
label={val}
/>
))}
</FilterGroup>
);
})}
</aside>
);
}
// ─── Build Shopify ProductFilter array ──────────────────────────────────────────
function buildProductFilters(active: ActiveFilters): ProductFilter[] {
const filters: ProductFilter[] = [];
if (active.availability) filters.push({ available: true });
if (active.minPrice !== '' || active.maxPrice !== '') {
filters.push({
price: {
min: active.minPrice !== '' ? parseFloat(active.minPrice) : undefined,
max: active.maxPrice !== '' ? parseFloat(active.maxPrice) : undefined,
},
});
}
for (const pt of active.productTypes) filters.push({ productType: pt });
for (const v of active.vendors) filters.push({ productVendor: v });
for (const t of active.tags) filters.push({ tag: t });
for (const c of active.colors) filters.push({ variantOption: { name: 'Color', value: c } });
for (const s of active.styles) filters.push({ variantOption: { name: 'Style', value: s } });
for (const s of active.sizes) filters.push({ variantOption: { name: 'Size', value: s } });
for (const m of active.materials) filters.push({ variantOption: { name: 'Material', value: m } });
for (const [mfKey, vals] of Object.entries(active.metafieldValues)) {
const [namespace, key] = mfKey.split('.');
for (const value of vals) {
filters.push({ productMetafield: { namespace, key, value } });
}
}
return filters;
}
// ─── Main component ──────────────────────────────────────────────────────────
export function CollectionView(props: CollectionProps) {
const { collection: selected, showDescription, showCoverImage, customCoverImage, columns, limit, defaultSort } = props;
const { handle: paramHandle } = useParams<{ handle?: string }>();
const handle = selected?.handle ?? paramHandle ?? '';
const [sort, setSort] = useState<CollectionSortKey>(defaultSort);
const [reverse, setReverse] = useState(false);
const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
const [active, setActive] = useState<ActiveFilters>({
availability: false,
productTypes: [],
vendors: [],
tags: [],
colors: [],
styles: [],
sizes: [],
materials: [],
minPrice: '',
maxPrice: '',
metafieldValues: {},
});
const patchActive = useCallback((patch: Partial<ActiveFilters>) => {
setActive((prev) => ({ ...prev, ...patch }));
}, []);
const productFilters = buildProductFilters(active);
const handleSortChange = (value: string) => {
if (value === 'PRICE_DESC') {
setSort('PRICE');
setReverse(true);
} else {
setSort(value as CollectionSortKey);
setReverse(false);
}
};
const sortValue = sort === 'PRICE' && reverse ? 'PRICE_DESC' : sort;
const { collection, loading, hasNextPage, fetchMore } = useCollectionProducts(handle, {
first: limit,
sortKey: sort,
reverse,
filters: productFilters.length ? productFilters : undefined,
});
const products = collection?.products ?? [];
const description = collection?.description ?? (selected as any)?.description;
const collectionImage = customCoverImage || collection?.image?.url;
if (!selected && !paramHandle) {
return ( return (
<section className="bg-background pb-24 pt-12 md:pt-20"> <section className="bg-background pb-24 pt-12 md:pt-20">
<div className="container mx-auto max-w-7xl px-6"> <div className="container mx-auto max-w-7xl px-6">
<header className="mx-auto mb-14 flex max-w-2xl flex-col items-center gap-3 text-center"> <header className="mx-auto mb-14 flex max-w-2xl flex-col items-center gap-3 text-center">
<Skeleton className="h-3 w-24" /> <Skeleton className="h-3 w-24" />
<Skeleton className="h-10 w-3/4" /> <Skeleton className="h-10 w-3/4" />
{showDescription === "yes" ? (
<Skeleton className="mt-1 h-5 w-2/3" />
) : null}
</header> </header>
<div className="grid grid-cols-2 gap-x-6 gap-y-12 md:grid-cols-3 lg:grid-cols-4"> <div className="grid grid-cols-2 gap-x-6 gap-y-12 md:grid-cols-3 lg:grid-cols-4">
{Array.from({ length: 8 }).map((_, i) => ( {Array.from({ length: 8 }).map((_, i) => (
@@ -37,39 +462,125 @@ export function CollectionView({
); );
} }
const products = (collection?.products as any[] | undefined) ?? [];
const description = collection?.description ?? selected.description;
return ( return (
<section className="bg-background pb-24 pt-12 md:pt-20"> <section className="bg-background pb-24 pt-12 md:pt-20">
<div className="container mx-auto max-w-7xl px-6"> <div className="container mx-auto max-w-7xl px-6">
<header className="mx-auto mb-14 max-w-2xl text-center"> {/* Cover image */}
{showCoverImage === 'yes' && collectionImage && (
<div className="mb-10 overflow-hidden rounded-lg">
<img
src={collectionImage}
alt={collection?.title ?? ''}
className="h-48 w-full object-cover md:h-72 lg:h-80"
/>
</div>
)}
{/* Header */}
<header className="mb-10">
<p className="mb-3 text-xs uppercase tracking-[0.2em] text-muted-foreground"> <p className="mb-3 text-xs uppercase tracking-[0.2em] text-muted-foreground">
Collection Collection
</p> </p>
<Typography variant="h1"> <Typography variant="h1">
{collection?.title ?? selected.title} {collection?.title ?? (selected as any)?.title ?? paramHandle}
</Typography> </Typography>
{showDescription === "yes" && description ? ( {showDescription === 'yes' && description ? (
<Typography variant="subtitle1" className="mt-4"> <Typography variant="subtitle1" className="mt-4 max-w-2xl">
{description} {description}
</Typography> </Typography>
) : null} ) : null}
</header> </header>
<div className="grid grid-cols-2 gap-x-6 gap-y-12 md:grid-cols-3 lg:grid-cols-4"> {/* Mobile filter toggle */}
{loading <div className="mb-4 flex items-center justify-between md:hidden">
? Array.from({ length: 8 }).map((_, i) => ( <button
<Skeleton key={i} className="aspect-[4/5] w-full" /> type="button"
)) onClick={() => setMobileFiltersOpen((o) => !o)}
: products.map((p: any) => <ProductCard key={p.id} product={p} />)} className="flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-medium"
>
<SlidersHorizontal size={14} />
Filters
</button>
<Select value={sortValue} onValueChange={handleSortChange}>
<SelectTrigger className="h-auto px-3 py-2 text-sm">
<SelectValue>
{[...SORT_OPTIONS, { label: 'Price: High to Low', value: 'PRICE_DESC' }].find((o) => o.value === sortValue)?.label}
</SelectValue>
</SelectTrigger>
<SelectContent>
{SORT_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
))}
<SelectItem value="PRICE_DESC">Price: High to Low</SelectItem>
</SelectContent>
</Select>
</div> </div>
{!loading && products.length === 0 ? ( {/* Mobile filter panel */}
<div className="mx-auto mt-12 max-w-md text-center text-sm text-muted-foreground"> {mobileFiltersOpen && (
This collection has no products yet. <div className="mb-6 rounded-lg border border-border p-4 md:hidden">
<Sidebar props={props} active={active} onChange={patchActive} />
</div> </div>
) : null} )}
<div className="flex gap-10">
{/* Desktop sidebar */}
<div className="hidden md:block">
<Sidebar props={props} active={active} onChange={patchActive} />
</div>
{/* Product area */}
<div className="min-w-0 flex-1">
{/* Sort + count bar */}
<div className="mb-6 flex items-center justify-between">
<p className="text-sm text-muted-foreground">
{loading ? 'Loading…' : `${products.length} product${products.length === 1 ? '' : 's'}`}
</p>
<div className="hidden md:block">
<Select value={sortValue} onValueChange={handleSortChange}>
<SelectTrigger className="h-auto px-3 py-1.5 text-sm">
<SelectValue>
{[...SORT_OPTIONS, { label: 'Price: High to Low', value: 'PRICE_DESC' }].find((o) => o.value === sortValue)?.label}
</SelectValue>
</SelectTrigger>
<SelectContent>
{SORT_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
))}
<SelectItem value="PRICE_DESC">Price: High to Low</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Grid */}
<div className={cn('grid gap-x-6 gap-y-10', colClass[columns])}>
{loading
? Array.from({ length: limit }).map((_, i) => (
<Skeleton key={i} className="aspect-[4/5] w-full" />
))
: products.map((p: any) => <ProductCard key={p.id} product={p} />)}
</div>
{!loading && products.length === 0 && (
<div className="mt-16 text-center text-sm text-muted-foreground">
No products found in this collection.
</div>
)}
{hasNextPage && !loading && (
<div className="mt-12 flex justify-center">
<button
type="button"
onClick={fetchMore}
className="rounded-md border border-border px-8 py-3 text-sm font-medium hover:bg-muted"
>
Load more
</button>
</div>
)}
</div>
</div>
</div> </div>
</section> </section>
); );

View File

@@ -47,8 +47,8 @@ export function FeaturedProductView({
<Skeleton className="h-4 w-4/6" /> <Skeleton className="h-4 w-4/6" />
</div> </div>
<div className="mt-2 flex flex-wrap gap-3"> <div className="mt-2 flex flex-wrap gap-3">
<Skeleton className="h-11 w-32 rounded-full" /> <Skeleton className="h-11 w-32 rounded-md" />
<Skeleton className="h-11 w-32 rounded-full" /> <Skeleton className="h-11 w-32 rounded-md" />
</div> </div>
</div> </div>
</div> </div>
@@ -111,13 +111,13 @@ export function FeaturedProductView({
await cart.addItem(variant.id, 1); await cart.addItem(variant.id, 1);
cart.openCart(); cart.openCart();
}} }}
className="inline-flex items-center justify-center rounded-full bg-foreground px-6 py-3 text-sm font-medium tracking-wide text-background hover:opacity-90" className="inline-flex items-center justify-center rounded-md bg-foreground px-6 py-3 text-sm font-medium tracking-wide text-background hover:opacity-90"
> >
{ctaLabel} {ctaLabel}
</button> </button>
<Link <Link
to={`/products/${product.handle}`} to={`/products/${product.handle}`}
className="inline-flex items-center justify-center rounded-full border border-foreground px-6 py-3 text-sm font-medium tracking-wide hover:opacity-80" className="inline-flex items-center justify-center rounded-md border border-foreground px-6 py-3 text-sm font-medium tracking-wide hover:opacity-80"
> >
View details View details
</Link> </Link>

View File

@@ -46,14 +46,14 @@ export function ProductDetailsView({ product: selected }: ProductDetailsProps) {
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<Skeleton className="h-3 w-16" /> <Skeleton className="h-3 w-16" />
<div className="flex gap-2"> <div className="flex gap-2">
<Skeleton className="h-10 w-16 rounded-full" /> <Skeleton className="h-10 w-16 rounded-md" />
<Skeleton className="h-10 w-16 rounded-full" /> <Skeleton className="h-10 w-16 rounded-md" />
<Skeleton className="h-10 w-16 rounded-full" /> <Skeleton className="h-10 w-16 rounded-md" />
</div> </div>
</div> </div>
<div className="flex items-center gap-4 pt-2"> <div className="flex items-center gap-4 pt-2">
<Skeleton className="h-11 w-32 rounded-full" /> <Skeleton className="h-11 w-32 rounded-md" />
<Skeleton className="h-11 flex-1 rounded-full" /> <Skeleton className="h-11 flex-1 rounded-md" />
</div> </div>
<div className="space-y-2 border-t border-border pt-6"> <div className="space-y-2 border-t border-border pt-6">
<Skeleton className="h-3 w-20" /> <Skeleton className="h-3 w-20" />
@@ -157,7 +157,7 @@ export function ProductDetailsView({ product: selected }: ProductDetailsProps) {
key={val} key={val}
onClick={() => matching && setVariant(matching.node)} onClick={() => matching && setVariant(matching.node)}
className={cn( className={cn(
"min-w-12 rounded-full border px-4 py-2 text-sm transition-colors", "min-w-12 rounded-md border px-4 py-2 text-sm transition-colors",
selected selected
? "border-foreground bg-foreground text-background" ? "border-foreground bg-foreground text-background"
: "border-border hover:border-foreground", : "border-border hover:border-foreground",
@@ -172,7 +172,7 @@ export function ProductDetailsView({ product: selected }: ProductDetailsProps) {
))} ))}
<div className="flex items-center gap-4 pt-2"> <div className="flex items-center gap-4 pt-2">
<div className="flex items-center gap-3 rounded-full border border-border px-4 py-2"> <div className="flex items-center gap-3 rounded-md border border-border px-4 py-2">
<button <button
onClick={() => setQuantity((q) => Math.max(1, q - 1))} onClick={() => setQuantity((q) => Math.max(1, q - 1))}
className="text-base hover:opacity-60" className="text-base hover:opacity-60"
@@ -190,7 +190,7 @@ export function ProductDetailsView({ product: selected }: ProductDetailsProps) {
<button <button
onClick={onAdd} onClick={onAdd}
disabled={!variant || adding} disabled={!variant || adding}
className="flex-1 rounded-full bg-foreground px-6 py-3 text-sm font-medium tracking-wide text-background transition-opacity hover:opacity-90 disabled:opacity-50" className="flex-1 rounded-md bg-foreground px-6 py-3 text-sm font-medium tracking-wide text-background transition-opacity hover:opacity-90 disabled:opacity-50"
> >
{adding ? ( {adding ? (
<span className="flex items-center justify-center gap-2"> <span className="flex items-center justify-center gap-2">

View File

@@ -50,7 +50,7 @@ export function ProductsCarousel({
const data = await getCollectionProducts(collection.handle, { const data = await getCollectionProducts(collection.handle, {
first: limit, first: limit,
}); });
if (!cancelled) setProducts(data?.products ?? []); if (!cancelled) setProducts(data?.collection?.products ?? []);
} else { } else {
const data = await getProducts({ const data = await getProducts({
first: limit, first: limit,

View File

@@ -42,7 +42,7 @@ export function ProductsGrid({
const data = await getCollectionProducts(collection.handle, { const data = await getCollectionProducts(collection.handle, {
first: limit, first: limit,
}); });
if (!cancelled) setProducts(data?.products ?? []); if (!cancelled) setProducts(data?.collection?.products ?? []);
} else { } else {
const data = await getProducts({ first: limit, sortKey: "BEST_SELLING" }); const data = await getProducts({ first: limit, sortKey: "BEST_SELLING" });
if (!cancelled) setProducts(data ?? []); if (!cancelled) setProducts(data ?? []);

View File

@@ -0,0 +1,242 @@
import { ComponentConfig } from '@reacteditor/core';
import { Search } from 'lucide-react';
import { SearchProductsView, type SearchProductsProps } from '@/components/commerce/search-products';
export const searchProductsEditor: ComponentConfig<SearchProductsProps> = {
label: 'Search & filter',
icon: <Search size={16} />,
category: 'commerce',
defaultProps: {
heading: 'Shop',
subheading: 'Browse our full collection.',
columns: '4',
limit: 24,
showAvailability: 'yes',
showPriceRange: 'yes',
showProductType: 'yes',
productTypeOptions: [
{ label: 'T-Shirts' },
{ label: 'Pants' },
{ label: 'Outerwear' },
{ label: 'Accessories' },
{ label: 'Shoes' },
],
showVendor: 'yes',
vendorOptions: [
{ label: 'Maison' },
{ label: 'Atelier' },
{ label: 'Studio' },
],
showTags: 'yes',
tagOptions: [
{ label: 'New' },
{ label: 'Sale' },
{ label: 'Bestseller' },
{ label: 'Limited Edition' },
],
showColor: 'yes',
colorOptions: [
{ label: 'Black', color: '#000000' },
{ label: 'White', color: '#FFFFFF' },
{ label: 'Navy', color: '#1e3a5f' },
{ label: 'Red', color: '#c0392b' },
],
showStyle: 'no',
styleOptions: [],
showSize: 'yes',
sizeOptions: [
{ label: 'XS' },
{ label: 'S' },
{ label: 'M' },
{ label: 'L' },
{ label: 'XL' },
],
showMaterial: 'no',
materialOptions: [],
metafieldFilters: [],
defaultSort: 'BEST_SELLING',
},
fields: {
heading: { label: 'Heading', type: 'text', contentEditable: true },
subheading: { label: 'Subheading', type: 'textarea', contentEditable: true },
columns: {
label: 'Columns',
type: 'radio',
options: [
{ label: '2', value: '2' },
{ label: '3', value: '3' },
{ label: '4', value: '4' },
],
},
limit: { label: 'Products per page', type: 'number', min: 4, max: 48 },
defaultSort: {
label: 'Default sort',
type: 'select',
options: [
{ label: 'Best Selling', value: 'BEST_SELLING' },
{ label: 'Relevance', value: 'RELEVANCE' },
{ label: 'Newest', value: 'NEWEST' },
{ label: 'Price: Low to High', value: 'PRICE_ASC' },
{ label: 'Price: High to Low', value: 'PRICE_DESC' },
{ label: 'Alphabetical', value: 'TITLE_ASC' },
],
},
showAvailability: {
label: 'Availability filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
showPriceRange: {
label: 'Price range filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
showProductType: {
label: 'Product type filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
productTypeOptions: {
label: 'Product types',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (it: any) => it?.label || 'Type',
arrayFields: {
label: { label: 'Type name', type: 'text' },
},
},
showVendor: {
label: 'Brand / vendor filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
vendorOptions: {
label: 'Brands',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (it: any) => it?.label || 'Brand',
arrayFields: {
label: { label: 'Brand name', type: 'text' },
},
},
showTags: {
label: 'Tags filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
tagOptions: {
label: 'Tags',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (it: any) => it?.label || 'Tag',
arrayFields: {
label: { label: 'Tag name', type: 'text' },
},
},
showColor: {
label: 'Color filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
colorOptions: {
label: 'Colors',
type: 'array',
defaultItemProps: { label: '', color: '#000000' },
getItemSummary: (it: any) => it?.label || 'Color',
arrayFields: {
label: { label: 'Color name', type: 'text' },
color: { label: 'Color', type: 'color' },
},
},
showStyle: {
label: 'Style filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
styleOptions: {
label: 'Styles',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (it: any) => it?.label || 'Style',
arrayFields: {
label: { label: 'Style name', type: 'text' },
},
},
showSize: {
label: 'Size filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
sizeOptions: {
label: 'Sizes',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (it: any) => it?.label || 'Size',
arrayFields: {
label: { label: 'Size name', type: 'text' },
},
},
showMaterial: {
label: 'Material filter',
type: 'radio',
options: [
{ label: 'Show', value: 'yes' },
{ label: 'Hide', value: 'no' },
],
},
materialOptions: {
label: 'Materials',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (it: any) => it?.label || 'Material',
arrayFields: {
label: { label: 'Material name', type: 'text' },
},
},
metafieldFilters: {
label: 'Metafield filters',
type: 'array',
defaultItemProps: { namespace: '', key: '', label: '', values: [{ label: '' }] },
getItemSummary: (it: any) => it?.label || it?.key || 'Metafield',
arrayFields: {
namespace: { label: 'Namespace', type: 'text' },
key: { label: 'Key', type: 'text' },
label: { label: 'Label', type: 'text' },
values: {
label: 'Values',
type: 'array',
defaultItemProps: { label: '' },
getItemSummary: (v: any) => v?.label || 'Value',
arrayFields: {
label: { label: 'Value', type: 'text' },
},
},
},
},
},
render: (props) => <SearchProductsView {...props} />,
};

View File

@@ -0,0 +1,562 @@
import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router';
import { ChevronDown, SlidersHorizontal, X } from 'lucide-react';
import { useShopifySearch, type SearchFilters, type SortOption } from '@/hooks/use-shopify-search';
import { ProductCard } from './product-card';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';
import { cn } from '@/lib/utils';
type FilterOption = { label: string };
type ColorOption = { label: string; color: string };
export type SearchProductsProps = {
heading: string;
subheading: string;
columns: '2' | '3' | '4';
limit: number;
showAvailability: 'yes' | 'no';
showPriceRange: 'yes' | 'no';
showProductType: 'yes' | 'no';
productTypeOptions: FilterOption[];
showVendor: 'yes' | 'no';
vendorOptions: FilterOption[];
showTags: 'yes' | 'no';
tagOptions: FilterOption[];
showColor: 'yes' | 'no';
colorOptions: ColorOption[];
showStyle: 'yes' | 'no';
styleOptions: FilterOption[];
showSize: 'yes' | 'no';
sizeOptions: FilterOption[];
showMaterial: 'yes' | 'no';
materialOptions: FilterOption[];
metafieldFilters: { namespace: string; key: string; label: string; values: { label: string }[] }[];
defaultSort: SortOption;
};
const SORT_OPTIONS: { label: string; value: SortOption }[] = [
{ label: 'Relevance', value: 'RELEVANCE' },
{ label: 'Best Selling', value: 'BEST_SELLING' },
{ label: 'Newest', value: 'NEWEST' },
{ label: 'Price: Low to High', value: 'PRICE_ASC' },
{ label: 'Price: High to Low', value: 'PRICE_DESC' },
{ label: 'Alphabetical', value: 'TITLE_ASC' },
];
const colClass: Record<SearchProductsProps['columns'], string> = {
'2': 'grid-cols-2',
'3': 'grid-cols-2 md:grid-cols-3',
'4': 'grid-cols-2 md:grid-cols-3 lg:grid-cols-4',
};
// ─── Filter group (collapsible) ────────────────────────────────────────────────
function FilterGroup({ label, children, defaultOpen = true }: {
label: string;
children: React.ReactNode;
defaultOpen?: boolean;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<div className="border-b border-border py-4">
<button
type="button"
onClick={() => setOpen((o) => !o)}
className="flex w-full items-center justify-between text-xs font-semibold uppercase tracking-[0.15em] text-foreground"
>
{label}
<ChevronDown
size={14}
className={cn('transition-transform', open ? 'rotate-180' : '')}
/>
</button>
{open && <div className="mt-3 space-y-2">{children}</div>}
</div>
);
}
function Checkbox({ checked, onChange, label }: {
checked: boolean;
onChange: (v: boolean) => void;
label: string;
}) {
return (
<label className="flex cursor-pointer items-center gap-2.5 text-sm text-foreground/80 hover:text-foreground">
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
className="sr-only"
/>
<span
className={cn(
'flex h-4 w-4 shrink-0 items-center justify-center rounded border',
checked ? 'border-foreground bg-foreground' : 'border-border',
)}
>
{checked && (
<svg viewBox="0 0 10 8" className="h-2.5 w-2.5 fill-background" aria-hidden>
<path d="M1 4l3 3 5-6" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)}
</span>
{label}
</label>
);
}
// ─── Sidebar ────────────────────────────────────────────────────────────────────
type ActiveFilters = {
availability: boolean;
productTypes: string[];
vendors: string[];
tags: string[];
colors: string[];
styles: string[];
sizes: string[];
materials: string[];
minPrice: string;
maxPrice: string;
metafieldValues: Record<string, string[]>;
};
function Sidebar({
props,
active,
onChange,
}: {
props: SearchProductsProps;
active: ActiveFilters;
onChange: (patch: Partial<ActiveFilters>) => void;
}) {
const productTypes = (props.productTypeOptions ?? []).map((o) => o.label).filter(Boolean);
const vendors = (props.vendorOptions ?? []).map((o) => o.label).filter(Boolean);
const tags = (props.tagOptions ?? []).map((o) => o.label).filter(Boolean);
const colors = (props.colorOptions ?? []) as ColorOption[];
const styles = (props.styleOptions ?? []).map((o) => o.label).filter(Boolean);
const sizes = (props.sizeOptions ?? []).map((o) => o.label).filter(Boolean);
const materials = (props.materialOptions ?? []).map((o) => o.label).filter(Boolean);
const metafieldFilters = (props.metafieldFilters ?? []).filter((mf) => mf.namespace && mf.key);
function toggle(key: 'productTypes' | 'vendors' | 'tags' | 'colors' | 'styles' | 'sizes' | 'materials', value: string) {
const arr = active[key];
onChange({ [key]: arr.includes(value) ? arr.filter((v) => v !== value) : [...arr, value] });
}
const hasActiveFilters =
active.availability ||
active.productTypes.length > 0 ||
active.vendors.length > 0 ||
active.tags.length > 0 ||
active.colors.length > 0 ||
active.styles.length > 0 ||
active.sizes.length > 0 ||
active.materials.length > 0 ||
active.minPrice !== '' ||
active.maxPrice !== '' ||
Object.values(active.metafieldValues).some((arr) => arr.length > 0);
return (
<aside className="w-full shrink-0 md:w-52 lg:w-56">
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="text-xs font-semibold uppercase tracking-[0.15em]">Filters</span>
{hasActiveFilters && (
<button
type="button"
onClick={() =>
onChange({
availability: false,
productTypes: [],
vendors: [],
tags: [],
colors: [],
styles: [],
sizes: [],
materials: [],
minPrice: '',
maxPrice: '',
metafieldValues: {},
})
}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
<X size={12} /> Clear all
</button>
)}
</div>
{props.showAvailability === 'yes' && (
<FilterGroup label="Availability">
<Checkbox
checked={active.availability}
onChange={(v) => onChange({ availability: v })}
label="In stock"
/>
</FilterGroup>
)}
{props.showPriceRange === 'yes' && (
<FilterGroup label="Price">
<div className="flex items-center gap-2">
<input
type="number"
min={0}
placeholder="Min"
value={active.minPrice}
onChange={(e) => onChange({ minPrice: e.target.value })}
className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm"
/>
<span className="text-muted-foreground"></span>
<input
type="number"
min={0}
placeholder="Max"
value={active.maxPrice}
onChange={(e) => onChange({ maxPrice: e.target.value })}
className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm"
/>
</div>
</FilterGroup>
)}
{props.showVendor === 'yes' && vendors.length > 0 && (
<FilterGroup label="Brand">
{vendors.map((v) => (
<Checkbox
key={v}
checked={active.vendors.includes(v)}
onChange={() => toggle('vendors', v)}
label={v}
/>
))}
</FilterGroup>
)}
{props.showColor === 'yes' && colors.length > 0 && (
<FilterGroup label="Color">
{colors.filter((c) => c.label).map((c) => (
<label
key={c.label}
className="flex cursor-pointer items-center gap-2.5 text-sm text-foreground/80 hover:text-foreground"
>
<input
type="checkbox"
checked={active.colors.includes(c.label)}
onChange={() => toggle('colors', c.label)}
className="sr-only"
/>
<span
className={cn(
'flex h-5 w-5 shrink-0 rounded-full border-2',
active.colors.includes(c.label) ? 'border-foreground' : 'border-transparent',
)}
style={{ backgroundColor: c.color || undefined }}
/>
{c.label}
</label>
))}
</FilterGroup>
)}
{props.showStyle === 'yes' && styles.length > 0 && (
<FilterGroup label="Style">
{styles.map((s) => (
<Checkbox
key={s}
checked={active.styles.includes(s)}
onChange={() => toggle('styles', s)}
label={s}
/>
))}
</FilterGroup>
)}
{props.showSize === 'yes' && sizes.length > 0 && (
<FilterGroup label="Size">
{sizes.map((s) => (
<Checkbox
key={s}
checked={active.sizes.includes(s)}
onChange={() => toggle('sizes', s)}
label={s}
/>
))}
</FilterGroup>
)}
{props.showMaterial === 'yes' && materials.length > 0 && (
<FilterGroup label="Material">
{materials.map((m) => (
<Checkbox
key={m}
checked={active.materials.includes(m)}
onChange={() => toggle('materials', m)}
label={m}
/>
))}
</FilterGroup>
)}
{props.showProductType === 'yes' && productTypes.length > 0 && (
<FilterGroup label="Product type">
{productTypes.map((pt) => (
<Checkbox
key={pt}
checked={active.productTypes.includes(pt)}
onChange={() => toggle('productTypes', pt)}
label={pt}
/>
))}
</FilterGroup>
)}
{props.showTags === 'yes' && tags.length > 0 && (
<FilterGroup label="Tags">
{tags.map((t) => (
<Checkbox
key={t}
checked={active.tags.includes(t)}
onChange={() => toggle('tags', t)}
label={t}
/>
))}
</FilterGroup>
)}
{metafieldFilters.map((mf, i) => {
const mfKey = `${mf.namespace}.${mf.key}`;
const selected = active.metafieldValues[mfKey] ?? [];
return (
<FilterGroup key={mfKey + i} label={mf.label || mfKey}>
{mf.values.map((v) => v.label).filter(Boolean).map((val) => (
<Checkbox
key={val}
checked={selected.includes(val)}
onChange={(checked) => {
const next = checked
? [...selected, val]
: selected.filter((v) => v !== val);
onChange({ metafieldValues: { ...active.metafieldValues, [mfKey]: next } });
}}
label={val}
/>
))}
</FilterGroup>
);
})}
</aside>
);
}
// ─── Main component ──────────────────────────────────────────────────────────
export function SearchProductsView(props: SearchProductsProps) {
const [searchParams, setSearchParams] = useSearchParams();
const initialQ = searchParams.get('q') ?? '';
const [query, setQuery] = useState(initialQ);
const [inputValue, setInputValue] = useState(initialQ);
const [sort, setSort] = useState<SortOption>(props.defaultSort);
const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
const [active, setActive] = useState<ActiveFilters>({
availability: false,
productTypes: [],
vendors: [],
tags: [],
colors: [],
styles: [],
sizes: [],
materials: [],
minPrice: '',
maxPrice: '',
metafieldValues: {},
});
const patchActive = useCallback((patch: Partial<ActiveFilters>) => {
setActive((prev) => ({ ...prev, ...patch }));
}, []);
const filters: SearchFilters = {
q: query,
sort,
availability: active.availability || undefined,
productTypes: active.productTypes.length ? active.productTypes : undefined,
vendors: active.vendors.length ? active.vendors : undefined,
tags: active.tags.length ? active.tags : undefined,
colors: active.colors.length ? active.colors : undefined,
styles: active.styles.length ? active.styles : undefined,
sizes: active.sizes.length ? active.sizes : undefined,
materials: active.materials.length ? active.materials : undefined,
minPrice: active.minPrice !== '' ? parseFloat(active.minPrice) : undefined,
maxPrice: active.maxPrice !== '' ? parseFloat(active.maxPrice) : undefined,
metafields: (() => {
const mfs = Object.entries(active.metafieldValues).flatMap(([mfKey, vals]) => {
const [namespace, key] = mfKey.split('.');
return vals.map((value) => ({ namespace, key, value }));
});
return mfs.length ? mfs : undefined;
})(),
};
const { products, loading, error, hasNextPage, fetchMore } = useShopifySearch(filters, {
first: props.limit,
});
// Sync ?q= param when query changes
useEffect(() => {
const params = new URLSearchParams(searchParams);
if (query) params.set('q', query); else params.delete('q');
setSearchParams(params, { replace: true });
}, [query]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
setQuery(inputValue.trim());
};
return (
<section className="bg-background py-12 md:py-16">
<div className="container mx-auto max-w-7xl px-6">
{/* Page header */}
<div className="mb-10">
{props.heading && (
<h1 className="mb-2 font-heading text-4xl font-bold tracking-tight text-foreground md:text-5xl">
{props.heading}
</h1>
)}
{props.subheading && (
<p className="text-muted-foreground">{props.subheading}</p>
)}
{/* Search bar (mobile only desktop version lives in the product area) */}
<form onSubmit={handleSearch} className="mt-6 flex gap-2 md:hidden">
<input
type="search"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Search products…"
className="flex-1 rounded-md border border-border bg-background px-4 py-2.5 text-sm outline-none focus:border-foreground"
/>
<button
type="submit"
className="rounded-md bg-foreground px-5 py-2.5 text-sm font-medium text-background hover:opacity-90"
>
Search
</button>
</form>
</div>
{/* Mobile filter toggle */}
<div className="mb-4 flex items-center justify-between md:hidden">
<button
type="button"
onClick={() => setMobileFiltersOpen((o) => !o)}
className="flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-medium"
>
<SlidersHorizontal size={14} />
Filters
</button>
<Select value={sort} onValueChange={(v) => setSort(v as SortOption)}>
<SelectTrigger className="h-auto px-3 py-2 text-sm">
<SelectValue>{SORT_OPTIONS.find((o) => o.value === sort)?.label}</SelectValue>
</SelectTrigger>
<SelectContent>
{SORT_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Mobile filter panel */}
{mobileFiltersOpen && (
<div className="mb-6 rounded-lg border border-border p-4 md:hidden">
<Sidebar props={props} active={active} onChange={patchActive} />
</div>
)}
<div className="flex gap-10">
{/* Desktop sidebar */}
<div className="hidden md:block">
<Sidebar props={props} active={active} onChange={patchActive} />
</div>
{/* Product area */}
<div className="min-w-0 flex-1">
{/* Search bar (desktop only) */}
<form onSubmit={handleSearch} className="mb-4 hidden gap-2 md:flex">
<input
type="search"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Search products…"
className="flex-1 rounded-md border border-border bg-background px-4 py-2.5 text-sm outline-none focus:border-foreground"
/>
<button
type="submit"
className="rounded-md bg-foreground px-5 py-2.5 text-sm font-medium text-background hover:opacity-90"
>
Search
</button>
</form>
{/* Sort + count bar */}
<div className="mb-6 flex items-center justify-between">
<p className="text-sm text-muted-foreground">
{loading ? 'Loading…' : `${products.length} product${products.length === 1 ? '' : 's'}`}
</p>
<div className="hidden md:block">
<Select value={sort} onValueChange={(v) => setSort(v as SortOption)}>
<SelectTrigger className="h-auto px-3 py-1.5 text-sm">
<SelectValue>{SORT_OPTIONS.find((o) => o.value === sort)?.label}</SelectValue>
</SelectTrigger>
<SelectContent>
{SORT_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{error && (
<p className="rounded-md border border-border p-4 text-sm text-muted-foreground">
{error}
</p>
)}
{/* Grid */}
<div className={cn('grid gap-x-6 gap-y-10', colClass[props.columns])}>
{loading
? Array.from({ length: props.limit }).map((_, i) => (
<Skeleton key={i} className="aspect-[4/5] w-full" />
))
: products.map((p) => <ProductCard key={p.id} product={p} />)}
</div>
{!loading && products.length === 0 && !error && (
<div className="mt-16 text-center text-sm text-muted-foreground">
No products found.{query ? ` Try a different search term.` : ''}
</div>
)}
{hasNextPage && !loading && (
<div className="mt-12 flex justify-center">
<button
type="button"
onClick={fetchMore}
className="rounded-md border border-border px-8 py-3 text-sm font-medium hover:bg-muted"
>
Load more
</button>
</div>
)}
</div>
</div>
</div>
</section>
);
}

View File

@@ -63,7 +63,7 @@ export function CTA({
{primaryCta?.label ? ( {primaryCta?.label ? (
<Link <Link
to={primaryCta.href || "#"} to={primaryCta.href || "#"}
className="inline-flex items-center justify-center rounded-full bg-white px-6 py-3 text-sm font-medium tracking-wide text-black hover:opacity-90" className="inline-flex items-center justify-center rounded-md bg-white px-6 py-3 text-sm font-medium tracking-wide text-black hover:opacity-90"
> >
{primaryCta.label} {primaryCta.label}
</Link> </Link>
@@ -71,7 +71,7 @@ export function CTA({
{secondaryCta?.label ? ( {secondaryCta?.label ? (
<Link <Link
to={secondaryCta.href || "#"} to={secondaryCta.href || "#"}
className="inline-flex items-center justify-center rounded-full border border-white px-6 py-3 text-sm font-medium tracking-wide text-white hover:bg-white/10" className="inline-flex items-center justify-center rounded-md border border-white px-6 py-3 text-sm font-medium tracking-wide text-white hover:bg-white/10"
> >
{secondaryCta.label} {secondaryCta.label}
</Link> </Link>

View File

@@ -97,7 +97,7 @@ export function Hero({
<Link <Link
to={primaryCta.href || "#"} to={primaryCta.href || "#"}
className={cn( className={cn(
"inline-flex items-center justify-center rounded-full px-6 py-3 text-sm font-medium tracking-wide transition-opacity hover:opacity-90", "inline-flex items-center justify-center rounded-md px-6 py-3 text-sm font-medium tracking-wide transition-opacity hover:opacity-90",
isDark ? "bg-white text-black" : "bg-foreground text-background", isDark ? "bg-white text-black" : "bg-foreground text-background",
)} )}
> >
@@ -108,7 +108,7 @@ export function Hero({
<Link <Link
to={secondaryCta.href || "#"} to={secondaryCta.href || "#"}
className={cn( className={cn(
"inline-flex items-center justify-center rounded-full border px-6 py-3 text-sm font-medium tracking-wide transition-opacity hover:opacity-80", "inline-flex items-center justify-center rounded-md border px-6 py-3 text-sm font-medium tracking-wide transition-opacity hover:opacity-80",
isDark ? "border-white text-white" : "border-foreground text-foreground", isDark ? "border-white text-white" : "border-foreground text-foreground",
)} )}
> >

View File

@@ -13,17 +13,15 @@ export const navigationEditor: ComponentConfig<NavigationProps> = {
brand: "Maison", brand: "Maison",
logo: "", logo: "",
links: [ links: [
{ label: "Shop", href: "/collections" }, { label: "Mens", href: "/collections/mens" },
{ label: "Lookbook", href: "/lookbook" }, { label: "Womens", href: "/collections/womens" },
{ label: "Journal", href: "/journal" }, { label: "Shop", href: "/search" },
{ label: "About", href: "/about" }, { label: "About", href: "/about" },
], ],
showSearch: "yes", showSearch: "yes",
showCart: "yes", showCart: "yes",
sticky: "yes", sticky: "yes",
tone: "default", tone: "default",
bannerText: "",
bannerTone: "accent",
}, },
fields: { fields: {
brand: { label: "Brand", type: "text", contentEditable: true }, brand: { label: "Brand", type: "text", contentEditable: true },
@@ -38,20 +36,6 @@ export const navigationEditor: ComponentConfig<NavigationProps> = {
href: { label: "Link", type: "text" }, href: { label: "Link", type: "text" },
}, },
}, },
bannerText: {
label: "Banner text",
type: "text",
contentEditable: true,
},
bannerTone: {
label: "Banner tone",
type: "select",
options: [
{ label: "Default", value: "default" },
{ label: "Accent", value: "accent" },
{ label: "Inverse (dark)", value: "inverse" },
],
},
showSearch: { showSearch: {
label: "Search icon", label: "Search icon",
type: "radio", type: "radio",

View File

@@ -13,8 +13,6 @@ export type NavigationProps = {
showCart: "yes" | "no"; showCart: "yes" | "no";
sticky: "yes" | "no"; sticky: "yes" | "no";
tone: "default" | "muted" | "inverse"; tone: "default" | "muted" | "inverse";
bannerText: string;
bannerTone: "default" | "accent" | "inverse";
}; };
export function Navigation({ export function Navigation({
@@ -25,8 +23,6 @@ export function Navigation({
showCart, showCart,
sticky, sticky,
tone, tone,
bannerText,
bannerTone,
}: NavigationProps) { }: NavigationProps) {
const [mobileOpen, setMobileOpen] = useState(false); const [mobileOpen, setMobileOpen] = useState(false);
const cart = useShopifyCart(); const cart = useShopifyCart();
@@ -38,14 +34,6 @@ export function Navigation({
inverse: "bg-foreground text-background", inverse: "bg-foreground text-background",
}; };
const bannerToneClass: Record<NavigationProps["bannerTone"], string> = {
default: "bg-muted text-foreground",
accent: "bg-primary text-primary-foreground",
inverse: "bg-foreground text-background",
};
const hasBanner = typeof bannerText === "string" && bannerText.trim().length > 0;
return ( return (
<> <>
<div <div
@@ -54,13 +42,6 @@ export function Navigation({
sticky === "yes" && "sticky top-0 z-40", sticky === "yes" && "sticky top-0 z-40",
)} )}
> >
{hasBanner && (
<div className={cn("w-full", bannerToneClass[bannerTone])}>
<div className="container mx-auto max-w-7xl px-6 py-2 text-center text-xs tracking-wide md:text-sm">
{bannerText}
</div>
</div>
)}
<header <header
className={cn( className={cn(
"w-full", "w-full",
@@ -99,12 +80,13 @@ export function Navigation({
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
{showSearch === "yes" && ( {showSearch === "yes" && (
<button <Link
to="/search"
aria-label="Search" aria-label="Search"
className="hidden h-10 w-10 items-center justify-center rounded-full transition-colors hover:bg-foreground/5 md:inline-flex" className="hidden h-10 w-10 items-center justify-center rounded-full transition-colors hover:bg-foreground/5 md:inline-flex"
> >
<Search size={18} strokeWidth={1.5} /> <Search size={18} strokeWidth={1.5} />
</button> </Link>
)} )}
{showCart === "yes" && ( {showCart === "yes" && (
<button <button

View File

@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
const buttonVariants = cva( const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:ring-2 focus-visible:ring-ring", "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[var(--radius-button)] text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:ring-2 focus-visible:ring-ring",
{ {
variants: { variants: {
variant: { variant: {
@@ -22,8 +22,8 @@ const buttonVariants = cva(
}, },
size: { size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3", default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md px-3 has-[>svg]:px-2.5", sm: "h-8 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4", lg: "h-10 px-6 has-[>svg]:px-4",
icon: "size-9", icon: "size-9",
}, },
}, },

View File

@@ -104,7 +104,7 @@ function SelectTrigger({
data-slot="select-trigger" data-slot="select-trigger"
onClick={() => setOpen(!open)} onClick={() => setOpen(!open)}
className={cn( className={cn(
'border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*="text-"])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 h-9 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4', 'border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*="text-"])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full min-w-[10rem] items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 h-9 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4',
className className
)} )}
{...props} {...props}

View File

@@ -31,9 +31,8 @@ export const Root: RootConfig<{
bgColor: "#ffffff", bgColor: "#ffffff",
fgColor: "#0a0a0a", fgColor: "#0a0a0a",
mutedColor: "#f5f5f5", mutedColor: "#f5f5f5",
roundedness: "md",
radius: "md", radius: "md",
shadowLevel: "sm", buttonRadius: "md",
shadow: "sm", shadow: "sm",
maxWidth: "xl", maxWidth: "xl",
}, },
@@ -49,34 +48,22 @@ export const Root: RootConfig<{
bgColor: { label: "Background color", type: "color", placeholder: "#ffffff" }, bgColor: { label: "Background color", type: "color", placeholder: "#ffffff" },
fgColor: { label: "Foreground color", type: "color", placeholder: "#0a0a0a" }, fgColor: { label: "Foreground color", type: "color", placeholder: "#0a0a0a" },
mutedColor: { label: "Muted color", type: "color", placeholder: "#f5f5f5" }, mutedColor: { label: "Muted color", type: "color", placeholder: "#f5f5f5" },
roundedness: {
label: "Roundedness",
type: "select",
options: [
{ label: "None", value: "none" },
{ label: "Small", value: "sm" },
{ label: "Medium", value: "md" },
{ label: "Large", value: "lg" },
{ label: "Extra large", value: "xl" },
{ label: "Full (pill)", value: "full" },
],
},
radius: { radius: {
label: "Radius", label: "Radius",
type: "select", type: "select",
options: [ options: [
{ label: "None", value: "none" }, { label: "None (square)", value: "none" },
{ label: "Extra small", value: "xs" },
{ label: "Small", value: "sm" }, { label: "Small", value: "sm" },
{ label: "Medium", value: "md" }, { label: "Medium", value: "md" },
{ label: "Large", value: "lg" }, { label: "Large", value: "lg" },
{ label: "Extra large", value: "xl" },
], ],
}, },
shadowLevel: { buttonRadius: {
label: "Shadow level", label: "Button radius",
type: "select", type: "select",
options: [ options: [
{ label: "None", value: "none" }, { label: "None (square)", value: "none" },
{ label: "Small", value: "sm" }, { label: "Small", value: "sm" },
{ label: "Medium", value: "md" }, { label: "Medium", value: "md" },
{ label: "Large", value: "lg" }, { label: "Large", value: "lg" },
@@ -91,6 +78,7 @@ export const Root: RootConfig<{
{ label: "Small", value: "sm" }, { label: "Small", value: "sm" },
{ label: "Medium", value: "md" }, { label: "Medium", value: "md" },
{ label: "Large", value: "lg" }, { label: "Large", value: "lg" },
{ label: "Extra large", value: "xl" },
], ],
}, },
maxWidth: { maxWidth: {
@@ -116,9 +104,8 @@ export const Root: RootConfig<{
bgColor, bgColor,
fgColor, fgColor,
mutedColor, mutedColor,
roundedness,
radius, radius,
shadowLevel, buttonRadius,
shadow, shadow,
}) => { }) => {
return ( return (
@@ -131,9 +118,8 @@ export const Root: RootConfig<{
bgColor={bgColor} bgColor={bgColor}
fgColor={fgColor} fgColor={fgColor}
mutedColor={mutedColor} mutedColor={mutedColor}
roundedness={roundedness}
radius={radius} radius={radius}
shadowLevel={shadowLevel} buttonRadius={buttonRadius}
shadow={shadow} shadow={shadow}
> >
{children} {children}

View File

@@ -31,7 +31,7 @@ export const GET_COLLECTIONS_QUERY = `
// Get products in a collection // Get products in a collection
export const GET_COLLECTION_PRODUCTS_QUERY = ` export const GET_COLLECTION_PRODUCTS_QUERY = `
${ProductFragment} ${ProductFragment}
query GetCollectionProducts($handle: String!, $first: Int!, $sortKey: ProductCollectionSortKeys, $reverse: Boolean) { query GetCollectionProducts($handle: String!, $first: Int!, $sortKey: ProductCollectionSortKeys, $reverse: Boolean, $filters: [ProductFilter!], $after: String) {
collection(handle: $handle) { collection(handle: $handle) {
id id
title title
@@ -45,7 +45,7 @@ export const GET_COLLECTION_PRODUCTS_QUERY = `
width width
height height
} }
products(first: $first, sortKey: $sortKey, reverse: $reverse) { products(first: $first, sortKey: $sortKey, reverse: $reverse, filters: $filters, after: $after) {
edges { edges {
node { node {
...ProductFragment ...ProductFragment

View File

@@ -105,6 +105,30 @@ export const GET_PRODUCT_QUERY = `
} }
`; `;
// Search products with cursor-based pagination and full filter support
export const GET_SEARCH_QUERY = `
${ProductFragment}
query SearchProducts(
$first: Int!
$query: String
$sortKey: ProductSortKeys
$reverse: Boolean
$after: String
) {
products(first: $first, query: $query, sortKey: $sortKey, reverse: $reverse, after: $after) {
edges {
node {
...ProductFragment
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
`;
// Get product recommendations // Get product recommendations
export const QUERY_PRODUCT_RECOMMENDATIONS = ` export const QUERY_PRODUCT_RECOMMENDATIONS = `
${ProductFragment} ${ProductFragment}

View File

@@ -26,10 +26,23 @@ export interface CollectionWithProducts extends Collection {
products: Product[]; 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 };
}
interface UseCollectionProductsOptions { interface UseCollectionProductsOptions {
first?: number; first?: number;
sortKey?: 'BEST_SELLING' | 'CREATED' | 'PRICE' | 'TITLE'; sortKey?: CollectionSortKey;
reverse?: boolean; reverse?: boolean;
filters?: ProductFilter[];
} }
// Fetch all collections // Fetch all collections
@@ -45,19 +58,24 @@ export async function getCollections(first = 50): Promise<Collection[]> {
// Fetch products in a collection by handle // Fetch products in a collection by handle
export async function getCollectionProducts( export async function getCollectionProducts(
handle: string, handle: string,
{ first = 50, sortKey = 'BEST_SELLING', reverse = false }: UseCollectionProductsOptions = {} { first = 50, sortKey = 'BEST_SELLING', reverse = false, filters }: UseCollectionProductsOptions = {},
): Promise<CollectionWithProducts | null> { after?: string | null,
): Promise<{ collection: CollectionWithProducts; hasNextPage: boolean; endCursor: string | null } | null> {
const response = await shopifyFetch({ const response = await shopifyFetch({
query: GET_COLLECTION_PRODUCTS_QUERY, query: GET_COLLECTION_PRODUCTS_QUERY,
variables: { handle, first, sortKey, reverse }, variables: { handle, first, sortKey, reverse, filters: filters?.length ? filters : undefined, after: after ?? null },
}); });
const collection = response.data.collection; const collection = response.data.collection;
if (!collection) return null; if (!collection) return null;
return { return {
...collection, collection: {
products: collection.products.edges.map((edge: { node: Product }) => edge.node), ...collection,
products: collection.products.edges.map((edge: { node: Product }) => edge.node),
},
hasNextPage: collection.products.pageInfo.hasNextPage,
endCursor: collection.products.pageInfo.endCursor,
}; };
} }
@@ -96,6 +114,10 @@ export function useCollectionProducts(
const [collection, setCollection] = useState<CollectionWithProducts | null>(null); const [collection, setCollection] = useState<CollectionWithProducts | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); 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 () => { const fetchCollection = useCallback(async () => {
if (!handle) { if (!handle) {
@@ -106,10 +128,14 @@ export function useCollectionProducts(
try { try {
setLoading(true); setLoading(true);
setError(null); setError(null);
const data = await getCollectionProducts(handle, options); const result = await getCollectionProducts(handle, options);
setCollection(data); if (!result) {
if (!data) { setCollection(null);
setError('Collection not found'); setError('Collection not found');
} else {
setCollection(result.collection);
setHasNextPage(result.hasNextPage);
setCursor(result.endCursor);
} }
} catch (err) { } catch (err) {
console.error('Error fetching collection products:', err); console.error('Error fetching collection products:', err);
@@ -117,11 +143,32 @@ export function useCollectionProducts(
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [handle, options.first, options.sortKey, options.reverse]); }, [handle, options.first, options.sortKey, options.reverse, filtersKey]);
useEffect(() => { useEffect(() => {
fetchCollection(); fetchCollection();
}, [fetchCollection]); }, [fetchCollection]);
return { collection, loading, error, refetch: 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 };
} }

View File

@@ -42,6 +42,10 @@ export interface Product {
description?: string; description?: string;
descriptionHtml?: string; descriptionHtml?: string;
handle: string; handle: string;
vendor?: string;
productType?: string;
tags?: string[];
availableForSale?: boolean;
images: { images: {
edges: Array<{ edges: Array<{
node: ProductImage; node: ProductImage;

178
hooks/use-shopify-search.ts Normal file
View File

@@ -0,0 +1,178 @@
'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 };
}

View File

@@ -16,6 +16,7 @@ import { collectionGridEditor } from "@/components/commerce/collection-grid.edit
import { createCollectionEditor } from "@/components/commerce/collection.editor"; import { createCollectionEditor } from "@/components/commerce/collection.editor";
import { createProductDetailsEditor } from "@/components/commerce/product-details.editor"; import { createProductDetailsEditor } from "@/components/commerce/product-details.editor";
import { createRecommendedProductsEditor } from "@/components/commerce/recommended-products.editor"; import { createRecommendedProductsEditor } from "@/components/commerce/recommended-products.editor";
import { searchProductsEditor } from "@/components/commerce/search-products.editor";
import { featuresEditor } from "@/components/features/features.editor"; import { featuresEditor } from "@/components/features/features.editor";
import { testimonialsEditor } from "@/components/testimonials/testimonials.editor"; import { testimonialsEditor } from "@/components/testimonials/testimonials.editor";
@@ -64,6 +65,7 @@ export function createConfig({ domain, token }: CreateConfigOptions): UserConfig
collection: createCollectionEditor({ collectionField }), collection: createCollectionEditor({ collectionField }),
"product-details": createProductDetailsEditor({ productField }), "product-details": createProductDetailsEditor({ productField }),
"recommended-products": createRecommendedProductsEditor({ productField }), "recommended-products": createRecommendedProductsEditor({ productField }),
"search-products": searchProductsEditor,
features: featuresEditor, features: featuresEditor,
testimonials: testimonialsEditor, testimonials: testimonialsEditor,
"image-gallery": imageGalleryEditor, "image-gallery": imageGalleryEditor,

View File

@@ -101,11 +101,6 @@ export default function App() {
}} }}
/> />
</ShopifyProvider> </ShopifyProvider>
{isPublishing && (
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/30">
<Loader size={32} />
</div>
)}
</div> </div>
); );
} }

View File

@@ -28,10 +28,11 @@
--color-input: var(--input); --color-input: var(--input);
--color-ring: var(--ring); --color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 4px); --radius-sm: calc(var(--radius) * 0.5);
--radius-md: calc(var(--radius) - 2px); --radius-md: calc(var(--radius) * 0.75);
--radius-lg: var(--radius); --radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px); --radius-xl: calc(var(--radius) * 1.5);
--radius-button: var(--button-radius, var(--radius));
--animate-marquee: marquee var(--duration) infinite linear; --animate-marquee: marquee var(--duration) infinite linear;
--animate-marquee-vertical: marquee-vertical var(--duration) linear infinite; --animate-marquee-vertical: marquee-vertical var(--duration) linear infinite;
@@ -59,9 +60,9 @@
--color-chart-3: var(--chart-3); --color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2); --color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1); --color-chart-1: var(--chart-1);
--radius-2xl: calc(var(--radius) * 1.8); --radius-2xl: calc(var(--radius) * 2);
--radius-3xl: calc(var(--radius) * 2.2); --radius-3xl: calc(var(--radius) * 3);
--radius-4xl: calc(var(--radius) * 2.6) --radius-4xl: calc(var(--radius) * 4)
} }
:root { :root {