Merge version_4 into main
Merge version_4 into main
This commit was merged in pull request #5.
This commit is contained in:
@@ -39,8 +39,8 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<head>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
|
||||
<script async src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
|
||||
<script async src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
|
||||
</head>
|
||||
<ServiceWrapper>
|
||||
<body className={`${inter.variable} antialiased`}>
|
||||
|
||||
@@ -1,118 +1,27 @@
|
||||
import { useEffect, useState, useRef, RefObject } from "react";
|
||||
import { useEffect } from "react";
|
||||
import gsap from "gsap";
|
||||
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
const ANIMATION_SPEED = 0.05;
|
||||
const ROTATION_SPEED = 0.1;
|
||||
const MOUSE_MULTIPLIER = 0.5;
|
||||
const ROTATION_MULTIPLIER = 0.25;
|
||||
|
||||
interface UseDepth3DAnimationProps {
|
||||
itemRefs: RefObject<(HTMLElement | null)[]>;
|
||||
containerRef: RefObject<HTMLDivElement | null>;
|
||||
perspectiveRef?: RefObject<HTMLDivElement | null>;
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
export const useDepth3DAnimation = ({
|
||||
itemRefs,
|
||||
containerRef,
|
||||
perspectiveRef,
|
||||
isEnabled,
|
||||
}: UseDepth3DAnimationProps) => {
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
|
||||
// Detect mobile viewport
|
||||
export const useDepth3DAnimation = (containerRef: React.RefObject<HTMLDivElement>) => {
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
};
|
||||
if (!containerRef.current) return;
|
||||
|
||||
checkMobile();
|
||||
window.addEventListener("resize", checkMobile);
|
||||
const container = containerRef.current;
|
||||
const cards = container.querySelectorAll("[data-card]");
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", checkMobile);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 3D mouse-tracking effect (desktop only)
|
||||
useEffect(() => {
|
||||
if (!isEnabled || isMobile) return;
|
||||
|
||||
let animationFrameId: number;
|
||||
let isAnimating = true;
|
||||
|
||||
// Apply perspective to the perspective ref (grid) if provided, otherwise to container (section)
|
||||
const perspectiveElement = perspectiveRef?.current || containerRef.current;
|
||||
if (perspectiveElement) {
|
||||
perspectiveElement.style.perspective = "1200px";
|
||||
perspectiveElement.style.transformStyle = "preserve-3d";
|
||||
}
|
||||
|
||||
let mouseX = 0;
|
||||
let mouseY = 0;
|
||||
let isMouseInSection = false;
|
||||
|
||||
let currentX = 0;
|
||||
let currentY = 0;
|
||||
let currentRotationX = 0;
|
||||
let currentRotationY = 0;
|
||||
|
||||
const handleMouseMove = (event: MouseEvent): void => {
|
||||
if (containerRef.current) {
|
||||
const rect = containerRef.current.getBoundingClientRect();
|
||||
isMouseInSection =
|
||||
event.clientX >= rect.left &&
|
||||
event.clientX <= rect.right &&
|
||||
event.clientY >= rect.top &&
|
||||
event.clientY <= rect.bottom;
|
||||
}
|
||||
|
||||
if (isMouseInSection) {
|
||||
mouseX = (event.clientX / window.innerWidth) * 100 - 50;
|
||||
mouseY = (event.clientY / window.innerHeight) * 100 - 50;
|
||||
}
|
||||
};
|
||||
|
||||
const animate = (): void => {
|
||||
if (!isAnimating) return;
|
||||
|
||||
if (isMouseInSection) {
|
||||
const distX = mouseX * MOUSE_MULTIPLIER - currentX;
|
||||
const distY = mouseY * MOUSE_MULTIPLIER - currentY;
|
||||
currentX += distX * ANIMATION_SPEED;
|
||||
currentY += distY * ANIMATION_SPEED;
|
||||
|
||||
const distRotX = -mouseY * ROTATION_MULTIPLIER - currentRotationX;
|
||||
const distRotY = mouseX * ROTATION_MULTIPLIER - currentRotationY;
|
||||
currentRotationX += distRotX * ROTATION_SPEED;
|
||||
currentRotationY += distRotY * ROTATION_SPEED;
|
||||
} else {
|
||||
currentX += -currentX * ANIMATION_SPEED;
|
||||
currentY += -currentY * ANIMATION_SPEED;
|
||||
currentRotationX += -currentRotationX * ROTATION_SPEED;
|
||||
currentRotationY += -currentRotationY * ROTATION_SPEED;
|
||||
}
|
||||
|
||||
itemRefs.current?.forEach((ref) => {
|
||||
if (!ref) return;
|
||||
ref.style.transform = `translate(${currentX}px, ${currentY}px) rotateX(${currentRotationX}deg) rotateY(${currentRotationY}deg)`;
|
||||
// Add scroll-triggered 3D animations
|
||||
cards.forEach((card, index) => {
|
||||
gsap.from(card, {
|
||||
opacity: 0,
|
||||
y: 50,
|
||||
rotationX: 10,
|
||||
duration: 0.8,
|
||||
delay: index * 0.1,
|
||||
scrollTrigger: {
|
||||
trigger: card,
|
||||
start: "top 80%", end: "top 20%", scrub: 1,
|
||||
markers: false
|
||||
}
|
||||
});
|
||||
|
||||
animationFrameId = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
animate();
|
||||
window.addEventListener("mousemove", handleMouseMove);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", handleMouseMove);
|
||||
if (animationFrameId) {
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
}
|
||||
isAnimating = false;
|
||||
};
|
||||
}, [isEnabled, isMobile, itemRefs, containerRef]);
|
||||
|
||||
return { isMobile };
|
||||
});
|
||||
}, [containerRef]);
|
||||
};
|
||||
|
||||
@@ -1,149 +1,44 @@
|
||||
"use client";
|
||||
import React, { useMemo } from "react";
|
||||
import { CardStack, CardStackProps } from "@/components/cardStack";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import React, { Children, useCallback } from "react";
|
||||
import { cls } from "@/lib/utils";
|
||||
import CardStackTextBox from "../../CardStackTextBox";
|
||||
import { useCardAnimation } from "../../hooks/useCardAnimation";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import type { ButtonConfig, CardAnimationType, TitleSegment, ButtonAnimationType } from "../../types";
|
||||
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
|
||||
|
||||
type TimelineVariant = "timeline";
|
||||
|
||||
interface TimelineBaseProps {
|
||||
children: React.ReactNode;
|
||||
variant?: TimelineVariant;
|
||||
uniformGridCustomHeightClasses?: string;
|
||||
animationType: CardAnimationType;
|
||||
title?: string;
|
||||
titleSegments?: TitleSegment[];
|
||||
description?: string;
|
||||
tag?: string;
|
||||
tagIcon?: LucideIcon;
|
||||
tagAnimation?: ButtonAnimationType;
|
||||
buttons?: ButtonConfig[];
|
||||
buttonAnimation?: ButtonAnimationType;
|
||||
textboxLayout?: TextboxLayout;
|
||||
useInvertedBackground?: InvertedBackground;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
textBoxClassName?: string;
|
||||
titleClassName?: string;
|
||||
titleImageWrapperClassName?: string;
|
||||
titleImageClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
tagClassName?: string;
|
||||
buttonContainerClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
ariaLabel?: string;
|
||||
export interface TimelineItem {
|
||||
id: string;
|
||||
reverse?: boolean;
|
||||
media?: React.ReactNode;
|
||||
content?: React.ReactNode;
|
||||
}
|
||||
|
||||
const TimelineBase = ({
|
||||
children,
|
||||
variant = "timeline",
|
||||
uniformGridCustomHeightClasses = "min-h-80 2xl:min-h-90",
|
||||
animationType,
|
||||
title,
|
||||
titleSegments,
|
||||
description,
|
||||
tag,
|
||||
tagIcon,
|
||||
tagAnimation,
|
||||
buttons,
|
||||
buttonAnimation,
|
||||
textboxLayout = "default",
|
||||
useInvertedBackground,
|
||||
className = "",
|
||||
containerClassName = "",
|
||||
textBoxClassName = "",
|
||||
titleClassName = "",
|
||||
titleImageWrapperClassName = "",
|
||||
titleImageClassName = "",
|
||||
descriptionClassName = "",
|
||||
tagClassName = "",
|
||||
buttonContainerClassName = "",
|
||||
buttonClassName = "",
|
||||
buttonTextClassName = "",
|
||||
ariaLabel = "Timeline section",
|
||||
}: TimelineBaseProps) => {
|
||||
const childrenArray = Children.toArray(children);
|
||||
const { itemRefs } = useCardAnimation({
|
||||
animationType,
|
||||
itemCount: childrenArray.length,
|
||||
isGrid: false
|
||||
});
|
||||
export interface TimelineBaseProps extends Omit<CardStackProps, "items"> {
|
||||
items: TimelineItem[];
|
||||
animationType?: "slide-up" | "none" | "opacity" | "blur-reveal";
|
||||
}
|
||||
|
||||
const getItemClasses = useCallback((index: number) => {
|
||||
// Timeline variant - scattered/organic pattern
|
||||
const alignmentClass =
|
||||
index % 2 === 0 ? "self-start ml-0" : "self-end mr-0";
|
||||
|
||||
const marginClasses = cls(
|
||||
index % 4 === 0 && "md:ml-0",
|
||||
index % 4 === 1 && "md:mr-20",
|
||||
index % 4 === 2 && "md:ml-15",
|
||||
index % 4 === 3 && "md:mr-30"
|
||||
);
|
||||
|
||||
return cls(alignmentClass, marginClasses);
|
||||
}, []);
|
||||
export const TimelineBase: React.FC<TimelineBaseProps> = ({
|
||||
items,
|
||||
animationType = "slide-up", className,
|
||||
containerClassName,
|
||||
...props
|
||||
}) => {
|
||||
const timelineItems = useMemo(
|
||||
() =>
|
||||
items.map((item) => ({
|
||||
id: item.id,
|
||||
title: "", description: "", content: item.content,
|
||||
media: item.media,
|
||||
reverse: item.reverse
|
||||
})),
|
||||
[items]
|
||||
);
|
||||
|
||||
return (
|
||||
<section
|
||||
className={cls(
|
||||
"relative py-20 w-full",
|
||||
useInvertedBackground && "bg-foreground",
|
||||
className
|
||||
)}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<div
|
||||
className={cls("w-content-width mx-auto flex flex-col gap-6", containerClassName)}
|
||||
>
|
||||
{(title || titleSegments || description) && (
|
||||
<CardStackTextBox
|
||||
title={title}
|
||||
titleSegments={titleSegments}
|
||||
description={description}
|
||||
tag={tag}
|
||||
tagIcon={tagIcon}
|
||||
tagAnimation={tagAnimation}
|
||||
buttons={buttons}
|
||||
buttonAnimation={buttonAnimation}
|
||||
textboxLayout={textboxLayout}
|
||||
useInvertedBackground={useInvertedBackground}
|
||||
textBoxClassName={textBoxClassName}
|
||||
titleClassName={titleClassName}
|
||||
titleImageWrapperClassName={titleImageWrapperClassName}
|
||||
titleImageClassName={titleImageClassName}
|
||||
descriptionClassName={descriptionClassName}
|
||||
tagClassName={tagClassName}
|
||||
buttonContainerClassName={buttonContainerClassName}
|
||||
buttonClassName={buttonClassName}
|
||||
buttonTextClassName={buttonTextClassName}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className={cls(
|
||||
"relative z-10 flex flex-col gap-6 md:gap-15"
|
||||
)}
|
||||
>
|
||||
{Children.map(childrenArray, (child, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={cls("w-65 md:w-25", uniformGridCustomHeightClasses, getItemClasses(index))}
|
||||
ref={(el) => { itemRefs.current[index] = el; }}
|
||||
>
|
||||
{child}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<CardStack
|
||||
items={timelineItems}
|
||||
className={cn("timeline-base", className)}
|
||||
containerClassName={containerClassName}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
TimelineBase.displayName = "TimelineBase";
|
||||
|
||||
export default React.memo(TimelineBase);
|
||||
export default TimelineBase;
|
||||
|
||||
@@ -1,131 +1,64 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import ContactForm from "@/components/form/ContactForm";
|
||||
import HeroBackgrounds, { type HeroBackgroundVariantProps } from "@/components/background/HeroBackgrounds";
|
||||
import { cls } from "@/lib/utils";
|
||||
import { LucideIcon } from "lucide-react";
|
||||
import { sendContactEmail } from "@/utils/sendContactEmail";
|
||||
import type { ButtonAnimationType } from "@/types/button";
|
||||
|
||||
type ContactCenterBackgroundProps = Extract<
|
||||
HeroBackgroundVariantProps,
|
||||
| { variant: "plain" }
|
||||
| { variant: "animated-grid" }
|
||||
| { variant: "canvas-reveal" }
|
||||
| { variant: "cell-wave" }
|
||||
| { variant: "downward-rays-animated" }
|
||||
| { variant: "downward-rays-animated-grid" }
|
||||
| { variant: "downward-rays-static" }
|
||||
| { variant: "downward-rays-static-grid" }
|
||||
| { variant: "gradient-bars" }
|
||||
| { variant: "radial-gradient" }
|
||||
| { variant: "rotated-rays-animated" }
|
||||
| { variant: "rotated-rays-animated-grid" }
|
||||
| { variant: "rotated-rays-static" }
|
||||
| { variant: "rotated-rays-static-grid" }
|
||||
| { variant: "sparkles-gradient" }
|
||||
>;
|
||||
|
||||
interface ContactCenterProps {
|
||||
title: string;
|
||||
description: string;
|
||||
tag: string;
|
||||
tagIcon?: LucideIcon;
|
||||
tagAnimation?: ButtonAnimationType;
|
||||
background: ContactCenterBackgroundProps;
|
||||
useInvertedBackground: boolean;
|
||||
tagClassName?: string;
|
||||
inputPlaceholder?: string;
|
||||
buttonText?: string;
|
||||
termsText?: string;
|
||||
onSubmit?: (email: string) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
contentClassName?: string;
|
||||
titleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
formWrapperClassName?: string;
|
||||
formClassName?: string;
|
||||
inputClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
termsClassName?: string;
|
||||
export interface ContactCenterProps {
|
||||
tag?: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
contactEmail?: string;
|
||||
contactPhone?: string;
|
||||
useInvertedBackground?: boolean;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
}
|
||||
|
||||
const ContactCenter = ({
|
||||
title,
|
||||
description,
|
||||
tag,
|
||||
tagIcon,
|
||||
tagAnimation,
|
||||
background,
|
||||
useInvertedBackground,
|
||||
tagClassName = "",
|
||||
inputPlaceholder = "Enter your email",
|
||||
buttonText = "Sign Up",
|
||||
termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.",
|
||||
onSubmit,
|
||||
ariaLabel = "Contact section",
|
||||
className = "",
|
||||
containerClassName = "",
|
||||
contentClassName = "",
|
||||
titleClassName = "",
|
||||
descriptionClassName = "",
|
||||
formWrapperClassName = "",
|
||||
formClassName = "",
|
||||
inputClassName = "",
|
||||
buttonClassName = "",
|
||||
buttonTextClassName = "",
|
||||
termsClassName = "",
|
||||
}: ContactCenterProps) => {
|
||||
export const ContactCenter: React.FC<ContactCenterProps> = ({
|
||||
tag,
|
||||
title,
|
||||
description,
|
||||
contactEmail,
|
||||
contactPhone,
|
||||
useInvertedBackground = false,
|
||||
className,
|
||||
containerClassName
|
||||
}) => {
|
||||
const [email, setEmail] = useState("");
|
||||
|
||||
const handleSubmit = async (email: string) => {
|
||||
try {
|
||||
await sendContactEmail({ email });
|
||||
console.log("Email send successfully");
|
||||
} catch (error) {
|
||||
console.error("Failed to send email:", error);
|
||||
}
|
||||
};
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setEmail("");
|
||||
};
|
||||
|
||||
return (
|
||||
<section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}>
|
||||
<div className={cls("w-content-width mx-auto relative z-10", containerClassName)}>
|
||||
<div className={cls("relative w-full card p-6 md:p-0 py-20 md:py-20 rounded-theme-capped flex items-center justify-center", contentClassName)}>
|
||||
<div className="relative z-10 w-full md:w-1/2">
|
||||
<ContactForm
|
||||
tag={tag}
|
||||
tagIcon={tagIcon}
|
||||
tagAnimation={tagAnimation}
|
||||
title={title}
|
||||
description={description}
|
||||
useInvertedBackground={useInvertedBackground}
|
||||
inputPlaceholder={inputPlaceholder}
|
||||
buttonText={buttonText}
|
||||
termsText={termsText}
|
||||
onSubmit={handleSubmit}
|
||||
centered={true}
|
||||
tagClassName={tagClassName}
|
||||
titleClassName={titleClassName}
|
||||
descriptionClassName={descriptionClassName}
|
||||
formWrapperClassName={cls("md:w-8/10 2xl:w-6/10", formWrapperClassName)}
|
||||
formClassName={formClassName}
|
||||
inputClassName={inputClassName}
|
||||
buttonClassName={buttonClassName}
|
||||
buttonTextClassName={buttonTextClassName}
|
||||
termsClassName={termsClassName}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute inset w-full h-full z-0 rounded-theme-capped overflow-hidden" >
|
||||
<HeroBackgrounds {...background} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"w-full py-20 px-4", useInvertedBackground && "bg-accent/10", containerClassName
|
||||
)}
|
||||
>
|
||||
<div className={cn("max-w-2xl mx-auto text-center", className)}>
|
||||
{tag && <p className="text-sm font-semibold mb-2 text-accent">{tag}</p>}
|
||||
<h2 className="text-4xl font-bold mb-4">{title}</h2>
|
||||
{description && <p className="text-lg text-muted-foreground mb-8">{description}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<input
|
||||
type="email"
|
||||
placeholder="your@email.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg"
|
||||
required
|
||||
/>
|
||||
<button type="submit" className="w-full px-4 py-2 bg-primary text-white rounded-lg">
|
||||
Send
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{contactEmail && <p className="mt-6 text-sm text-muted-foreground">Email: {contactEmail}</p>}
|
||||
{contactPhone && <p className="text-sm text-muted-foreground">Phone: {contactPhone}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
ContactCenter.displayName = "ContactCenter";
|
||||
|
||||
export default ContactCenter;
|
||||
|
||||
@@ -1,171 +1,123 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import ContactForm from "@/components/form/ContactForm";
|
||||
import MediaContent from "@/components/shared/MediaContent";
|
||||
import HeroBackgrounds, { type HeroBackgroundVariantProps } from "@/components/background/HeroBackgrounds";
|
||||
import { cls } from "@/lib/utils";
|
||||
import { useButtonAnimation } from "@/components/hooks/useButtonAnimation";
|
||||
import { LucideIcon } from "lucide-react";
|
||||
import { sendContactEmail } from "@/utils/sendContactEmail";
|
||||
import type { ButtonAnimationType } from "@/types/button";
|
||||
|
||||
type ContactSplitBackgroundProps = Extract<
|
||||
HeroBackgroundVariantProps,
|
||||
| { variant: "plain" }
|
||||
| { variant: "animated-grid" }
|
||||
| { variant: "canvas-reveal" }
|
||||
| { variant: "cell-wave" }
|
||||
| { variant: "downward-rays-animated" }
|
||||
| { variant: "downward-rays-animated-grid" }
|
||||
| { variant: "downward-rays-static" }
|
||||
| { variant: "downward-rays-static-grid" }
|
||||
| { variant: "gradient-bars" }
|
||||
| { variant: "radial-gradient" }
|
||||
| { variant: "rotated-rays-animated" }
|
||||
| { variant: "rotated-rays-animated-grid" }
|
||||
| { variant: "rotated-rays-static" }
|
||||
| { variant: "rotated-rays-static-grid" }
|
||||
| { variant: "sparkles-gradient" }
|
||||
>;
|
||||
|
||||
interface ContactSplitProps {
|
||||
title: string;
|
||||
description: string;
|
||||
tag: string;
|
||||
tagIcon?: LucideIcon;
|
||||
tagAnimation?: ButtonAnimationType;
|
||||
background: ContactSplitBackgroundProps;
|
||||
useInvertedBackground: boolean;
|
||||
imageSrc?: string;
|
||||
videoSrc?: string;
|
||||
imageAlt?: string;
|
||||
videoAriaLabel?: string;
|
||||
mediaPosition?: "left" | "right";
|
||||
mediaAnimation: ButtonAnimationType;
|
||||
inputPlaceholder?: string;
|
||||
buttonText?: string;
|
||||
termsText?: string;
|
||||
onSubmit?: (email: string) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
contentClassName?: string;
|
||||
contactFormClassName?: string;
|
||||
tagClassName?: string;
|
||||
titleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
formWrapperClassName?: string;
|
||||
formClassName?: string;
|
||||
inputClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
termsClassName?: string;
|
||||
mediaWrapperClassName?: string;
|
||||
mediaClassName?: string;
|
||||
export interface ContactSplitProps {
|
||||
tag?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
background?: { variant: string };
|
||||
useInvertedBackground?: boolean;
|
||||
imageSrc?: string;
|
||||
videoSrc?: string;
|
||||
imageAlt?: string;
|
||||
videoAriaLabel?: string;
|
||||
mediaAnimation?: "none" | "opacity" | "slide-up" | "blur-reveal";
|
||||
mediaPosition?: "left" | "right";
|
||||
inputPlaceholder?: string;
|
||||
buttonText?: string;
|
||||
termsText?: string;
|
||||
onSubmit?: (email: string) => void;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
contentClassName?: string;
|
||||
contactFormClassName?: string;
|
||||
tagClassName?: string;
|
||||
titleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
formWrapperClassName?: string;
|
||||
formClassName?: string;
|
||||
inputClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
termsClassName?: string;
|
||||
mediaWrapperClassName?: string;
|
||||
mediaClassName?: string;
|
||||
}
|
||||
|
||||
const ContactSplit = ({
|
||||
title,
|
||||
description,
|
||||
tag,
|
||||
tagIcon,
|
||||
tagAnimation,
|
||||
background,
|
||||
useInvertedBackground,
|
||||
imageSrc,
|
||||
videoSrc,
|
||||
imageAlt = "",
|
||||
videoAriaLabel = "Contact section video",
|
||||
mediaPosition = "right",
|
||||
mediaAnimation,
|
||||
inputPlaceholder = "Enter your email",
|
||||
buttonText = "Sign Up",
|
||||
termsText = "By clicking Sign Up you're confirming that you agree with our Terms and Conditions.",
|
||||
onSubmit,
|
||||
ariaLabel = "Contact section",
|
||||
className = "",
|
||||
containerClassName = "",
|
||||
contentClassName = "",
|
||||
contactFormClassName = "",
|
||||
tagClassName = "",
|
||||
titleClassName = "",
|
||||
descriptionClassName = "",
|
||||
formWrapperClassName = "",
|
||||
formClassName = "",
|
||||
inputClassName = "",
|
||||
buttonClassName = "",
|
||||
buttonTextClassName = "",
|
||||
termsClassName = "",
|
||||
mediaWrapperClassName = "",
|
||||
mediaClassName = "",
|
||||
}: ContactSplitProps) => {
|
||||
const { containerRef: mediaContainerRef } = useButtonAnimation({ animationType: mediaAnimation });
|
||||
export const ContactSplit: React.FC<ContactSplitProps> = ({
|
||||
tag,
|
||||
title,
|
||||
description,
|
||||
imageSrc,
|
||||
videoSrc,
|
||||
imageAlt = "", mediaPosition = "right", inputPlaceholder = "Enter your email", buttonText = "Sign Up", termsText,
|
||||
useInvertedBackground = false,
|
||||
className,
|
||||
containerClassName,
|
||||
contentClassName,
|
||||
tagClassName,
|
||||
titleClassName,
|
||||
descriptionClassName,
|
||||
formWrapperClassName,
|
||||
formClassName,
|
||||
inputClassName,
|
||||
buttonClassName,
|
||||
buttonTextClassName,
|
||||
termsClassName,
|
||||
mediaWrapperClassName,
|
||||
mediaClassName
|
||||
}) => {
|
||||
const [email, setEmail] = useState("");
|
||||
|
||||
const handleSubmit = async (email: string) => {
|
||||
try {
|
||||
await sendContactEmail({ email });
|
||||
console.log("Email send successfully");
|
||||
} catch (error) {
|
||||
console.error("Failed to send email:", error);
|
||||
}
|
||||
};
|
||||
const handleFormSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setEmail("");
|
||||
};
|
||||
|
||||
const contactContent = (
|
||||
<div className="relative card rounded-theme-capped p-6 py-15 md:py-6 flex items-center justify-center">
|
||||
<ContactForm
|
||||
tag={tag}
|
||||
tagIcon={tagIcon}
|
||||
tagAnimation={tagAnimation}
|
||||
title={title}
|
||||
description={description}
|
||||
useInvertedBackground={useInvertedBackground}
|
||||
inputPlaceholder={inputPlaceholder}
|
||||
buttonText={buttonText}
|
||||
termsText={termsText}
|
||||
onSubmit={handleSubmit}
|
||||
centered={true}
|
||||
className={cls("w-full", contactFormClassName)}
|
||||
tagClassName={tagClassName}
|
||||
titleClassName={titleClassName}
|
||||
descriptionClassName={descriptionClassName}
|
||||
formWrapperClassName={cls("w-full md:w-8/10 2xl:w-7/10", formWrapperClassName)}
|
||||
formClassName={formClassName}
|
||||
inputClassName={inputClassName}
|
||||
buttonClassName={buttonClassName}
|
||||
buttonTextClassName={buttonTextClassName}
|
||||
termsClassName={termsClassName}
|
||||
/>
|
||||
<div className="absolute inset w-full h-full z-0 rounded-theme-capped overflow-hidden" >
|
||||
<HeroBackgrounds {...background} />
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"w-full py-20 px-4", useInvertedBackground && "bg-accent/10", containerClassName
|
||||
)}
|
||||
>
|
||||
<div className={cn("max-w-6xl mx-auto", contentClassName)}>
|
||||
<div className={cn("grid grid-cols-1 md:grid-cols-2 gap-12 items-center", className)}>
|
||||
{mediaPosition === "left" && imageSrc && (
|
||||
<div className={cn("order-first", mediaWrapperClassName)}>
|
||||
<img src={imageSrc} alt={imageAlt} className={cn("w-full rounded-lg", mediaClassName)} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)}
|
||||
|
||||
const mediaContent = (
|
||||
<div ref={mediaContainerRef} className={cls("overflow-hidden rounded-theme-capped card h-130", mediaWrapperClassName)}>
|
||||
<MediaContent
|
||||
imageSrc={imageSrc}
|
||||
videoSrc={videoSrc}
|
||||
imageAlt={imageAlt}
|
||||
videoAriaLabel={videoAriaLabel}
|
||||
imageClassName={cls("relative z-1 w-full h-full object-cover", mediaClassName)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
<div className={cn("space-y-6", contactFormClassName)}>
|
||||
{tag && <p className={cn("text-sm font-semibold text-accent", tagClassName)}>{tag}</p>}
|
||||
<h2 className={cn("text-4xl font-bold", titleClassName)}>{title}</h2>
|
||||
<p className={cn("text-lg text-muted-foreground", descriptionClassName)}>{description}</p>
|
||||
|
||||
return (
|
||||
<section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}>
|
||||
<div className={cls("w-content-width mx-auto relative z-10", containerClassName)}>
|
||||
<div className={cls("grid grid-cols-1 md:grid-cols-2 gap-6 md:auto-rows-fr", contentClassName)}>
|
||||
{mediaPosition === "left" && mediaContent}
|
||||
{contactContent}
|
||||
{mediaPosition === "right" && mediaContent}
|
||||
</div>
|
||||
<form onSubmit={handleFormSubmit} className={cn("space-y-4", formWrapperClassName)}>
|
||||
<div className={cn("space-y-2", formClassName)}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder={inputPlaceholder}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={cn(
|
||||
"w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary", inputClassName
|
||||
)}
|
||||
required
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className={cn(
|
||||
"w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors", buttonClassName
|
||||
)}
|
||||
>
|
||||
<span className={buttonTextClassName}>{buttonText}</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{termsText && <p className={cn("text-xs text-muted-foreground", termsClassName)}>{termsText}</p>}
|
||||
</div>
|
||||
|
||||
{mediaPosition === "right" && imageSrc && (
|
||||
<div className={cn("order-last", mediaWrapperClassName)}>
|
||||
<img src={imageSrc} alt={imageAlt} className={cn("w-full rounded-lg", mediaClassName)} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
ContactSplit.displayName = "ContactSplit";
|
||||
|
||||
export default ContactSplit;
|
||||
|
||||
@@ -1,214 +1,59 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { useState } from "react";
|
||||
import TextAnimation from "@/components/text/TextAnimation";
|
||||
import Button from "@/components/button/Button";
|
||||
import Input from "@/components/form/Input";
|
||||
import Textarea from "@/components/form/Textarea";
|
||||
import MediaContent from "@/components/shared/MediaContent";
|
||||
import { cls, shouldUseInvertedText } from "@/lib/utils";
|
||||
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
|
||||
import { useButtonAnimation } from "@/components/hooks/useButtonAnimation";
|
||||
import { getButtonProps } from "@/lib/buttonUtils";
|
||||
import type { AnimationType } from "@/components/text/types";
|
||||
import type { ButtonAnimationType } from "@/types/button";
|
||||
import {sendContactEmail} from "@/utils/sendContactEmail";
|
||||
|
||||
export interface InputField {
|
||||
name: string;
|
||||
type: string;
|
||||
placeholder: string;
|
||||
required?: boolean;
|
||||
className?: string;
|
||||
export interface ContactSplitFormProps {
|
||||
tag?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
useInvertedBackground?: boolean;
|
||||
inputPlaceholder?: string;
|
||||
buttonText?: string;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
}
|
||||
|
||||
export interface TextareaField {
|
||||
name: string;
|
||||
placeholder: string;
|
||||
rows?: number;
|
||||
required?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
export const ContactSplitForm: React.FC<ContactSplitFormProps> = ({
|
||||
tag,
|
||||
title,
|
||||
description,
|
||||
useInvertedBackground = false,
|
||||
inputPlaceholder = "Enter your email", buttonText = "Sign Up", className,
|
||||
containerClassName
|
||||
}) => {
|
||||
const [email, setEmail] = useState("");
|
||||
|
||||
interface ContactSplitFormProps {
|
||||
title: string;
|
||||
description: string;
|
||||
inputs: InputField[];
|
||||
textarea?: TextareaField;
|
||||
useInvertedBackground: boolean;
|
||||
imageSrc?: string;
|
||||
videoSrc?: string;
|
||||
imageAlt?: string;
|
||||
videoAriaLabel?: string;
|
||||
mediaPosition?: "left" | "right";
|
||||
mediaAnimation: ButtonAnimationType;
|
||||
buttonText?: string;
|
||||
onSubmit?: (data: Record<string, string>) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
contentClassName?: string;
|
||||
formCardClassName?: string;
|
||||
titleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
buttonClassName?: string;
|
||||
buttonTextClassName?: string;
|
||||
mediaWrapperClassName?: string;
|
||||
mediaClassName?: string;
|
||||
}
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setEmail("");
|
||||
};
|
||||
|
||||
const ContactSplitForm = ({
|
||||
title,
|
||||
description,
|
||||
inputs,
|
||||
textarea,
|
||||
useInvertedBackground,
|
||||
imageSrc,
|
||||
videoSrc,
|
||||
imageAlt = "",
|
||||
videoAriaLabel = "Contact section video",
|
||||
mediaPosition = "right",
|
||||
mediaAnimation,
|
||||
buttonText = "Submit",
|
||||
onSubmit,
|
||||
ariaLabel = "Contact section",
|
||||
className = "",
|
||||
containerClassName = "",
|
||||
contentClassName = "",
|
||||
formCardClassName = "",
|
||||
titleClassName = "",
|
||||
descriptionClassName = "",
|
||||
buttonClassName = "",
|
||||
buttonTextClassName = "",
|
||||
mediaWrapperClassName = "",
|
||||
mediaClassName = "",
|
||||
}: ContactSplitFormProps) => {
|
||||
const theme = useTheme();
|
||||
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
|
||||
const { containerRef: mediaContainerRef } = useButtonAnimation({ animationType: mediaAnimation });
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"w-full py-20 px-4", useInvertedBackground && "bg-accent/10", containerClassName
|
||||
)}
|
||||
>
|
||||
<div className={cn("max-w-2xl mx-auto text-center space-y-6", className)}>
|
||||
{tag && <p className="text-sm font-semibold text-accent">{tag}</p>}
|
||||
<h2 className="text-4xl font-bold">{title}</h2>
|
||||
<p className="text-lg text-muted-foreground">{description}</p>
|
||||
|
||||
// Validate minimum inputs requirement
|
||||
if (inputs.length < 2) {
|
||||
throw new Error("ContactSplitForm requires at least 2 inputs");
|
||||
}
|
||||
|
||||
// Initialize form data dynamically
|
||||
const initialFormData: Record<string, string> = {};
|
||||
inputs.forEach(input => {
|
||||
initialFormData[input.name] = "";
|
||||
});
|
||||
if (textarea) {
|
||||
initialFormData[textarea.name] = "";
|
||||
}
|
||||
|
||||
const [formData, setFormData] = useState(initialFormData);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await sendContactEmail({ formData });
|
||||
console.log("Email send successfully");
|
||||
setFormData(initialFormData);
|
||||
} catch (error) {
|
||||
console.error("Failed to send email:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const getButtonConfigProps = () => {
|
||||
if (theme.defaultButtonVariant === "hover-bubble") {
|
||||
return { bgClassName: "w-full" };
|
||||
}
|
||||
if (theme.defaultButtonVariant === "icon-arrow") {
|
||||
return { className: "justify-between" };
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
const formContent = (
|
||||
<div className={cls("card rounded-theme-capped p-6 md:p-10 flex items-center justify-center", formCardClassName)}>
|
||||
<form onSubmit={handleSubmit} className="relative z-1 w-full flex flex-col gap-6">
|
||||
<div className="w-full flex flex-col gap-0 text-center">
|
||||
<TextAnimation
|
||||
type={theme.defaultTextAnimation as AnimationType}
|
||||
text={title}
|
||||
variant="trigger"
|
||||
className={cls("text-4xl font-medium leading-[1.175] text-balance", shouldUseLightText ? "text-background" : "text-foreground", titleClassName)}
|
||||
/>
|
||||
|
||||
<TextAnimation
|
||||
type={theme.defaultTextAnimation as AnimationType}
|
||||
text={description}
|
||||
variant="words-trigger"
|
||||
className={cls("text-base leading-[1.15] text-balance", shouldUseLightText ? "text-background" : "text-foreground", descriptionClassName)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full flex flex-col gap-4">
|
||||
{inputs.map((input) => (
|
||||
<Input
|
||||
key={input.name}
|
||||
type={input.type}
|
||||
placeholder={input.placeholder}
|
||||
value={formData[input.name] || ""}
|
||||
onChange={(value) => setFormData({ ...formData, [input.name]: value })}
|
||||
required={input.required}
|
||||
ariaLabel={input.placeholder}
|
||||
className={input.className}
|
||||
/>
|
||||
))}
|
||||
|
||||
{textarea && (
|
||||
<Textarea
|
||||
placeholder={textarea.placeholder}
|
||||
value={formData[textarea.name] || ""}
|
||||
onChange={(value) => setFormData({ ...formData, [textarea.name]: value })}
|
||||
required={textarea.required}
|
||||
rows={textarea.rows || 5}
|
||||
ariaLabel={textarea.placeholder}
|
||||
className={textarea.className}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button
|
||||
{...getButtonProps(
|
||||
{ text: buttonText, props: getButtonConfigProps() },
|
||||
0,
|
||||
theme.defaultButtonVariant,
|
||||
cls("w-full", buttonClassName),
|
||||
cls("text-base", buttonTextClassName)
|
||||
)}
|
||||
type="submit"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
|
||||
const mediaContent = (
|
||||
<div ref={mediaContainerRef} className={cls("overflow-hidden rounded-theme-capped card md:relative md:h-full", mediaWrapperClassName)}>
|
||||
<MediaContent
|
||||
imageSrc={imageSrc}
|
||||
videoSrc={videoSrc}
|
||||
imageAlt={imageAlt}
|
||||
videoAriaLabel={videoAriaLabel}
|
||||
imageClassName={cls("w-full md:absolute md:inset-0 md:h-full object-cover", mediaClassName)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<section aria-label={ariaLabel} className={cls("relative py-20 w-full", useInvertedBackground && "bg-foreground", className)}>
|
||||
<div className={cls("w-content-width mx-auto", containerClassName)}>
|
||||
<div className={cls("grid grid-cols-1 md:grid-cols-2 gap-6 md:auto-rows-fr", contentClassName)}>
|
||||
{mediaPosition === "left" && mediaContent}
|
||||
{formContent}
|
||||
{mediaPosition === "right" && mediaContent}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<input
|
||||
type="email"
|
||||
placeholder={inputPlaceholder}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
required
|
||||
/>
|
||||
<button type="submit" className="w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
|
||||
{buttonText}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
ContactSplitForm.displayName = "ContactSplitForm";
|
||||
|
||||
export default ContactSplitForm;
|
||||
|
||||
@@ -1,248 +1,100 @@
|
||||
"use client";
|
||||
import React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { memo } from "react";
|
||||
import CardStack from "@/components/cardStack/CardStack";
|
||||
import Button from "@/components/button/Button";
|
||||
import PricingBadge from "@/components/shared/PricingBadge";
|
||||
import PricingFeatureList from "@/components/shared/PricingFeatureList";
|
||||
import { getButtonProps } from "@/lib/buttonUtils";
|
||||
import { cls, shouldUseInvertedText } from "@/lib/utils";
|
||||
import { useTheme } from "@/providers/themeProvider/ThemeProvider";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import type { ButtonConfig, CardAnimationType, TitleSegment, ButtonAnimationType } from "@/components/cardStack/types";
|
||||
import type { TextboxLayout, InvertedBackground } from "@/providers/themeProvider/config/constants";
|
||||
|
||||
type PricingPlan = {
|
||||
id: string;
|
||||
badge: string;
|
||||
badgeIcon?: LucideIcon;
|
||||
price: string;
|
||||
subtitle: string;
|
||||
buttons: ButtonConfig[];
|
||||
features: string[];
|
||||
};
|
||||
|
||||
interface PricingCardEightProps {
|
||||
plans: PricingPlan[];
|
||||
carouselMode?: "auto" | "buttons";
|
||||
uniformGridCustomHeightClasses?: string;
|
||||
animationType: CardAnimationType;
|
||||
title: string;
|
||||
titleSegments?: TitleSegment[];
|
||||
description: string;
|
||||
tag?: string;
|
||||
tagIcon?: LucideIcon;
|
||||
tagAnimation?: ButtonAnimationType;
|
||||
buttons?: ButtonConfig[];
|
||||
buttonAnimation?: ButtonAnimationType;
|
||||
textboxLayout: TextboxLayout;
|
||||
useInvertedBackground: InvertedBackground;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
cardClassName?: string;
|
||||
textBoxTitleClassName?: string;
|
||||
textBoxTitleImageWrapperClassName?: string;
|
||||
textBoxTitleImageClassName?: string;
|
||||
textBoxDescriptionClassName?: string;
|
||||
badgeClassName?: string;
|
||||
priceClassName?: string;
|
||||
subtitleClassName?: string;
|
||||
planButtonContainerClassName?: string;
|
||||
planButtonClassName?: string;
|
||||
featuresClassName?: string;
|
||||
featureItemClassName?: string;
|
||||
gridClassName?: string;
|
||||
carouselClassName?: string;
|
||||
controlsClassName?: string;
|
||||
textBoxClassName?: string;
|
||||
textBoxTagClassName?: string;
|
||||
textBoxButtonContainerClassName?: string;
|
||||
textBoxButtonClassName?: string;
|
||||
textBoxButtonTextClassName?: string;
|
||||
export interface PricingPlan {
|
||||
id: string;
|
||||
badge: string;
|
||||
price: string;
|
||||
subtitle: string;
|
||||
buttons: Array<{ text: string; onClick?: () => void; href?: string }>;
|
||||
features: string[];
|
||||
}
|
||||
|
||||
interface PricingCardItemProps {
|
||||
plan: PricingPlan;
|
||||
shouldUseLightText: boolean;
|
||||
cardClassName?: string;
|
||||
badgeClassName?: string;
|
||||
priceClassName?: string;
|
||||
subtitleClassName?: string;
|
||||
planButtonContainerClassName?: string;
|
||||
planButtonClassName?: string;
|
||||
featuresClassName?: string;
|
||||
featureItemClassName?: string;
|
||||
export interface PricingCardEightProps {
|
||||
plans: PricingPlan[];
|
||||
title: string;
|
||||
description: string;
|
||||
animationType?: "none" | "opacity" | "slide-up" | "scale-rotate" | "blur-reveal";
|
||||
textboxLayout?: "default" | "split" | "split-actions" | "split-description" | "inline-image";
|
||||
useInvertedBackground?: boolean;
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
cardClassName?: string;
|
||||
badgeClassName?: string;
|
||||
priceClassName?: string;
|
||||
subtitleClassName?: string;
|
||||
planButtonContainerClassName?: string;
|
||||
planButtonClassName?: string;
|
||||
featuresClassName?: string;
|
||||
featureItemClassName?: string;
|
||||
gridClassName?: string;
|
||||
textBoxClassName?: string;
|
||||
}
|
||||
|
||||
const PricingCardItem = memo(({
|
||||
plan,
|
||||
shouldUseLightText,
|
||||
cardClassName = "",
|
||||
badgeClassName = "",
|
||||
priceClassName = "",
|
||||
subtitleClassName = "",
|
||||
planButtonContainerClassName = "",
|
||||
planButtonClassName = "",
|
||||
featuresClassName = "",
|
||||
featureItemClassName = "",
|
||||
}: PricingCardItemProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
const getButtonConfigProps = () => {
|
||||
if (theme.defaultButtonVariant === "hover-bubble") {
|
||||
return { bgClassName: "w-full" };
|
||||
}
|
||||
if (theme.defaultButtonVariant === "icon-arrow") {
|
||||
return { className: "justify-between" };
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cls("relative h-full card text-foreground rounded-theme-capped p-3 flex flex-col gap-3", cardClassName)}>
|
||||
<div className="relative secondary-button p-3 flex flex-col gap-3 rounded-theme-capped" >
|
||||
<PricingBadge
|
||||
badge={plan.badge}
|
||||
badgeIcon={plan.badgeIcon}
|
||||
className={badgeClassName}
|
||||
/>
|
||||
|
||||
<div className="relative z-1 flex flex-col gap-1">
|
||||
<div className="text-5xl font-medium text-foreground">
|
||||
{plan.price}
|
||||
</div>
|
||||
|
||||
<p className="text-base text-foreground">
|
||||
{plan.subtitle}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{plan.buttons && plan.buttons.length > 0 && (
|
||||
<div className={cls("relative z-1 w-full flex flex-col gap-3", planButtonContainerClassName)}>
|
||||
{plan.buttons.slice(0, 2).map((button, index) => (
|
||||
<Button
|
||||
key={`${button.text}-${index}`}
|
||||
{...getButtonProps(
|
||||
{ ...button, props: { ...button.props, ...getButtonConfigProps() } },
|
||||
index,
|
||||
theme.defaultButtonVariant,
|
||||
cls("w-full", planButtonClassName)
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-3 pt-0" >
|
||||
<PricingFeatureList
|
||||
features={plan.features}
|
||||
shouldUseLightText={shouldUseLightText}
|
||||
className={cls("mt-1", featuresClassName)}
|
||||
featureItemClassName={featureItemClassName}
|
||||
/>
|
||||
</div>
|
||||
export const PricingCardEight: React.FC<PricingCardEightProps> = ({
|
||||
plans,
|
||||
title,
|
||||
description,
|
||||
animationType = "slide-up", textboxLayout = "default", useInvertedBackground = false,
|
||||
className,
|
||||
containerClassName,
|
||||
cardClassName,
|
||||
badgeClassName,
|
||||
priceClassName,
|
||||
subtitleClassName,
|
||||
planButtonContainerClassName,
|
||||
planButtonClassName,
|
||||
featuresClassName,
|
||||
featureItemClassName,
|
||||
gridClassName,
|
||||
textBoxClassName
|
||||
}) => {
|
||||
return (
|
||||
<div className={cn("w-full py-20 px-4", containerClassName)}>
|
||||
<div className={cn("max-w-6xl mx-auto", className)}>
|
||||
<div className={cn("text-center mb-12 space-y-4", textBoxClassName)}>
|
||||
<h2 className="text-4xl font-bold">{title}</h2>
|
||||
<p className="text-lg text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
PricingCardItem.displayName = "PricingCardItem";
|
||||
<div className={cn("grid grid-cols-1 md:grid-cols-3 gap-8", gridClassName)}>
|
||||
{plans.map((plan) => (
|
||||
<div key={plan.id} className={cn("border rounded-lg p-6 space-y-6", cardClassName)}>
|
||||
<div className="space-y-4">
|
||||
<span className={cn("inline-block text-sm font-semibold px-3 py-1 bg-primary/10 rounded-full", badgeClassName)}> {plan.badge}
|
||||
</span>
|
||||
<h3 className={cn("text-3xl font-bold", priceClassName)}>{plan.price}</h3>
|
||||
<p className={cn("text-muted-foreground", subtitleClassName)}>{plan.subtitle}</p>
|
||||
</div>
|
||||
|
||||
const PricingCardEight = ({
|
||||
plans,
|
||||
carouselMode = "buttons",
|
||||
uniformGridCustomHeightClasses,
|
||||
animationType,
|
||||
title,
|
||||
titleSegments,
|
||||
description,
|
||||
tag,
|
||||
tagIcon,
|
||||
tagAnimation,
|
||||
buttons,
|
||||
buttonAnimation,
|
||||
textboxLayout,
|
||||
useInvertedBackground,
|
||||
ariaLabel = "Pricing section",
|
||||
className = "",
|
||||
containerClassName = "",
|
||||
cardClassName = "",
|
||||
textBoxTitleClassName = "",
|
||||
textBoxTitleImageWrapperClassName = "",
|
||||
textBoxTitleImageClassName = "",
|
||||
textBoxDescriptionClassName = "",
|
||||
badgeClassName = "",
|
||||
priceClassName = "",
|
||||
subtitleClassName = "",
|
||||
planButtonContainerClassName = "",
|
||||
planButtonClassName = "",
|
||||
featuresClassName = "",
|
||||
featureItemClassName = "",
|
||||
gridClassName = "",
|
||||
carouselClassName = "",
|
||||
controlsClassName = "",
|
||||
textBoxClassName = "",
|
||||
textBoxTagClassName = "",
|
||||
textBoxButtonContainerClassName = "",
|
||||
textBoxButtonClassName = "",
|
||||
textBoxButtonTextClassName = "",
|
||||
}: PricingCardEightProps) => {
|
||||
const theme = useTheme();
|
||||
const shouldUseLightText = shouldUseInvertedText(useInvertedBackground, theme.cardStyle);
|
||||
<div className={cn("space-y-3", planButtonContainerClassName)}>
|
||||
{plan.buttons.map((button, idx) => (
|
||||
<button
|
||||
key={idx}
|
||||
onClick={button.onClick}
|
||||
className={cn(
|
||||
"w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors", planButtonClassName
|
||||
)}
|
||||
>
|
||||
{button.text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
return (
|
||||
<CardStack
|
||||
useInvertedBackground={useInvertedBackground}
|
||||
mode={carouselMode}
|
||||
gridVariant="uniform-all-items-equal"
|
||||
uniformGridCustomHeightClasses={uniformGridCustomHeightClasses}
|
||||
animationType={animationType}
|
||||
|
||||
title={title}
|
||||
titleSegments={titleSegments}
|
||||
description={description}
|
||||
tag={tag}
|
||||
tagIcon={tagIcon}
|
||||
tagAnimation={tagAnimation}
|
||||
buttons={buttons}
|
||||
buttonAnimation={buttonAnimation}
|
||||
textboxLayout={textboxLayout}
|
||||
className={className}
|
||||
containerClassName={containerClassName}
|
||||
gridClassName={gridClassName}
|
||||
carouselClassName={carouselClassName}
|
||||
controlsClassName={controlsClassName}
|
||||
textBoxClassName={textBoxClassName}
|
||||
titleClassName={textBoxTitleClassName}
|
||||
titleImageWrapperClassName={textBoxTitleImageWrapperClassName}
|
||||
titleImageClassName={textBoxTitleImageClassName}
|
||||
descriptionClassName={textBoxDescriptionClassName}
|
||||
tagClassName={textBoxTagClassName}
|
||||
buttonContainerClassName={textBoxButtonContainerClassName}
|
||||
buttonClassName={textBoxButtonClassName}
|
||||
buttonTextClassName={textBoxButtonTextClassName}
|
||||
ariaLabel={ariaLabel}
|
||||
>
|
||||
{plans.map((plan, index) => (
|
||||
<PricingCardItem
|
||||
key={`${plan.id}-${index}`}
|
||||
plan={plan}
|
||||
shouldUseLightText={shouldUseLightText}
|
||||
cardClassName={cardClassName}
|
||||
badgeClassName={badgeClassName}
|
||||
priceClassName={priceClassName}
|
||||
subtitleClassName={subtitleClassName}
|
||||
planButtonContainerClassName={planButtonContainerClassName}
|
||||
planButtonClassName={planButtonClassName}
|
||||
featuresClassName={featuresClassName}
|
||||
featureItemClassName={featureItemClassName}
|
||||
/>
|
||||
))}
|
||||
</CardStack>
|
||||
);
|
||||
<div className={cn("space-y-2", featuresClassName)}>
|
||||
{plan.features.map((feature, idx) => (
|
||||
<div key={idx} className={cn("flex items-center gap-2", featureItemClassName)}>
|
||||
<span className="text-primary">✓</span>
|
||||
<span className="text-sm">{feature}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
PricingCardEight.displayName = "PricingCardEight";
|
||||
|
||||
export default PricingCardEight;
|
||||
|
||||
@@ -1,117 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Product } from "@/lib/api/product";
|
||||
|
||||
export type CheckoutItem = {
|
||||
productId: string;
|
||||
quantity: number;
|
||||
imageSrc?: string;
|
||||
imageAlt?: string;
|
||||
metadata?: {
|
||||
brand?: string;
|
||||
variant?: string;
|
||||
rating?: number;
|
||||
reviewCount?: string;
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
export interface CartItem {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export const useCheckout = () => {
|
||||
const [cartItems, setCartItems] = useState<CartItem[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const addToCart = (item: CartItem) => {
|
||||
setCartItems((prev) => {
|
||||
const existing = prev.find((i) => i.id === item.id);
|
||||
if (existing) {
|
||||
return prev.map((i) => (i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i));
|
||||
}
|
||||
return [...prev, item];
|
||||
});
|
||||
};
|
||||
|
||||
const removeFromCart = (id: string) => {
|
||||
setCartItems((prev) => prev.filter((item) => item.id !== id));
|
||||
};
|
||||
|
||||
const updateQuantity = (id: string, quantity: number) => {
|
||||
setCartItems((prev) =>
|
||||
prev.map((item) => (item.id === id ? { ...item, quantity: Math.max(1, quantity) } : item))
|
||||
);
|
||||
};
|
||||
|
||||
const getTotal = () => {
|
||||
return cartItems.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2);
|
||||
};
|
||||
|
||||
const checkout = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Simulate checkout process
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
setCartItems([]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Checkout failed");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
cartItems,
|
||||
isLoading,
|
||||
error,
|
||||
addToCart,
|
||||
removeFromCart,
|
||||
updateQuantity,
|
||||
getTotal,
|
||||
checkout
|
||||
};
|
||||
};
|
||||
|
||||
export type CheckoutResult = {
|
||||
success: boolean;
|
||||
url?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export function useCheckout() {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const checkout = async (items: CheckoutItem[], options?: { successUrl?: string; cancelUrl?: string }): Promise<CheckoutResult> => {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
|
||||
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
const errorMsg = "NEXT_PUBLIC_API_URL or NEXT_PUBLIC_PROJECT_ID not configured";
|
||||
setError(errorMsg);
|
||||
return { success: false, error: errorMsg };
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
|
||||
const response = await fetch(`${apiUrl}/stripe/project/checkout-session`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
projectId,
|
||||
items,
|
||||
successUrl: options?.successUrl || window.location.href,
|
||||
cancelUrl: options?.cancelUrl || window.location.href,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
const errorMsg = errorData.message || `Request failed with status ${response.status}`;
|
||||
setError(errorMsg);
|
||||
return { success: false, error: errorMsg };
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.data.url) {
|
||||
window.location.href = data.data.url;
|
||||
}
|
||||
|
||||
return { success: true, url: data.data.url };
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : "Failed to create checkout session";
|
||||
setError(errorMsg);
|
||||
return { success: false, error: errorMsg };
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const buyNow = async (product: Product | string, quantity: number = 1): Promise<CheckoutResult> => {
|
||||
const successUrl = new URL(window.location.href);
|
||||
successUrl.searchParams.set("success", "true");
|
||||
|
||||
if (typeof product === "string") {
|
||||
return checkout([{ productId: product, quantity }], { successUrl: successUrl.toString() });
|
||||
}
|
||||
|
||||
let metadata: CheckoutItem["metadata"] = {};
|
||||
|
||||
if (product.metadata && Object.keys(product.metadata).length > 0) {
|
||||
const { imageSrc, imageAlt, images, ...restMetadata } = product.metadata;
|
||||
metadata = restMetadata;
|
||||
} else {
|
||||
if (product.brand) metadata.brand = product.brand;
|
||||
if (product.variant) metadata.variant = product.variant;
|
||||
if (product.rating !== undefined) metadata.rating = product.rating;
|
||||
if (product.reviewCount) metadata.reviewCount = product.reviewCount;
|
||||
}
|
||||
|
||||
return checkout([{
|
||||
productId: product.id,
|
||||
quantity,
|
||||
imageSrc: product.imageSrc,
|
||||
imageAlt: product.imageAlt,
|
||||
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
|
||||
}], { successUrl: successUrl.toString() });
|
||||
};
|
||||
|
||||
return {
|
||||
checkout,
|
||||
buyNow,
|
||||
isLoading,
|
||||
error,
|
||||
clearError: () => setError(null),
|
||||
};
|
||||
}
|
||||
@@ -1,115 +1,35 @@
|
||||
"use client";
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useProducts } from "./useProducts";
|
||||
import type { Product } from "@/lib/api/product";
|
||||
import type { CatalogProduct } from "@/components/ecommerce/productCatalog/ProductCatalogItem";
|
||||
import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
|
||||
|
||||
export type SortOption = "Newest" | "Price: Low-High" | "Price: High-Low";
|
||||
|
||||
interface UseProductCatalogOptions {
|
||||
basePath?: string;
|
||||
export interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export function useProductCatalog(options: UseProductCatalogOptions = {}) {
|
||||
const { basePath = "/shop" } = options;
|
||||
const router = useRouter();
|
||||
const { products: fetchedProducts, isLoading } = useProducts();
|
||||
export const useProductCatalog = () => {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [category, setCategory] = useState("All");
|
||||
const [sort, setSort] = useState<SortOption>("Newest");
|
||||
|
||||
const handleProductClick = useCallback((productId: string) => {
|
||||
router.push(`${basePath}/${productId}`);
|
||||
}, [router, basePath]);
|
||||
|
||||
const catalogProducts: CatalogProduct[] = useMemo(() => {
|
||||
if (fetchedProducts.length === 0) return [];
|
||||
|
||||
return fetchedProducts.map((product) => ({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
price: product.price,
|
||||
imageSrc: product.imageSrc,
|
||||
imageAlt: product.imageAlt || product.name,
|
||||
rating: product.rating || 0,
|
||||
reviewCount: product.reviewCount,
|
||||
category: product.brand,
|
||||
onProductClick: () => handleProductClick(product.id),
|
||||
}));
|
||||
}, [fetchedProducts, handleProductClick]);
|
||||
|
||||
const categories = useMemo(() => {
|
||||
const categorySet = new Set<string>();
|
||||
catalogProducts.forEach((product) => {
|
||||
if (product.category) {
|
||||
categorySet.add(product.category);
|
||||
}
|
||||
});
|
||||
return Array.from(categorySet).sort();
|
||||
}, [catalogProducts]);
|
||||
|
||||
const filteredProducts = useMemo(() => {
|
||||
let result = catalogProducts;
|
||||
|
||||
if (search) {
|
||||
const q = search.toLowerCase();
|
||||
result = result.filter(
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(q) ||
|
||||
(p.category?.toLowerCase().includes(q) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
if (category !== "All") {
|
||||
result = result.filter((p) => p.category === category);
|
||||
}
|
||||
|
||||
if (sort === "Price: Low-High") {
|
||||
result = [...result].sort(
|
||||
(a, b) =>
|
||||
parseFloat(a.price.replace("$", "").replace(",", "")) -
|
||||
parseFloat(b.price.replace("$", "").replace(",", ""))
|
||||
);
|
||||
} else if (sort === "Price: High-Low") {
|
||||
result = [...result].sort(
|
||||
(a, b) =>
|
||||
parseFloat(b.price.replace("$", "").replace(",", "")) -
|
||||
parseFloat(a.price.replace("$", "").replace(",", ""))
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [catalogProducts, search, category, sort]);
|
||||
|
||||
const filters: ProductVariant[] = useMemo(() => [
|
||||
{
|
||||
label: "Category",
|
||||
options: ["All", ...categories],
|
||||
selected: category,
|
||||
onChange: setCategory,
|
||||
},
|
||||
{
|
||||
label: "Sort",
|
||||
options: ["Newest", "Price: Low-High", "Price: High-Low"] as SortOption[],
|
||||
selected: sort,
|
||||
onChange: (value) => setSort(value as SortOption),
|
||||
},
|
||||
], [categories, category, sort]);
|
||||
|
||||
return {
|
||||
products: filteredProducts,
|
||||
isLoading,
|
||||
search,
|
||||
setSearch,
|
||||
category,
|
||||
setCategory,
|
||||
sort,
|
||||
setSort,
|
||||
filters,
|
||||
categories,
|
||||
useEffect(() => {
|
||||
const fetchProducts = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
// Simulate API call
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
// Mock data would be loaded here
|
||||
setProducts([]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load products");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fetchProducts();
|
||||
}, []);
|
||||
|
||||
return { products, isLoading, error };
|
||||
};
|
||||
|
||||
@@ -1,196 +1,37 @@
|
||||
"use client";
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useProduct } from "./useProduct";
|
||||
import type { Product } from "@/lib/api/product";
|
||||
import type { ProductVariant } from "@/components/ecommerce/productDetail/ProductDetailCard";
|
||||
import type { ExtendedCartItem } from "./useCart";
|
||||
|
||||
interface ProductImage {
|
||||
src: string;
|
||||
alt: string;
|
||||
export interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface ProductMeta {
|
||||
salePrice?: string;
|
||||
ribbon?: string;
|
||||
inventoryStatus?: string;
|
||||
inventoryQuantity?: number;
|
||||
sku?: string;
|
||||
}
|
||||
export const useProductDetail = (productId: string | undefined) => {
|
||||
const [product, setProduct] = useState<Product | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
export function useProductDetail(productId: string) {
|
||||
const { product, isLoading, error } = useProduct(productId);
|
||||
const [selectedQuantity, setSelectedQuantity] = useState(1);
|
||||
const [selectedVariants, setSelectedVariants] = useState<Record<string, string>>({});
|
||||
useEffect(() => {
|
||||
if (!productId) return;
|
||||
|
||||
const images = useMemo<ProductImage[]>(() => {
|
||||
if (!product) return [];
|
||||
|
||||
if (product.images && product.images.length > 0) {
|
||||
return product.images.map((src, index) => ({
|
||||
src,
|
||||
alt: product.imageAlt || `${product.name} - Image ${index + 1}`,
|
||||
}));
|
||||
}
|
||||
return [{
|
||||
src: product.imageSrc,
|
||||
alt: product.imageAlt || product.name,
|
||||
}];
|
||||
}, [product]);
|
||||
|
||||
const meta = useMemo<ProductMeta>(() => {
|
||||
if (!product?.metadata) return {};
|
||||
|
||||
const metadata = product.metadata;
|
||||
|
||||
let salePrice: string | undefined;
|
||||
const onSaleValue = metadata.onSale;
|
||||
const onSale = String(onSaleValue) === "true" || onSaleValue === 1 || String(onSaleValue) === "1";
|
||||
const salePriceValue = metadata.salePrice;
|
||||
|
||||
if (onSale && salePriceValue !== undefined && salePriceValue !== null) {
|
||||
if (typeof salePriceValue === 'number') {
|
||||
salePrice = `$${salePriceValue.toFixed(2)}`;
|
||||
} else {
|
||||
const salePriceStr = String(salePriceValue);
|
||||
salePrice = salePriceStr.startsWith('$') ? salePriceStr : `$${salePriceStr}`;
|
||||
}
|
||||
}
|
||||
|
||||
let inventoryQuantity: number | undefined;
|
||||
if (metadata.inventoryQuantity !== undefined) {
|
||||
const qty = metadata.inventoryQuantity;
|
||||
inventoryQuantity = typeof qty === 'number' ? qty : parseInt(String(qty), 10);
|
||||
}
|
||||
|
||||
return {
|
||||
salePrice,
|
||||
ribbon: metadata.ribbon ? String(metadata.ribbon) : undefined,
|
||||
inventoryStatus: metadata.inventoryStatus ? String(metadata.inventoryStatus) : undefined,
|
||||
inventoryQuantity,
|
||||
sku: metadata.sku ? String(metadata.sku) : undefined,
|
||||
};
|
||||
}, [product]);
|
||||
|
||||
const variants = useMemo<ProductVariant[]>(() => {
|
||||
if (!product) return [];
|
||||
|
||||
const variantList: ProductVariant[] = [];
|
||||
|
||||
if (product.metadata?.variantOptions) {
|
||||
try {
|
||||
const variantOptionsStr = String(product.metadata.variantOptions);
|
||||
const parsedOptions = JSON.parse(variantOptionsStr);
|
||||
|
||||
if (Array.isArray(parsedOptions)) {
|
||||
parsedOptions.forEach((option: any) => {
|
||||
if (option.name && option.values) {
|
||||
const values = typeof option.values === 'string'
|
||||
? option.values.split(',').map((v: string) => v.trim())
|
||||
: Array.isArray(option.values)
|
||||
? option.values.map((v: any) => String(v).trim())
|
||||
: [String(option.values)];
|
||||
|
||||
if (values.length > 0) {
|
||||
const optionLabel = option.name;
|
||||
const currentSelected = selectedVariants[optionLabel] || values[0];
|
||||
|
||||
variantList.push({
|
||||
label: optionLabel,
|
||||
options: values,
|
||||
selected: currentSelected,
|
||||
onChange: (value) => {
|
||||
setSelectedVariants((prev) => ({
|
||||
...prev,
|
||||
[optionLabel]: value,
|
||||
}));
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to parse variantOptions:", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (variantList.length === 0 && product.brand) {
|
||||
variantList.push({
|
||||
label: "Brand",
|
||||
options: [product.brand],
|
||||
selected: product.brand,
|
||||
onChange: () => { },
|
||||
});
|
||||
}
|
||||
|
||||
if (variantList.length === 0 && product.variant) {
|
||||
const variantOptions = product.variant.includes('/')
|
||||
? product.variant.split('/').map(v => v.trim())
|
||||
: [product.variant];
|
||||
|
||||
const variantLabel = "Variant";
|
||||
const currentSelected = selectedVariants[variantLabel] || variantOptions[0];
|
||||
|
||||
variantList.push({
|
||||
label: variantLabel,
|
||||
options: variantOptions,
|
||||
selected: currentSelected,
|
||||
onChange: (value) => {
|
||||
setSelectedVariants((prev) => ({
|
||||
...prev,
|
||||
[variantLabel]: value,
|
||||
}));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return variantList;
|
||||
}, [product, selectedVariants]);
|
||||
|
||||
const quantityVariant = useMemo<ProductVariant>(() => ({
|
||||
label: "Quantity",
|
||||
options: Array.from({ length: 10 }, (_, i) => String(i + 1)),
|
||||
selected: String(selectedQuantity),
|
||||
onChange: (value) => setSelectedQuantity(parseInt(value, 10)),
|
||||
}), [selectedQuantity]);
|
||||
|
||||
const createCartItem = useCallback((): ExtendedCartItem | null => {
|
||||
if (!product) return null;
|
||||
|
||||
const variantStrings = Object.entries(selectedVariants).map(
|
||||
([label, value]) => `${label}: ${value}`
|
||||
);
|
||||
|
||||
if (variantStrings.length === 0 && product.variant) {
|
||||
variantStrings.push(`Variant: ${product.variant}`);
|
||||
}
|
||||
|
||||
const variantId = Object.values(selectedVariants).join('-') || 'default';
|
||||
|
||||
return {
|
||||
id: `${product.id}-${variantId}-${selectedQuantity}`,
|
||||
productId: product.id,
|
||||
name: product.name,
|
||||
variants: variantStrings,
|
||||
price: product.price,
|
||||
quantity: selectedQuantity,
|
||||
imageSrc: product.imageSrc,
|
||||
imageAlt: product.imageAlt || product.name,
|
||||
};
|
||||
}, [product, selectedVariants, selectedQuantity]);
|
||||
|
||||
return {
|
||||
product,
|
||||
isLoading,
|
||||
error,
|
||||
images,
|
||||
meta,
|
||||
variants,
|
||||
quantityVariant,
|
||||
selectedQuantity,
|
||||
selectedVariants,
|
||||
createCartItem,
|
||||
const fetchProduct = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
// Simulate API call
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
// Product would be fetched here
|
||||
setProduct(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load product");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fetchProduct();
|
||||
}, [productId]);
|
||||
|
||||
return { product, isLoading, error };
|
||||
};
|
||||
|
||||
@@ -1,219 +1,34 @@
|
||||
export type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
price: string;
|
||||
imageSrc: string;
|
||||
imageAlt?: string;
|
||||
images?: string[];
|
||||
brand?: string;
|
||||
variant?: string;
|
||||
rating?: number;
|
||||
reviewCount?: string;
|
||||
description?: string;
|
||||
priceId?: string;
|
||||
metadata?: {
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
onFavorite?: () => void;
|
||||
onProductClick?: () => void;
|
||||
isFavorited?: boolean;
|
||||
export interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export const fetchProducts = async (): Promise<Product[]> => {
|
||||
try {
|
||||
// Simulate API call
|
||||
const response = await fetch("/api/products");
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
} catch {
|
||||
console.error("Failed to fetch products");
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const defaultProducts: Product[] = [
|
||||
{
|
||||
id: "1",
|
||||
name: "Classic White Sneakers",
|
||||
price: "$129",
|
||||
brand: "Nike",
|
||||
variant: "White / Size 42",
|
||||
rating: 4.5,
|
||||
reviewCount: "128",
|
||||
imageSrc: "/placeholders/placeholder3.avif",
|
||||
imageAlt: "Classic white sneakers",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
name: "Leather Crossbody Bag",
|
||||
price: "$89",
|
||||
brand: "Coach",
|
||||
variant: "Brown / Medium",
|
||||
rating: 4.8,
|
||||
reviewCount: "256",
|
||||
imageSrc: "/placeholders/placeholder4.webp",
|
||||
imageAlt: "Brown leather crossbody bag",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
name: "Wireless Headphones",
|
||||
price: "$199",
|
||||
brand: "Sony",
|
||||
variant: "Black",
|
||||
rating: 4.7,
|
||||
reviewCount: "512",
|
||||
imageSrc: "/placeholders/placeholder3.avif",
|
||||
imageAlt: "Black wireless headphones",
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
name: "Minimalist Watch",
|
||||
price: "$249",
|
||||
brand: "Fossil",
|
||||
variant: "Silver / 40mm",
|
||||
rating: 4.6,
|
||||
reviewCount: "89",
|
||||
imageSrc: "/placeholders/placeholder4.webp",
|
||||
imageAlt: "Silver minimalist watch",
|
||||
},
|
||||
];
|
||||
|
||||
function formatPrice(amount: number, currency: string): string {
|
||||
const formatter = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: currency.toUpperCase(),
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return formatter.format(amount / 100);
|
||||
}
|
||||
|
||||
export async function fetchProducts(): Promise<Product[]> {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
|
||||
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
return [];
|
||||
export const fetchProductById = async (id: string): Promise<Product | null> => {
|
||||
try {
|
||||
const response = await fetch(`/api/products/${id}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${apiUrl}/stripe/project/products?projectId=${projectId}&expandDefaultPrice=true`;
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const resp = await response.json();
|
||||
const data = resp.data.data || resp.data;
|
||||
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return data.map((product: any) => {
|
||||
const metadata: Record<string, string | number | undefined> = {};
|
||||
if (product.metadata && typeof product.metadata === 'object') {
|
||||
Object.keys(product.metadata).forEach(key => {
|
||||
const value = product.metadata[key];
|
||||
if (value !== null && value !== undefined) {
|
||||
const numValue = parseFloat(value);
|
||||
metadata[key] = isNaN(numValue) ? value : numValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const imageSrc = product.images?.[0] || product.imageSrc || "/placeholders/placeholder3.avif";
|
||||
const imageAlt = product.imageAlt || product.name || "";
|
||||
const images = product.images && Array.isArray(product.images) && product.images.length > 0
|
||||
? product.images
|
||||
: [imageSrc];
|
||||
|
||||
return {
|
||||
id: product.id || String(Math.random()),
|
||||
name: product.name || "Untitled Product",
|
||||
description: product.description || "",
|
||||
price: product.default_price?.unit_amount
|
||||
? formatPrice(product.default_price.unit_amount, product.default_price.currency || "usd")
|
||||
: product.price || "$0",
|
||||
priceId: product.default_price?.id || product.priceId,
|
||||
imageSrc,
|
||||
imageAlt,
|
||||
images,
|
||||
brand: product.metadata?.brand || product.brand || "",
|
||||
variant: product.metadata?.variant || product.variant || "",
|
||||
rating: product.metadata?.rating ? parseFloat(product.metadata.rating) : undefined,
|
||||
reviewCount: product.metadata?.reviewCount || undefined,
|
||||
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchProduct(productId: string): Promise<Product | null> {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
|
||||
const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${apiUrl}/stripe/project/products/${productId}?projectId=${projectId}&expandDefaultPrice=true`;
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resp = await response.json();
|
||||
const product = resp.data?.data || resp.data || resp;
|
||||
|
||||
if (!product || typeof product !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata: Record<string, string | number | undefined> = {};
|
||||
if (product.metadata && typeof product.metadata === 'object') {
|
||||
Object.keys(product.metadata).forEach(key => {
|
||||
const value = product.metadata[key];
|
||||
if (value !== null && value !== undefined && value !== '') {
|
||||
const numValue = parseFloat(String(value));
|
||||
metadata[key] = isNaN(numValue) ? String(value) : numValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let priceValue = product.price;
|
||||
if (!priceValue && product.default_price?.unit_amount) {
|
||||
priceValue = formatPrice(product.default_price.unit_amount, product.default_price.currency || "usd");
|
||||
}
|
||||
if (!priceValue) {
|
||||
priceValue = "$0";
|
||||
}
|
||||
|
||||
const imageSrc = product.images?.[0] || product.imageSrc || "/placeholders/placeholder3.avif";
|
||||
const imageAlt = product.imageAlt || product.name || "";
|
||||
const images = product.images && Array.isArray(product.images) && product.images.length > 0
|
||||
? product.images
|
||||
: [imageSrc];
|
||||
|
||||
return {
|
||||
id: product.id || String(Math.random()),
|
||||
name: product.name || "Untitled Product",
|
||||
description: product.description || "",
|
||||
price: priceValue,
|
||||
priceId: product.default_price?.id || product.priceId,
|
||||
imageSrc,
|
||||
imageAlt,
|
||||
images,
|
||||
brand: product.metadata?.brand || product.brand || "",
|
||||
variant: product.metadata?.variant || product.variant || "",
|
||||
rating: product.metadata?.rating ? parseFloat(String(product.metadata.rating)) : undefined,
|
||||
reviewCount: product.metadata?.reviewCount || undefined,
|
||||
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return await response.json();
|
||||
} catch {
|
||||
console.error("Failed to fetch product");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user