Files
webb/src/components/sections/TryItWidget.tsx
T

436 lines
16 KiB
TypeScript

'use client';
import React, { useState, useRef } from 'react';
import Link from 'next/link';
import {
UploadCloud,
AlertCircle,
RefreshCw,
Download,
Smartphone,
Loader2,
Image as ImageIcon,
} from 'lucide-react';
import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types';
import { CardBeforeAfterSlider } from '../ui/CardBeforeAfterSlider';
import { TurnstileWidget } from '@/components/turnstile/TurnstileWidget';
interface TryItWidgetProps {
tool: ToolItem;
homeApp?: AppItem | null;
variants?: VariantSpec[];
locale?: string;
className?: string;
samplePresets?: Array<{ label: string; url: string; resultUrl?: string }>;
ctaText?: string;
onSwitchToCompare?: () => void;
}
export function TryItWidget({
tool,
homeApp,
variants = [],
locale = 'en',
className = '',
samplePresets,
ctaText,
}: TryItWidgetProps) {
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [resultUrl, setResultUrl] = useState<string | null>(null);
const [activeVariant, setActiveVariant] = useState<string>(
tool.tryIt?.endpointRef?.defaultVariant || (variants.length > 0 ? variants[0].id : '')
);
const [status, setStatus] = useState<'idle' | 'selected' | 'processing' | 'success' | 'limit' | 'error' | 'unavailable'>('idle');
const [errorMessage, setErrorMessage] = useState<string>('');
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
const [turnstileToken, setTurnstileToken] = useState<string>('');
const [isDragOver, setIsDragOver] = useState<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const activePresets = samplePresets && samplePresets.length > 0
? samplePresets
: [
{
label: 'Sample portrait',
url: (tool as any).media?.before || '/management/pages/home/sections/our-tools/blemish-remover/before.jpg',
resultUrl: (tool as any).media?.after || '/management/pages/home/sections/our-tools/blemish-remover/after.jpg',
},
];
const handleFileChange = (file: File) => {
const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
if (!validTypes.includes(file.type)) {
setStatus('error');
setErrorMessage('Please upload a valid JPG, PNG, or WebP photo.');
return;
}
const maxBytes = (tool.tryIt?.limits?.maxMB || 12) * 1024 * 1024;
if (file.size > maxBytes) {
setStatus('error');
setErrorMessage(`Image exceeds max size of ${tool.tryIt?.limits?.maxMB || 12}MB.`);
return;
}
setSelectedFile(file);
const objectUrl = URL.createObjectURL(file);
setPreviewUrl(objectUrl);
setResultUrl(null);
setStatus('selected');
setErrorMessage('');
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
handleFileChange(e.dataTransfer.files[0]);
}
};
const loadSamplePreset = async (presetUrl: string, sampleResult?: string) => {
try {
setStatus('selected');
setPreviewUrl(presetUrl);
if (sampleResult) {
setResultUrl(sampleResult);
}
const res = await fetch(presetUrl);
const blob = await res.blob();
const file = new File([blob], 'sample_photo.jpg', { type: 'image/jpeg' });
setSelectedFile(file);
setErrorMessage('');
} catch {
setStatus('error');
setErrorMessage('Failed to load sample image.');
}
};
const runTryIt = async () => {
if (!selectedFile && !previewUrl) return;
setStatus('processing');
setErrorMessage('');
try {
const formData = new FormData();
if (selectedFile) {
formData.append('image', selectedFile);
} else if (previewUrl) {
const res = await fetch(previewUrl);
const blob = await res.blob();
formData.append('image', blob, 'preset.jpg');
}
if (activeVariant) {
formData.append('variant', activeVariant);
}
if (turnstileToken) {
formData.append('cf-turnstile-response', turnstileToken);
}
const response = await fetch(`/api/try/${tool.id}`, {
method: 'POST',
body: formData,
});
if (response.status === 429) {
setStatus('limit');
setRemainingTries(0);
return;
}
if (response.status === 503) {
setStatus('unavailable');
return;
}
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
setStatus('error');
setErrorMessage(errData?.error?.message || 'Inference call failed. Please try another image.');
return;
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
setResultUrl(url);
setStatus('success');
setRemainingTries((prev) => Math.max(0, prev - 1));
} catch {
setStatus('error');
setErrorMessage('Network error connecting to inference API.');
}
};
const reset = () => {
setSelectedFile(null);
setPreviewUrl(null);
setResultUrl(null);
setStatus('idle');
setErrorMessage('');
if (fileInputRef.current) fileInputRef.current.value = '';
};
return (
<div className={`w-full ${className}`}>
{/* Top Header Row */}
<div className="flex items-center justify-between pb-3 border-b border-rule text-xs font-body">
<div className="flex items-center gap-2">
<span className="font-medium text-ink">{resolveLocalised(tool.name, locale)}</span>
<span className="text-muted">· Web trial</span>
</div>
<div className="text-muted">
<span>{remainingTries} free tries remaining today</span>
</div>
</div>
{/* Error Message */}
{errorMessage && (
<div className="mt-4 p-3 bg-paper-2 border border-rule rounded-card flex items-center gap-2 text-xs text-ink font-body">
<AlertCircle className="w-4 h-4 text-accent shrink-0" aria-hidden="true" />
<span>{errorMessage}</span>
</div>
)}
{/* Main Body */}
<div className="mt-5">
{status === 'idle' && (
<div className="space-y-4">
{/* Drag & Drop Upload Zone */}
<div
onDrop={handleDrop}
onDragOver={(e) => {
e.preventDefault();
setIsDragOver(true);
}}
onDragLeave={() => setIsDragOver(false)}
onClick={() => fileInputRef.current?.click()}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
fileInputRef.current?.click();
}
}}
role="button"
tabIndex={0}
aria-label="Upload photo to edit"
className={`border border-dashed rounded-card p-8 sm:p-12 text-center cursor-pointer transition-colors duration-150 min-h-[300px] flex flex-col items-center justify-center ${
isDragOver
? 'border-accent bg-paper-2'
: 'border-rule hover:border-ink bg-paper-2/60'
}`}
>
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => e.target.files?.[0] && handleFileChange(e.target.files[0])}
/>
<div className="mb-3 text-accent">
<UploadCloud className="w-8 h-8" aria-hidden="true" />
</div>
<div className="mb-2">
<span className="btn-primary text-xs">
Choose photo to upload
</span>
</div>
<p className="text-sm font-body text-ink-2 mt-2">
or drag and drop your photo into this workspace
</p>
<p className="mt-1 text-xs text-muted font-body">
Supports JPG, PNG, WebP up to {tool.tryIt?.limits?.maxMB || 12}MB
</p>
</div>
{/* Quick Sample Preset */}
<div className="pt-1 flex items-center gap-2 text-xs font-body text-muted">
<span>Or test preset:</span>
{activePresets.map((preset, idx) => (
<button
key={idx}
type="button"
onClick={() => loadSamplePreset(preset.url, preset.resultUrl)}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded bg-paper-2 hover:bg-paper-3 border border-rule text-ink transition-colors"
>
<ImageIcon className="w-3.5 h-3.5 text-muted" aria-hidden="true" />
<span>{preset.label}</span>
</button>
))}
</div>
</div>
)}
{status === 'selected' && previewUrl && (
<div className="space-y-5">
<div className="grid grid-cols-1 md:grid-cols-2 gap-5 items-start">
{/* Preview */}
<div className="relative aspect-[4/3] rounded-card overflow-hidden border border-rule bg-paper-2">
<img src={previewUrl} alt="Selected photo" className="w-full h-full object-cover" />
<button
type="button"
onClick={reset}
className="absolute top-2.5 right-2.5 bg-paper-hi text-ink text-xs px-2.5 py-1 rounded border border-rule hover:border-ink transition-colors font-body shadow-sm"
>
Change photo
</button>
</div>
{/* Mode Selection & Run Action */}
<div className="space-y-4">
{variants.length > 0 && (
<div>
<label className="block text-xs font-body text-muted mb-2">
{resolveLocalised(tool.tryIt?.variantControl?.label, locale, 'Retouch mode')}
</label>
<div className="space-y-1.5">
{variants.map((v) => (
<label
key={v.id}
className={`flex items-center justify-between p-2.5 rounded-card border cursor-pointer transition-colors duration-100 ${
activeVariant === v.id
? 'border-accent bg-paper-hi text-ink'
: 'border-rule hover:border-ink bg-paper-2 text-ink-2'
}`}
>
<div className="flex items-center space-x-2.5">
<input
type="radio"
name="variant"
value={v.id}
checked={activeVariant === v.id}
onChange={() => setActiveVariant(v.id)}
className="accent-[var(--color-accent)] h-3.5 w-3.5"
/>
<div>
<p className="text-xs font-body font-medium text-ink">
{resolveLocalised(v.label, locale, v.description || v.id)}
</p>
{v.description && (
<p className="text-[11px] text-muted font-body">{v.description}</p>
)}
</div>
</div>
</label>
))}
</div>
</div>
)}
<div className="py-2 flex justify-center">
<TurnstileWidget
onVerify={(tok) => setTurnstileToken(tok)}
onExpire={() => setTurnstileToken('')}
theme="auto"
size="flexible"
/>
</div>
<button
type="button"
onClick={runTryIt}
className="btn-primary w-full text-center"
>
<span>{ctaText || `Process ${resolveLocalised(tool.name, locale)}`}</span>
</button>
</div>
</div>
</div>
)}
{status === 'processing' && (
<div className="py-14 text-center space-y-4">
<div className="inline-flex p-4 rounded-card bg-paper-2 border border-rule text-accent">
<Loader2 className="w-8 h-8 animate-spin text-accent" aria-hidden="true" />
</div>
<div>
<h4 className="text-base font-body font-semibold text-ink">
Processing neural layers…
</h4>
<p className="text-xs text-muted max-w-sm mx-auto mt-1 font-body">
Synthesizing sub-pixel output in volatile GPU memory while preserving skin pores and edges.
</p>
</div>
</div>
)}
{status === 'success' && previewUrl && resultUrl && (
<div className="space-y-5">
<div className="aspect-[4/3] rounded-card overflow-hidden bg-paper-2 border border-rule">
<CardBeforeAfterSlider
beforeUrl={previewUrl}
afterUrl={resultUrl}
beforeLabel="Original"
afterLabel="Enhanced"
/>
</div>
{/* Actions: Download & Reset */}
<div className="flex flex-wrap items-center justify-between gap-3 pt-2">
<button
type="button"
onClick={reset}
className="btn-secondary"
>
<RefreshCw className="w-3.5 h-3.5" aria-hidden="true" />
<span>Process another photo</span>
</button>
<a
href={resultUrl}
download={`${tool.slug}-result.png`}
className="btn-primary"
>
<Download className="w-3.5 h-3.5" aria-hidden="true" />
<span>Download output</span>
</a>
</div>
{/* Mobile App Handoff */}
{homeApp && (
<div className="mt-4 p-4 rounded-card bg-paper-2 border border-rule flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
<div className="space-y-0.5">
<span className="text-xs font-body font-semibold text-ink">
Need batch processing or 4K lossless export?
</span>
<p className="text-xs text-muted font-body">
Download {resolveLocalised(homeApp.name, locale)} on your phone for unlimited processing.
</p>
</div>
<Link
href={`/apps/${homeApp.slug}`}
className="btn-secondary shrink-0 text-xs"
>
<Smartphone className="w-3.5 h-3.5 text-accent" aria-hidden="true" />
<span>Get mobile app</span>
</Link>
</div>
)}
</div>
)}
{status === 'limit' && (
<div className="p-8 text-center space-y-4 bg-paper-2 border border-rule rounded-card">
<h4 className="text-base font-body font-semibold text-ink">
Daily browser limit reached
</h4>
<p className="text-xs text-muted max-w-sm mx-auto font-body">
You have completed all free browser sessions for today. Download our mobile app for unlimited inferences.
</p>
{homeApp && (
<Link href={`/apps/${homeApp.slug}`} className="btn-primary inline-flex">
<span>Open {resolveLocalised(homeApp.name, locale)}</span>
</Link>
)}
</div>
)}
</div>
</div>
);
}