feat: complete dynamic JSON-driven photo tools frontend connected to FastAPI backend

This commit is contained in:
2026-11-03 12:24:43 +05:30
commit fa2eca3643
91 changed files with 11372 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from 'next/server';
import { normaliseCatalog } from '@/lib/catalog/loader';
export const dynamic = 'force-dynamic';
export async function POST() {
try {
const { endpoints, diff } = normaliseCatalog();
return NextResponse.json({
success: true,
timestamp: new Date().toISOString(),
totalEndpoints: endpoints.length,
diff,
});
} catch (err: any) {
return NextResponse.json(
{ success: false, error: err.message },
{ status: 500 }
);
}
}
export async function GET() {
return POST();
}
+148
View File
@@ -0,0 +1,148 @@
import { NextRequest, NextResponse } from 'next/server';
import { getToolById, getToolBySlug } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
export const dynamic = 'force-dynamic';
export const maxDuration = 60; // 60 seconds request timeout per PRD §4.1
export async function POST(req: NextRequest, { params }: { params: { toolId: string } }) {
const toolIdentifier = params.toolId;
const tool = getToolById(toolIdentifier) || getToolBySlug(toolIdentifier);
if (!tool) {
return NextResponse.json(
{ state: 'failed', error: { code: 'TOOL_NOT_FOUND', messageKey: 'toolNotFound', retryable: false } },
{ status: 404 }
);
}
if (!tool.tryIt || !tool.tryIt.enabled) {
return NextResponse.json(
{ state: 'unavailable', messageKey: 'toolUnavailable' },
{ status: 403 }
);
}
const endpointId = tool.tryIt.endpointRef?.id;
const endpoint = endpointId ? getEndpointById(endpointId) : undefined;
if (!endpoint || !endpoint.enabled || !endpoint.publicTry || isCircuitOpen(endpoint.id)) {
return NextResponse.json(
{ state: 'unavailable', messageKey: 'toolTemporarilyUnavailable' },
{ status: 503 }
);
}
// Rate Limiting & Abuse Prevention
const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || '127.0.0.1';
let visitorId = req.cookies.get('photoai_vid')?.value;
let isNewVisitor = false;
if (!visitorId) {
visitorId = 'v_' + Math.random().toString(36).substring(2, 15);
isNewVisitor = true;
}
const rateCheck = checkRateLimits(visitorId, ip);
if (!rateCheck.allowed) {
const res = NextResponse.json(
{
state: 'limit',
messageKey: rateCheck.reason === 'budget_exhausted' ? 'dailyBudgetExceeded' : 'freeTriesExhausted',
remainingToday: 0,
},
{ status: 429 }
);
if (isNewVisitor) {
res.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: 60 * 60 * 24 * 30, httpOnly: true });
}
return res;
}
try {
const formData = await req.formData();
const file = formData.get('image') as File | null;
const variantId = (formData.get('variant') as string) || tool.tryIt.endpointRef?.defaultVariant;
const optionsRaw = formData.get('options') as string | null;
let options: Record<string, any> = {};
if (optionsRaw) {
try {
options = JSON.parse(optionsRaw);
} catch {
// Ignore malformed options
}
}
if (!file) {
return NextResponse.json(
{ state: 'failed', error: { code: 'NO_IMAGE', messageKey: 'noImageProvided', retryable: false } },
{ status: 400 }
);
}
// Size limit check
const maxBytes = (tool.tryIt.limits?.maxMB || 12) * 1024 * 1024;
if (file.size > maxBytes) {
return NextResponse.json(
{ state: 'failed', error: { code: 'FILE_TOO_LARGE', messageKey: 'fileTooLarge', retryable: false } },
{ status: 400 }
);
}
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// File signature verification (JPEG, PNG, WEBP)
const sigCheck = checkFileSignature(buffer);
if (!sigCheck.valid) {
return NextResponse.json(
{ state: 'failed', error: { code: 'INVALID_SIGNATURE', messageKey: 'invalidFileType', retryable: false } },
{ status: 400 }
);
}
// Record rate-limit usage
recordUsage(visitorId, ip);
// Call backend or mock engine
const { buffer: resultBuffer, contentType } = await executeBackendTryIt(
endpoint,
tool.id,
variantId,
buffer,
file.name || 'image.jpg',
options
);
const response = new NextResponse(new Uint8Array(resultBuffer), {
status: 200,
headers: {
'Content-Type': contentType,
'Content-Length': resultBuffer.length.toString(),
'Cache-Control': 'no-store, no-cache, must-revalidate',
'X-Remaining-Tries': rateCheck.remainingToday.toString(),
},
});
if (isNewVisitor) {
response.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: 60 * 60 * 24 * 30, httpOnly: true });
}
return response;
} catch (err: any) {
console.error(`[API /try/${toolIdentifier}] Error:`, err);
return NextResponse.json(
{
state: 'failed',
error: {
code: 'PROCESSING_ERROR',
messageKey: 'processingError',
message: err.message || 'Internal processing error',
retryable: true,
},
},
{ status: 500 }
);
}
}
+81
View File
@@ -0,0 +1,81 @@
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getAllApps, getAppBySlug, getAllTools, getTemplate } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { resolveLocalised } from '@/types';
interface AppPageProps {
params: { slug: string };
}
export async function generateStaticParams() {
const apps = getAllApps();
return apps.map((a) => ({ slug: a.slug }));
}
export async function generateMetadata({ params }: AppPageProps): Promise<Metadata> {
const app = getAppBySlug(params.slug);
if (!app) return {};
const name = resolveLocalised(app.name, 'en');
const tagline = resolveLocalised(app.tagline, 'en');
return {
title: `${name} | Official Mobile App Download`,
description: tagline,
alternates: {
canonical: `/apps/${app.slug}`,
},
openGraph: {
title: `${name} — AI Photo Editing App`,
description: tagline,
type: 'website',
},
};
}
export default function AppDetailPage({ params }: AppPageProps) {
const app = getAppBySlug(params.slug);
if (!app) notFound();
const template = getTemplate('app') || { sections: [] };
const allTools = getAllTools();
const appTools = allTools.filter((t) => app.tools.includes(t.id));
const context = {
app,
tools: appTools,
locale: 'en',
};
// Structured Data (JSON-LD) per PRD §10 SEO-07
const structuredData = {
'@context': 'https://schema.org',
'@type': 'SoftwareApplication',
name: resolveLocalised(app.name, 'en'),
operatingSystem: 'ANDROID, IOS',
applicationCategory: 'MultimediaApplication',
aggregateRating: {
'@type': 'AggregateRating',
ratingValue: app.rating.value.toString(),
ratingCount: app.rating.count.toString(),
},
offers: {
'@type': 'Offer',
price: '0',
priceCurrency: 'USD',
},
};
return (
<div>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
/>
{template.sections.map((section: any) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { Metadata } from 'next';
import { getPageConfig, getAllApps, getAllTools } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const metadata: Metadata = {
title: 'Dedicated Mobile Apps Suite | Android & iOS | Ekagni PhotoAI',
description: 'Download our suite of AI photo editing apps for Android and iOS. Built with hardware-accelerated neural networks and 4K lossless export.',
};
export default function AppsIndexPage() {
const page = getPageConfig('apps');
if (!page) notFound();
const apps = getAllApps();
const tools = getAllTools();
const context = {
page,
apps,
tools,
locale: 'en',
};
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
);
}
+131
View File
@@ -0,0 +1,131 @@
'use client';
import React, { useState, useEffect } from 'react';
import { RefreshCw, CheckCircle2, AlertTriangle, ShieldCheck, Database, Layers, ArrowRight } from 'lucide-react';
import { EndpointSpec, DiffReport } from '@/types';
export default function CatalogManagerPage() {
const [endpoints, setEndpoints] = useState<EndpointSpec[]>([]);
const [diff, setDiff] = useState<DiffReport | null>(null);
const [loading, setLoading] = useState(true);
const [reloading, setReloading] = useState(false);
const [selectedEndpoint, setSelectedEndpoint] = useState<EndpointSpec | null>(null);
const fetchCatalog = async () => {
setLoading(true);
try {
const res = await fetch('/api/catalog/reload', { method: 'POST' });
const data = await res.json();
if (data.success) {
setDiff(data.diff);
}
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchCatalog();
}, []);
const triggerReload = async () => {
setReloading(true);
try {
const res = await fetch('/api/catalog/reload', { method: 'POST' });
const data = await res.json();
if (data.success) {
setDiff(data.diff);
}
} catch (err) {
console.error(err);
} finally {
setReloading(false);
}
};
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
{/* Top Banner */}
<div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4 pb-8 border-b border-slate-200 dark:border-slate-800">
<div>
<div className="inline-flex items-center space-x-2 px-3 py-1 rounded-full bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400 text-xs font-semibold mb-2">
<Database className="w-3.5 h-3.5" />
<span>Catalogue-Driven API Engine (PRD §7)</span>
</div>
<h1 className="text-3xl font-bold text-slate-900 dark:text-white">
Backend API Catalogue Inspector
</h1>
<p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
Real-time reflection of FastAPI endpoints, overlays, parameters, variants, and snapshot diffs.
</p>
</div>
<button
onClick={triggerReload}
disabled={reloading}
className="inline-flex items-center space-x-2 px-5 py-2.5 rounded-xl text-sm font-semibold text-white bg-blue-600 hover:bg-blue-700 shadow-md shadow-blue-500/20 disabled:opacity-50 transition-all active:scale-95"
>
<RefreshCw className={`w-4 h-4 ${reloading ? 'animate-spin' : ''}`} />
<span>Reload & Diff Snapshot</span>
</button>
</div>
{/* Snapshot Diff Card */}
{diff && (
<div className="my-8 p-6 rounded-2xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-sm grid grid-cols-2 sm:grid-cols-4 gap-4">
<div className="space-y-1">
<p className="text-xs font-medium text-slate-500">Total Active Endpoints</p>
<p className="text-2xl font-bold text-slate-900 dark:text-white">{diff.totalEndpoints}</p>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-slate-500">Added Endpoints</p>
<p className="text-2xl font-bold text-emerald-600">{diff.addedEndpointIds.length}</p>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-slate-500">Changed Endpoints</p>
<p className="text-2xl font-bold text-blue-600">{diff.changedEndpointIds.length}</p>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-slate-500">Misconfigured</p>
<p className="text-2xl font-bold text-amber-600">{diff.misconfiguredEndpoints.length}</p>
</div>
</div>
)}
{/* Key Architectural Guarantees */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10">
<div className="p-5 rounded-2xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 space-y-2">
<div className="flex items-center space-x-2 text-emerald-600 font-semibold text-sm">
<ShieldCheck className="w-4 h-4" />
<span>Zero Secret Leakage</span>
</div>
<p className="text-xs text-slate-600 dark:text-slate-400">
Secrets and authentication keys stay server-side only. Browser calls exclusively talk to <code>/api/try/*</code>.
</p>
</div>
<div className="p-5 rounded-2xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 space-y-2">
<div className="flex items-center space-x-2 text-blue-600 font-semibold text-sm">
<Layers className="w-4 h-4" />
<span>Two-Layer Decoupling</span>
</div>
<p className="text-xs text-slate-600 dark:text-slate-400">
FastAPI owner edits <code>api.catalog.json</code> anytime. Website settings live independently in <code>api.overlay.json</code>.
</p>
</div>
<div className="p-5 rounded-2xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 space-y-2">
<div className="flex items-center space-x-2 text-indigo-600 font-semibold text-sm">
<CheckCircle2 className="w-4 h-4" />
<span>Graceful Degradation</span>
</div>
<p className="text-xs text-slate-600 dark:text-slate-400">
Missing or invalid catalogue endpoints automatically flag tools as unavailable without taking down the website.
</p>
</div>
</div>
</div>
);
}
+36
View File
@@ -0,0 +1,36 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--color-primary: #2563EB;
--color-primary-hover: #1D4ED8;
--color-primary-light: #EFF6FF;
--color-primary-dark: #1E40AF;
--color-accent: #0E9F9A;
--color-accent-hover: #0B7F7B;
--color-accent-light: #F0FDF4;
--color-surface: #FFFFFF;
--color-surface-subtle: #F8FAFC;
--color-surface-dark: #0F172A;
--color-surface-dark-subtle: #1E293B;
--theme-radius: 12px;
--theme-max-width: 1280px;
}
.dark {
--color-surface: #0B1220;
--color-surface-subtle: #0F172A;
}
body {
color: #0F1F3D;
background-color: #FFFFFF;
font-family: Inter, system-ui, -apple-system, sans-serif;
overflow-x: hidden;
}
.dark body {
color: #E5E9F2;
background-color: #0B1220;
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAppBySlug, getAppById, getToolBySlug, getToolById } from '@/lib/config/loader';
export const dynamic = 'force-dynamic';
export async function GET(
req: NextRequest,
{ params }: { params: { tool: string; app: string } }
) {
const tool = getToolBySlug(params.tool) || getToolById(params.tool);
const app = getAppBySlug(params.app) || getAppById(params.app);
if (!app) {
return NextResponse.redirect(new URL('/apps', req.url));
}
const userAgent = req.headers.get('user-agent') || '';
const isAndroid = /android/i.test(userAgent);
const isIOS = /ipad|iphone|ipod/i.test(userAgent);
const searchParams = req.nextUrl.searchParams;
const source = searchParams.get('utm_source') || 'web_try';
const campaign = searchParams.get('utm_campaign') || (tool ? tool.slug : 'general');
const promo = searchParams.get('promo') || (app.welcomeBonus ? app.welcomeBonus.code : 'TRYWEB50');
if (isAndroid) {
const playUrl = app.stores.android?.url || 'https://play.google.com';
const finalUrl = new URL(playUrl);
finalUrl.searchParams.set('referrer', `utm_source=${source}&utm_campaign=${campaign}&promo=${promo}`);
return NextResponse.redirect(finalUrl.toString());
}
if (isIOS) {
const iosUrl = app.stores.ios?.url || 'https://apps.apple.com';
const finalUrl = new URL(iosUrl);
finalUrl.searchParams.set('pt', '123456');
finalUrl.searchParams.set('ct', `${source}_${campaign}`);
return NextResponse.redirect(finalUrl.toString());
}
// Desktop visitor -> Redirect to app page with QR code & deep link info
const desktopUrl = new URL(`/apps/${app.slug}`, req.url);
desktopUrl.searchParams.set('src', source);
desktopUrl.searchParams.set('tool', tool ? tool.slug : '');
desktopUrl.searchParams.set('promo', promo);
return NextResponse.redirect(desktopUrl.toString());
}
+43
View File
@@ -0,0 +1,43 @@
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import { getSiteConfig } from '@/lib/config/loader';
import { Navbar } from '@/components/ui/Navbar';
import { Footer } from '@/components/ui/Footer';
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
export async function generateMetadata(): Promise<Metadata> {
const config = getSiteConfig();
return {
title: {
default: config.brand.name + ' | AI Photo Tools',
template: config.seo.titleTemplate || `%s | ${config.brand.name}`,
},
description: typeof config.brand.tagline === 'string' ? config.brand.tagline : config.brand.tagline.en,
metadataBase: new URL(config.seo.siteUrl || 'http://localhost:3000'),
openGraph: {
type: 'website',
siteName: config.brand.name,
images: [{ url: config.seo.defaultOgImage || '/brand/og-default.png' }],
},
};
}
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const config = getSiteConfig();
return (
<html lang="en" className={inter.variable}>
<body className="min-h-screen flex flex-col antialiased selection:bg-blue-500 selection:text-white">
<Navbar config={config} currentLocale="en" />
<main className="flex-1">{children}</main>
<Footer config={config} currentLocale="en" />
</body>
</html>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { getPageConfig, getAllTools, getAllApps, getAllCategories, getToolById, getAppById } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const revalidate = 600; // ISR 10 minutes fallback per PRD §4.2
export default function HomePage() {
const page = getPageConfig('home');
if (!page) notFound();
const tools = getAllTools();
const apps = getAllApps();
const categories = getAllCategories();
// Find hero tool and variants
const heroTool = getToolById('face.blemish.remove') || tools[0];
const heroApp = heroTool ? getAppById(heroTool.homeApp) : null;
const endpoint = heroTool?.tryIt?.endpointRef?.id ? getEndpointById(heroTool.tryIt.endpointRef.id) : undefined;
const variants = endpoint?.variants || [];
const context = {
page,
tools,
apps,
categories,
tool: heroTool,
homeApp: heroApp,
variants,
locale: 'en',
};
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { Metadata } from 'next';
import { getPageConfig, getAllApps } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const metadata: Metadata = {
title: 'Pricing & In-App Purchases | Ekagni PhotoAI',
description: 'Understand how free web tries and app-specific pricing work. No cross-app subscriptions or web wallets.',
};
export default function PricingPage() {
const page = getPageConfig('pricing');
if (!page) notFound();
const apps = getAllApps();
const context = { page, apps, locale: 'en' };
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { getPageConfig } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const metadata: Metadata = {
title: 'Privacy Policy | Ekagni PhotoAI',
description: 'Full privacy policy: transient image handling, zero retention, and GDPR compliance.',
};
export default function PrivacyPage() {
const page = getPageConfig('privacy');
if (!page) notFound();
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={{ page, locale: 'en' }} />
))}
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { MetadataRoute } from 'next';
export default function robots(): MetadataRoute.Robots {
const baseUrl = process.env.SITE_URL || 'http://localhost:3000';
return {
rules: {
userAgent: '*',
allow: '/',
disallow: ['/api/', '/go/', '/catalog-manager'],
},
sitemap: `${baseUrl}/sitemap.xml`,
};
}
+38
View File
@@ -0,0 +1,38 @@
import { MetadataRoute } from 'next';
import { getAllTools, getAllApps } from '@/lib/config/loader';
export default function sitemap(): MetadataRoute.Sitemap {
const baseUrl = process.env.SITE_URL || 'http://localhost:3000';
const now = new Date();
const staticPages = [
'',
'/tools',
'/apps',
'/pricing',
'/trust',
'/privacy',
'/terms',
].map((route) => ({
url: `${baseUrl}${route}`,
lastModified: now,
changeFrequency: 'daily' as const,
priority: route === '' ? 1.0 : 0.8,
}));
const tools = getAllTools().map((t) => ({
url: `${baseUrl}/tools/${t.slug}`,
lastModified: now,
changeFrequency: 'weekly' as const,
priority: 0.9,
}));
const apps = getAllApps().map((a) => ({
url: `${baseUrl}/apps/${a.slug}`,
lastModified: now,
changeFrequency: 'weekly' as const,
priority: 0.8,
}));
return [...staticPages, ...tools, ...apps];
}
+22
View File
@@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { getPageConfig } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const metadata: Metadata = {
title: 'Terms of Service | Ekagni PhotoAI',
description: 'Terms of Service for online web tools and mobile app handoff.',
};
export default function TermsPage() {
const page = getPageConfig('terms');
if (!page) notFound();
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={{ page, locale: 'en' }} />
))}
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getAllTools, getToolBySlug, getAppById, getTemplate } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { resolveLocalised } from '@/types';
interface ToolPageProps {
params: { slug: string };
}
export async function generateStaticParams() {
const tools = getAllTools();
return tools.map((t) => ({ slug: t.slug }));
}
export async function generateMetadata({ params }: ToolPageProps): Promise<Metadata> {
const tool = getToolBySlug(params.slug);
if (!tool) return {};
const name = resolveLocalised(tool.name, 'en');
const summary = resolveLocalised(tool.summary, 'en');
return {
title: tool.seo?.title || `${name} Free Online | Ekagni PhotoAI`,
description: tool.seo?.description || summary,
alternates: {
canonical: `/tools/${tool.slug}`,
},
openGraph: {
title: `${name} Free Online`,
description: summary,
type: 'website',
},
};
}
export default function ToolDetailPage({ params }: ToolPageProps) {
const tool = getToolBySlug(params.slug);
if (!tool) notFound();
const homeApp = getAppById(tool.homeApp);
const template = getTemplate('tool') || { sections: [] };
const endpoint = tool.tryIt?.endpointRef?.id ? getEndpointById(tool.tryIt.endpointRef.id) : undefined;
const variants = endpoint?.variants || [];
// Related tools
const allTools = getAllTools();
const relatedTools = (tool.related || [])
.map((rId) => allTools.find((t) => t.id === rId))
.filter(Boolean) as any[];
const context = {
tool,
homeApp,
variants,
tools: allTools,
relatedTools,
locale: 'en',
};
// Structured Data (JSON-LD) per PRD §10 SEO-07
const structuredData = {
'@context': 'https://schema.org',
'@type': 'WebApplication',
name: resolveLocalised(tool.name, 'en'),
description: resolveLocalised(tool.summary, 'en'),
applicationCategory: 'MultimediaApplication',
operatingSystem: 'Any',
offers: {
'@type': 'Offer',
price: '0',
priceCurrency: 'USD',
},
};
return (
<div>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
/>
{template.sections.map((section: any) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
);
}
+34
View File
@@ -0,0 +1,34 @@
import { Metadata } from 'next';
import { getPageConfig, getAllTools, getAllApps, getAllCategories } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const metadata: Metadata = {
title: 'All AI Photo Tools | Free Online Directory',
description: 'Browse all free online AI photo editing tools: blemish remover, background cutout, photo enhancer, old photo restorer, and anime avatars.',
};
export default function ToolsIndexPage() {
const page = getPageConfig('tools');
if (!page) notFound();
const tools = getAllTools();
const apps = getAllApps();
const categories = getAllCategories();
const context = {
page,
tools,
apps,
categories,
locale: 'en',
};
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { getPageConfig } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
export const metadata: Metadata = {
title: 'Trust & Biometric Privacy Safeguards | Ekagni PhotoAI',
description: 'Our four privacy pillars: Zero-storage, RAM processing, no model training on user photos, and strict biometric protections.',
};
export default function TrustPage() {
const page = getPageConfig('trust');
if (!page) notFound();
return (
<div>
{page.sections.map((section) => (
<SectionRenderer key={section.id} section={section} context={{ page, locale: 'en' }} />
))}
</div>
);
}
+105
View File
@@ -0,0 +1,105 @@
import React from 'react';
import Link from 'next/link';
import { Smartphone, Star, Check, ArrowRight, ShieldCheck } from 'lucide-react';
import { AppItem, resolveLocalised } from '@/types';
interface AppCardsSectionProps {
title?: any;
subtitle?: any;
apps?: AppItem[];
layout?: 'compact' | 'detailed';
showRating?: boolean;
locale?: string;
}
export function AppCardsSection({
title,
subtitle,
apps = [],
layout = 'compact',
showRating = true,
locale = 'en',
}: AppCardsSectionProps) {
return (
<section className="py-12 lg:py-16 bg-slate-50/50 dark:bg-slate-950/50">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{(title || subtitle) && (
<div className="text-center max-w-3xl mx-auto mb-12 space-y-3">
{title && (
<h2 className="text-3xl sm:text-4xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(title, locale)}
</h2>
)}
{subtitle && (
<p className="text-base text-slate-600 dark:text-slate-400">
{resolveLocalised(subtitle, locale)}
</p>
)}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{apps.map((app) => (
<div
key={app.id}
className="bg-white dark:bg-slate-900 rounded-3xl p-6 border border-slate-200 dark:border-slate-800 shadow-sm hover:shadow-xl transition-all flex flex-col justify-between"
>
<div>
{/* Header: Icon & Rating */}
<div className="flex items-center justify-between mb-4">
<div className="w-12 h-12 rounded-2xl bg-gradient-to-tr from-blue-600 to-indigo-600 flex items-center justify-center text-white shadow-md shadow-blue-500/20">
<Smartphone className="w-6 h-6" />
</div>
{showRating && (
<div className="flex items-center space-x-1 bg-amber-50 dark:bg-amber-950/50 border border-amber-200 dark:border-amber-800 px-2.5 py-1 rounded-full text-xs font-semibold text-amber-700 dark:text-amber-400">
<Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
<span>{app.rating.value}</span>
</div>
)}
</div>
<h3 className="text-xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(app.name, locale)}
</h3>
<p className="mt-1 text-xs text-blue-600 dark:text-blue-400 font-medium">
{resolveLocalised(app.tagline, locale)}
</p>
<p className="mt-3 text-xs text-slate-600 dark:text-slate-400 leading-relaxed line-clamp-3">
{resolveLocalised(app.description, locale)}
</p>
{/* Features Checklist */}
{app.features && app.features.length > 0 && (
<div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800 space-y-2">
{app.features.slice(0, 3).map((feat, idx) => (
<div key={idx} className="flex items-start space-x-2 text-xs text-slate-600 dark:text-slate-300">
<Check className="w-3.5 h-3.5 text-emerald-500 shrink-0 mt-0.5" />
<span className="line-clamp-1">{feat}</span>
</div>
))}
</div>
)}
</div>
<div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-800 space-y-3">
{/* Mandatory Disclaimer (PRD §1.2, §9 APP-10) */}
<p className="text-[10px] text-slate-400 dark:text-slate-500 italic text-center">
{resolveLocalised(app.creditsNote, locale, 'Credits and purchases are specific to this app.')}
</p>
<Link
href={`/apps/${app.slug}`}
className="w-full inline-flex items-center justify-center space-x-2 py-3 rounded-xl text-xs font-semibold text-white bg-slate-900 dark:bg-white dark:text-slate-900 hover:bg-blue-600 dark:hover:bg-blue-500 dark:hover:text-white transition-all shadow-md"
>
<span>Get App & Bonus</span>
<ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
))}
</div>
</div>
</section>
);
}
@@ -0,0 +1,145 @@
'use client';
import React, { useState, useEffect } from 'react';
import QRCode from 'qrcode';
import { Smartphone, QrCode, Copy, Check, Gift } from 'lucide-react';
import { AppItem, ToolItem, resolveLocalised } from '@/types';
interface AppHandoffSectionProps {
app?: AppItem;
tool?: ToolItem | null;
locale?: string;
showBonus?: boolean;
showQr?: boolean;
}
export function AppHandoffSection({
app,
tool,
locale = 'en',
showBonus = true,
showQr = true,
}: AppHandoffSectionProps) {
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [copied, setCopied] = useState(false);
if (!app) return null;
const bonusCode = app.welcomeBonus?.code || 'TRYWEB50';
const targetUrl = tool
? `http://localhost:3000/go/${tool.slug}/${app.slug}?promo=${bonusCode}`
: `http://localhost:3000/apps/${app.slug}?promo=${bonusCode}`;
useEffect(() => {
if (showQr) {
QRCode.toDataURL(targetUrl, {
width: 180,
margin: 1,
color: {
dark: '#0f172a',
light: '#ffffff',
},
})
.then(setQrDataUrl)
.catch(console.error);
}
}, [targetUrl, showQr]);
const copyPromo = () => {
navigator.clipboard.writeText(bonusCode);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<section className="py-12 bg-gradient-to-br from-blue-50/50 via-white to-teal-50/50 dark:from-slate-900 dark:via-slate-900 dark:to-slate-950 border-y border-slate-200 dark:border-slate-800">
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="bg-white dark:bg-slate-900 rounded-3xl p-6 sm:p-10 border border-slate-200 dark:border-slate-800 shadow-xl flex flex-col md:flex-row items-center justify-between gap-8">
{/* Left Column: Copy & Store CTA */}
<div className="space-y-4 max-w-xl">
<div className="inline-flex items-center space-x-2 px-3 py-1 rounded-full bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400 text-xs font-semibold">
<Smartphone className="w-3.5 h-3.5" />
<span>Native iOS & Android App</span>
</div>
<h3 className="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white">
{tool
? `Continue in ${resolveLocalised(app.name, locale)} with 4K Lossless Export`
: `Download ${resolveLocalised(app.name, locale)}`}
</h3>
<p className="text-sm text-slate-600 dark:text-slate-400 leading-relaxed">
Experience zero-latency hardware accelerated neural processing, batch photoshoot enhancement, and professional fine-tuning sliders.
</p>
{/* Welcome Bonus Promo Banner */}
{showBonus && (
<div className="p-4 rounded-2xl bg-amber-50 dark:bg-amber-950/40 border border-amber-200 dark:border-amber-800/60 flex items-center justify-between">
<div className="flex items-center space-x-3">
<div className="w-10 h-10 rounded-xl bg-amber-100 dark:bg-amber-900/60 flex items-center justify-center text-amber-600">
<Gift className="w-5 h-5" />
</div>
<div>
<p className="text-xs font-bold text-slate-900 dark:text-white">
{app.welcomeBonus?.title || '50 Free HD Export Credits'}
</p>
<p className="text-[11px] text-slate-500 dark:text-slate-400">
Claim promo code on first launch
</p>
</div>
</div>
<button
onClick={copyPromo}
className="inline-flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-xs font-mono font-bold bg-white dark:bg-slate-900 border border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-950 transition-colors"
>
{copied ? <Check className="w-3.5 h-3.5 text-emerald-600" /> : <Copy className="w-3.5 h-3.5" />}
<span>{bonusCode}</span>
</button>
</div>
)}
{/* Store Download Buttons */}
<div className="flex flex-wrap items-center gap-3 pt-2">
<a
href={app.stores.android?.url || '#'}
target="_blank"
rel="noreferrer"
className="px-5 py-2.5 rounded-xl text-xs font-semibold text-white bg-slate-900 hover:bg-slate-800 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-100 shadow-md transition-all flex items-center space-x-2"
>
<span>Google Play</span>
</a>
<a
href={app.stores.ios?.url || '#'}
target="_blank"
rel="noreferrer"
className="px-5 py-2.5 rounded-xl text-xs font-semibold text-white bg-slate-900 hover:bg-slate-800 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-100 shadow-md transition-all flex items-center space-x-2"
>
<span>Apple App Store</span>
</a>
</div>
{/* Disclaimer */}
<p className="text-[11px] text-slate-400 dark:text-slate-500 italic">
{resolveLocalised(app.creditsNote, locale, 'Credits and in-app purchases are specific to this app.')}
</p>
</div>
{/* Right Column: QR Code Handoff (PRD §9 APP-05) */}
{showQr && qrDataUrl && (
<div className="text-center p-6 rounded-2xl bg-slate-50 dark:bg-slate-950/60 border border-slate-200 dark:border-slate-800 shrink-0">
<div className="p-2 bg-white rounded-xl shadow-inner inline-block">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={qrDataUrl} alt="Scan QR code to install app" className="w-36 h-36" />
</div>
<div className="mt-3 flex items-center justify-center space-x-1.5 text-xs text-slate-600 dark:text-slate-400 font-medium">
<QrCode className="w-4 h-4 text-blue-600" />
<span>Scan with phone camera</span>
</div>
</div>
)}
</div>
</div>
</section>
);
}
@@ -0,0 +1,125 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { HelpCircle, CheckCircle2, ArrowRight, Sparkles, Smartphone } from 'lucide-react';
import { AppItem, resolveLocalised } from '@/types';
interface AppPickerSectionProps {
title?: any;
subtitle?: any;
apps?: AppItem[];
locale?: string;
}
export function AppPickerSection({
title,
subtitle,
apps = [],
locale = 'en',
}: AppPickerSectionProps) {
const [photoGoal, setPhotoGoal] = useState<string>('portrait');
const [step, setStep] = useState<number>(1);
const goalOptions = [
{
id: 'portrait',
title: 'Portraits, Selfies & Skin Beauty',
desc: 'Acne, blemish removal, teeth whitening, eye redness',
appSlug: 'portrait-app',
},
{
id: 'restoration',
title: 'Blurry, Damaged or Old Photos',
desc: 'Restoring old photos, fixing scratches, sharpening faces',
appSlug: 'photo-enhancer-pro',
},
{
id: 'cutout',
title: 'Background Cutout & Object Removal',
desc: 'Transparent PNGs, product photography, erasing strangers',
appSlug: 'bg-cleaner-app',
},
{
id: 'art',
title: 'Anime, Cartoon & Vintage Film Art',
desc: 'Cartoon avatars, Polaroid aesthetic, anime stylization',
appSlug: 'art-studio-app',
},
];
const matchedGoal = goalOptions.find((g) => g.id === photoGoal) || goalOptions[0];
const recommendedApp = apps.find((a) => a.slug === matchedGoal.appSlug) || apps[0];
return (
<section className="py-12 lg:py-16 bg-white dark:bg-slate-900 border-t border-slate-200 dark:border-slate-800">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center space-y-3 mb-10">
<div className="inline-flex items-center space-x-2 px-3 py-1 rounded-full bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400 text-xs font-semibold">
<HelpCircle className="w-3.5 h-3.5" />
<span>Interactive App Matcher</span>
</div>
<h2 className="text-3xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(title, locale, 'Not Sure Which App You Need?')}
</h2>
<p className="text-sm text-slate-600 dark:text-slate-400">
{resolveLocalised(subtitle, locale, 'Select your photo editing goal to find your tailored mobile tool.')}
</p>
</div>
<div className="bg-slate-50 dark:bg-slate-950 rounded-3xl p-6 sm:p-8 border border-slate-200 dark:border-slate-800 shadow-md space-y-8">
<div>
<label className="block text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-4">
Step 1: What would you like to edit?
</label>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{goalOptions.map((opt) => (
<button
key={opt.id}
onClick={() => setPhotoGoal(opt.id)}
className={`p-4 rounded-2xl border text-left transition-all ${
photoGoal === opt.id
? 'border-blue-600 bg-white dark:bg-slate-900 shadow-md ring-2 ring-blue-500/20'
: 'border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700 bg-white/60 dark:bg-slate-900/60'
}`}
>
<p className="font-semibold text-sm text-slate-900 dark:text-white">
{opt.title}
</p>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
{opt.desc}
</p>
</button>
))}
</div>
</div>
{/* Recommended Result */}
{recommendedApp && (
<div className="pt-6 border-t border-slate-200 dark:border-slate-800 flex flex-col sm:flex-row items-center justify-between gap-6 bg-gradient-to-r from-blue-50/50 to-teal-50/50 dark:from-blue-950/20 dark:to-teal-950/20 p-6 rounded-2xl">
<div className="space-y-1">
<span className="text-[11px] font-bold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
Recommended Match:
</span>
<h4 className="text-xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(recommendedApp.name, locale)}
</h4>
<p className="text-xs text-slate-600 dark:text-slate-400">
{resolveLocalised(recommendedApp.tagline, locale)}
</p>
</div>
<Link
href={`/apps/${recommendedApp.slug}`}
className="shrink-0 inline-flex items-center space-x-2 px-5 py-3 rounded-xl text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 shadow-md shadow-blue-500/20 transition-all hover:scale-105"
>
<span>View App & Get 50 Bonus Credits</span>
<ArrowRight className="w-4 h-4" />
</Link>
</div>
)}
</div>
</div>
</section>
);
}
@@ -0,0 +1,62 @@
import React from 'react';
import Link from 'next/link';
import { Globe, Smartphone, ArrowRight } from 'lucide-react';
import { ToolItem, AppItem, resolveLocalised } from '@/types';
interface AvailabilitySectionProps {
tool?: ToolItem;
homeApp?: AppItem | null;
locale?: string;
}
export function AvailabilitySection({ tool, homeApp, locale = 'en' }: AvailabilitySectionProps) {
if (!tool) return null;
return (
<section className="py-8 bg-white dark:bg-slate-900 border-t border-slate-200 dark:border-slate-800">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<h4 className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-4 text-center">
Platform Availability for {resolveLocalised(tool.name, locale)}
</h4>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* Web Try */}
<div className="p-4 rounded-2xl border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
<div className="flex items-center space-x-3">
<div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-950 text-blue-600 flex items-center justify-center">
<Globe className="w-5 h-5" />
</div>
<div>
<p className="text-sm font-bold text-slate-900 dark:text-white">Web Browser</p>
<p className="text-xs text-slate-500 dark:text-slate-400">Free online try • Standard HD</p>
</div>
</div>
<span className="text-xs font-semibold text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-950/60 px-2.5 py-1 rounded-md">
Live
</span>
</div>
{/* Home App */}
{homeApp && (
<Link
href={`/go/${tool.slug}/${homeApp.slug}`}
className="p-4 rounded-2xl border border-blue-200 dark:border-blue-900 bg-blue-50/40 dark:bg-blue-950/30 hover:border-blue-500 transition-all flex items-center justify-between group"
>
<div className="flex items-center space-x-3">
<div className="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shadow-md">
<Smartphone className="w-5 h-5" />
</div>
<div>
<p className="text-sm font-bold text-slate-900 dark:text-white group-hover:text-blue-600 transition-colors">
{resolveLocalised(homeApp.name, locale)}
</p>
<p className="text-xs text-blue-600 dark:text-blue-400">Home App • 4K Lossless & Batch</p>
</div>
</div>
<ArrowRight className="w-4 h-4 text-blue-600 group-hover:translate-x-1 transition-transform" />
</Link>
)}
</div>
</div>
</section>
);
}
@@ -0,0 +1,57 @@
import React from 'react';
import { resolveLocalised } from '@/types';
import { BeforeAfterSlider } from '../ui/BeforeAfterSlider';
interface BeforeAfterSectionProps {
title?: any;
subtitle?: any;
items?: Array<{
before: string;
after: string;
alt?: any;
caption?: string;
}>;
locale?: string;
}
export function BeforeAfterSection({
title,
subtitle,
items = [],
locale = 'en',
}: BeforeAfterSectionProps) {
if (!items || items.length === 0) return null;
return (
<section className="py-12 lg:py-16">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{(title || subtitle) && (
<div className="text-center max-w-3xl mx-auto mb-10 space-y-3">
{title && (
<h2 className="text-3xl sm:text-4xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(title, locale)}
</h2>
)}
{subtitle && (
<p className="text-base text-slate-600 dark:text-slate-400">
{resolveLocalised(subtitle, locale)}
</p>
)}
</div>
)}
<div className={`grid grid-cols-1 ${items.length > 1 ? 'md:grid-cols-2' : 'max-w-2xl mx-auto'} gap-8`}>
{items.map((item, idx) => (
<div key={idx} className="space-y-2">
<BeforeAfterSlider
beforeUrl={item.before}
afterUrl={item.after}
caption={item.caption}
/>
</div>
))}
</div>
</div>
</section>
);
}
@@ -0,0 +1,66 @@
import React from 'react';
import Link from 'next/link';
import { ArrowRight } from 'lucide-react';
import { resolveLocalised } from '@/types';
interface CtaBannerSectionProps {
title?: any;
subtitle?: any;
primaryCta?: {
label: any;
href: string;
};
secondaryCta?: {
label: any;
href: string;
};
locale?: string;
}
export function CtaBannerSection({
title,
subtitle,
primaryCta,
secondaryCta,
locale = 'en',
}: CtaBannerSectionProps) {
return (
<section className="py-12 lg:py-16">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="rounded-3xl bg-gradient-to-r from-blue-600 via-indigo-600 to-teal-600 p-8 sm:p-12 text-center text-white shadow-2xl relative overflow-hidden">
<div className="relative z-10 max-w-2xl mx-auto space-y-4">
{title && (
<h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
{resolveLocalised(title, locale)}
</h2>
)}
{subtitle && (
<p className="text-base text-blue-100">
{resolveLocalised(subtitle, locale)}
</p>
)}
<div className="pt-4 flex flex-wrap items-center justify-center gap-4">
{primaryCta && (
<Link
href={primaryCta.href}
className="px-6 py-3.5 rounded-xl text-sm font-semibold text-slate-900 bg-white hover:bg-slate-100 shadow-md transition-all hover:scale-105 active:scale-95"
>
{resolveLocalised(primaryCta.label, locale)}
</Link>
)}
{secondaryCta && (
<Link
href={secondaryCta.href}
className="px-6 py-3.5 rounded-xl text-sm font-semibold text-white border border-white/40 hover:bg-white/10 transition-colors"
>
{resolveLocalised(secondaryCta.label, locale)}
</Link>
)}
</div>
</div>
</div>
</div>
</section>
);
}
+66
View File
@@ -0,0 +1,66 @@
'use client';
import React, { useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { resolveLocalised } from '@/types';
interface FaqSectionProps {
title?: any;
items?: Array<{
q: string;
a: string;
}>;
locale?: string;
}
export function FaqSection({
title,
items = [],
locale = 'en',
}: FaqSectionProps) {
const [openIndex, setOpenIndex] = useState<number | null>(0);
if (!items || items.length === 0) return null;
return (
<section className="py-12 lg:py-16">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
{title && (
<h2 className="text-3xl font-bold text-slate-900 dark:text-white mb-8 text-center">
{resolveLocalised(title, locale)}
</h2>
)}
<div className="space-y-3">
{items.map((item, idx) => {
const isOpen = openIndex === idx;
return (
<div
key={idx}
className="rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 overflow-hidden shadow-sm transition-all"
>
<button
onClick={() => setOpenIndex(isOpen ? null : idx)}
className="w-full p-5 text-left flex items-center justify-between gap-4 font-semibold text-slate-900 dark:text-white hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
>
<span className="text-base">{item.q}</span>
<ChevronDown
className={`w-5 h-5 text-slate-400 shrink-0 transition-transform duration-200 ${
isOpen ? 'rotate-180 text-blue-600' : ''
}`}
/>
</button>
{isOpen && (
<div className="px-5 pb-5 text-sm text-slate-600 dark:text-slate-400 leading-relaxed border-t border-slate-100 dark:border-slate-800/60 pt-3">
{item.a}
</div>
)}
</div>
);
})}
</div>
</div>
</section>
);
}
@@ -0,0 +1,45 @@
import React from 'react';
import { Check } from 'lucide-react';
import { resolveLocalised } from '@/types';
interface FeatureListSectionProps {
title?: any;
items?: string[];
locale?: string;
}
export function FeatureListSection({
title,
items = [],
locale = 'en',
}: FeatureListSectionProps) {
if (!items || items.length === 0) return null;
return (
<section className="py-12 bg-white dark:bg-slate-900">
<div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
{title && (
<h3 className="text-2xl font-bold text-slate-900 dark:text-white mb-8 text-center">
{resolveLocalised(title, locale)}
</h3>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{items.map((feature, idx) => (
<div
key={idx}
className="flex items-start space-x-3 p-4 rounded-2xl bg-slate-50 dark:bg-slate-950/50 border border-slate-200 dark:border-slate-800"
>
<div className="w-5 h-5 rounded-full bg-emerald-100 dark:bg-emerald-950/60 text-emerald-600 flex items-center justify-center shrink-0 mt-0.5">
<Check className="w-3 h-3" />
</div>
<span className="text-sm font-medium text-slate-800 dark:text-slate-200">
{feature}
</span>
</div>
))}
</div>
</div>
</section>
);
}
+111
View File
@@ -0,0 +1,111 @@
import React from 'react';
import Link from 'next/link';
import { Sparkles, ArrowRight, Smartphone } from 'lucide-react';
import { resolveLocalised, ToolItem, AppItem, VariantSpec } from '@/types';
import { TryItWidget } from './TryItWidget';
interface HeroSectionProps {
title?: any;
subtitle?: any;
variant?: string;
badge?: any;
tryIt?: {
toolRef: string;
};
tool?: ToolItem | null;
homeApp?: AppItem | null;
variants?: VariantSpec[];
locale?: string;
}
export function HeroSection({
title,
subtitle,
variant = 'centered',
badge,
tool,
homeApp,
variants = [],
locale = 'en',
}: HeroSectionProps) {
const resolvedTitle = resolveLocalised(title, locale);
const resolvedSubtitle = resolveLocalised(subtitle, locale);
const resolvedBadge = resolveLocalised(badge, locale);
if (variant === 'tryit' && tool) {
return (
<section className="relative overflow-hidden pt-8 pb-16 lg:pt-14 lg:pb-24">
{/* Ambient Gradient Background Glow */}
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-full max-w-7xl h-96 bg-gradient-to-tr from-blue-500/10 via-teal-500/10 to-indigo-500/10 blur-3xl pointer-events-none -z-10" />
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center max-w-3xl mx-auto space-y-4 mb-10">
{resolvedBadge && (
<div className="inline-flex items-center space-x-2 px-3.5 py-1.5 rounded-full bg-blue-50 dark:bg-blue-950/60 border border-blue-200 dark:border-blue-800 text-xs font-semibold text-blue-700 dark:text-blue-300">
<Sparkles className="w-3.5 h-3.5 text-blue-500" />
<span>{resolvedBadge}</span>
</div>
)}
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold text-slate-900 dark:text-white tracking-tight leading-tight">
{resolvedTitle}
</h1>
<p className="text-lg text-slate-600 dark:text-slate-300 leading-relaxed">
{resolvedSubtitle}
</p>
</div>
{/* Embedded Interactive Try-It Widget */}
<div className="max-w-4xl mx-auto">
<TryItWidget
tool={tool}
homeApp={homeApp}
variants={variants}
locale={locale}
/>
</div>
</div>
</section>
);
}
// Centered or Standard Hero
return (
<section className="relative overflow-hidden pt-12 pb-16 lg:pt-20 lg:pb-24 text-center">
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-full max-w-7xl h-80 bg-gradient-to-b from-blue-500/10 to-transparent blur-3xl pointer-events-none -z-10" />
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6">
{resolvedBadge && (
<div className="inline-flex items-center space-x-2 px-3.5 py-1.5 rounded-full bg-blue-50 dark:bg-blue-950/60 border border-blue-200 dark:border-blue-800 text-xs font-semibold text-blue-700 dark:text-blue-300">
<Sparkles className="w-3.5 h-3.5" />
<span>{resolvedBadge}</span>
</div>
)}
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold text-slate-900 dark:text-white tracking-tight leading-tight">
{resolvedTitle}
</h1>
<p className="text-lg sm:text-xl text-slate-600 dark:text-slate-300 max-w-2xl mx-auto">
{resolvedSubtitle}
</p>
<div className="flex flex-wrap items-center justify-center gap-4 pt-4">
<Link
href="/tools"
className="inline-flex items-center space-x-2 px-6 py-3.5 rounded-xl font-semibold text-white bg-blue-600 hover:bg-blue-700 shadow-md shadow-blue-500/20 transition-all hover:scale-105 active:scale-95"
>
<span>Explore All Free Tools</span>
<ArrowRight className="w-4 h-4" />
</Link>
<Link
href="/apps"
className="inline-flex items-center space-x-2 px-6 py-3.5 rounded-xl font-semibold text-slate-700 dark:text-slate-200 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors"
>
<Smartphone className="w-4 h-4 text-slate-500" />
<span>Mobile Apps Suite</span>
</Link>
</div>
</div>
</section>
);
}
+31
View File
@@ -0,0 +1,31 @@
import React from 'react';
import { Info, AlertTriangle, CheckCircle2 } from 'lucide-react';
import { resolveLocalised } from '@/types';
interface NoticeSectionProps {
text?: any;
level?: 'info' | 'warning' | 'success';
locale?: string;
}
export function NoticeSection({ text, level = 'info', locale = 'en' }: NoticeSectionProps) {
const resolvedText = resolveLocalised(text, locale);
if (!resolvedText) return null;
const styles = {
info: 'bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900',
warning: 'bg-amber-50 text-amber-800 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900',
success: 'bg-emerald-50 text-emerald-800 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-900',
};
const Icon = level === 'warning' ? AlertTriangle : level === 'success' ? CheckCircle2 : Info;
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6 my-4">
<div className={`p-4 rounded-2xl border flex items-center space-x-3 text-xs font-medium ${styles[level]}`}>
<Icon className="w-4 h-4 shrink-0" />
<span>{resolvedText}</span>
</div>
</div>
);
}
@@ -0,0 +1,51 @@
import React from 'react';
import { ShieldCheck, Info } from 'lucide-react';
import { resolveLocalised } from '@/types';
interface PricingExplainerSectionProps {
title?: any;
notes?: string[];
locale?: string;
}
export function PricingExplainerSection({
title,
notes = [],
locale = 'en',
}: PricingExplainerSectionProps) {
return (
<section className="py-12 bg-white dark:bg-slate-900">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="bg-gradient-to-br from-blue-50/60 to-slate-50 dark:from-blue-950/30 dark:to-slate-950 rounded-3xl p-6 sm:p-8 border border-blue-100 dark:border-blue-900/60 space-y-6">
<div className="flex items-center space-x-3">
<div className="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center">
<ShieldCheck className="w-5 h-5" />
</div>
<div>
<h3 className="text-xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(title, locale, 'How App Pricing & Credits Work')}
</h3>
<p className="text-xs text-slate-500 dark:text-slate-400">
Transparent and simple: no surprise auto-renewing web subscriptions.
</p>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{notes.map((note, idx) => (
<div
key={idx}
className="flex items-start space-x-3 p-4 rounded-2xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800"
>
<Info className="w-4 h-4 text-blue-600 shrink-0 mt-0.5" />
<span className="text-xs text-slate-700 dark:text-slate-300 leading-relaxed">
{note}
</span>
</div>
))}
</div>
</div>
</div>
</section>
);
}
@@ -0,0 +1,64 @@
import React from 'react';
import Link from 'next/link';
import { ArrowRight, Wand2 } from 'lucide-react';
import { ToolItem, resolveLocalised } from '@/types';
interface RelatedToolsSectionProps {
tools?: ToolItem[];
locale?: string;
}
export function RelatedToolsSection({ tools = [], locale = 'en' }: RelatedToolsSectionProps) {
if (!tools || tools.length === 0) return null;
return (
<section className="py-12 bg-slate-50/50 dark:bg-slate-950/40 border-t border-slate-200 dark:border-slate-800">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between mb-8">
<div>
<h3 className="text-2xl font-bold text-slate-900 dark:text-white">
Related AI Tools
</h3>
<p className="text-xs text-slate-500 dark:text-slate-400">
Explore more tools to enhance your photo editing workflow
</p>
</div>
<Link
href="/tools"
className="text-xs font-semibold text-blue-600 dark:text-blue-400 hover:underline flex items-center space-x-1"
>
<span>View all tools</span>
<ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
{tools.map((tool) => (
<Link
key={tool.id}
href={`/tools/${tool.slug}`}
className="group p-5 rounded-2xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-sm hover:shadow-md hover:border-blue-500 transition-all flex flex-col justify-between"
>
<div>
<div className="w-8 h-8 rounded-lg bg-blue-50 dark:bg-blue-950 text-blue-600 flex items-center justify-center mb-3 group-hover:scale-110 transition-transform">
<Wand2 className="w-4 h-4" />
</div>
<h4 className="font-bold text-slate-900 dark:text-white text-sm group-hover:text-blue-600 transition-colors">
{resolveLocalised(tool.name, locale)}
</h4>
<p className="mt-1 text-xs text-slate-500 dark:text-slate-400 line-clamp-2">
{resolveLocalised(tool.summary, locale)}
</p>
</div>
<div className="mt-4 pt-3 border-t border-slate-100 dark:border-slate-800 text-xs font-medium text-blue-600 dark:text-blue-400 flex items-center justify-between">
<span>Try free</span>
<ArrowRight className="w-3 h-3 group-hover:translate-x-1 transition-transform" />
</div>
</Link>
))}
</div>
</div>
</section>
);
}
@@ -0,0 +1,47 @@
import React from 'react';
interface RichTextSectionProps {
markdown?: string;
}
export function RichTextSection({ markdown = '' }: RichTextSectionProps) {
// Simple, safe markdown to HTML parser for headers, lists, and paragraphs
const renderFormatted = (text: string) => {
const lines = text.split('\n');
return lines.map((line, idx) => {
if (line.startsWith('### ')) {
return (
<h3 key={idx} className="text-xl font-bold text-slate-900 dark:text-white mt-6 mb-3">
{line.replace('### ', '')}
</h3>
);
}
if (line.startsWith('1. ') || line.startsWith('2. ') || line.startsWith('3. ') || line.startsWith('4. ')) {
return (
<div key={idx} className="flex items-start space-x-2 my-2 text-sm text-slate-700 dark:text-slate-300">
<span className="font-bold text-blue-600">{line.slice(0, 3)}</span>
<span>{line.slice(3)}</span>
</div>
);
}
if (line.trim().length === 0) {
return <div key={idx} className="h-2" />;
}
return (
<p key={idx} className="text-sm text-slate-600 dark:text-slate-400 leading-relaxed my-2">
{line}
</p>
);
});
};
return (
<section className="py-12 bg-white dark:bg-slate-900">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="bg-slate-50 dark:bg-slate-950/60 rounded-3xl p-6 sm:p-10 border border-slate-200 dark:border-slate-800 shadow-sm">
{renderFormatted(markdown)}
</div>
</div>
</section>
);
}
+157
View File
@@ -0,0 +1,157 @@
import React from 'react';
import { SectionConfig, ToolItem, AppItem, CategoryItem, VariantSpec } from '@/types';
import { resolveBindings, isSectionVisible } from '@/lib/config/bindings';
import { HeroSection } from './HeroSection';
import { ToolGridSection } from './ToolGridSection';
import { TryItWidget } from './TryItWidget';
import { BeforeAfterSection } from './BeforeAfterSection';
import { AppCardsSection } from './AppCardsSection';
import { AppHandoffSection } from './AppHandoffSection';
import { AvailabilitySection } from './AvailabilitySection';
import { AppPickerSection } from './AppPickerSection';
import { StepsSection } from './StepsSection';
import { FeatureListSection } from './FeatureListSection';
import { FaqSection } from './FaqSection';
import { StatsSection } from './StatsSection';
import { PricingExplainerSection } from './PricingExplainerSection';
import { RelatedToolsSection } from './RelatedToolsSection';
import { RichTextSection } from './RichTextSection';
import { CtaBannerSection } from './CtaBannerSection';
import { NoticeSection } from './NoticeSection';
interface SectionRendererProps {
section: SectionConfig;
context: {
site?: any;
page?: any;
tool?: ToolItem | null;
app?: AppItem | null;
homeApp?: AppItem | null;
tools?: ToolItem[];
apps?: AppItem[];
categories?: CategoryItem[];
variants?: VariantSpec[];
relatedTools?: ToolItem[];
locale?: string;
device?: 'mobile' | 'desktop';
};
}
export function SectionRenderer({ section, context }: SectionRendererProps) {
const locale = context.locale || 'en';
// Visibility Check (PRD §5.2, §5.3 CFG-09)
if (!isSectionVisible(section, { device: context.device, locale })) {
return null;
}
// Resolve bindings on section props (PRD §5.2)
const resolvedProps = resolveBindings(section.props || {}, context, locale);
switch (section.type) {
case 'hero':
return (
<HeroSection
{...resolvedProps}
variant={section.variant}
tool={context.tool}
homeApp={context.homeApp}
variants={context.variants}
locale={locale}
/>
);
case 'toolGrid':
return (
<ToolGridSection
{...resolvedProps}
tools={context.tools}
categories={context.categories}
apps={context.apps}
locale={locale}
/>
);
case 'tryItWidget':
if (!context.tool) return null;
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<TryItWidget
tool={context.tool}
homeApp={context.homeApp}
variants={context.variants}
locale={locale}
/>
</div>
);
case 'beforeAfter':
return <BeforeAfterSection {...resolvedProps} locale={locale} />;
case 'appCards':
return (
<AppCardsSection
{...resolvedProps}
apps={context.apps}
layout={section.variant as any}
locale={locale}
/>
);
case 'appHandoff':
if (!context.app && !context.homeApp) return null;
return (
<AppHandoffSection
{...resolvedProps}
app={(context.app || context.homeApp)!}
tool={context.tool}
locale={locale}
/>
);
case 'availability':
if (!context.tool) return null;
return (
<AvailabilitySection
tool={context.tool}
homeApp={context.homeApp}
locale={locale}
/>
);
case 'appPicker':
return <AppPickerSection {...resolvedProps} apps={context.apps} locale={locale} />;
case 'steps':
return <StepsSection {...resolvedProps} locale={locale} />;
case 'featureList':
return <FeatureListSection {...resolvedProps} locale={locale} />;
case 'faq':
return <FaqSection {...resolvedProps} locale={locale} />;
case 'stats':
return <StatsSection {...resolvedProps} />;
case 'pricingExplainer':
return <PricingExplainerSection {...resolvedProps} locale={locale} />;
case 'relatedTools':
return <RelatedToolsSection tools={context.relatedTools} locale={locale} />;
case 'richText':
return <RichTextSection {...resolvedProps} />;
case 'ctaBanner':
return <CtaBannerSection {...resolvedProps} locale={locale} />;
case 'notice':
return <NoticeSection {...resolvedProps} locale={locale} />;
default:
console.warn(`[SectionRenderer] Unknown section type: ${section.type}`);
return null;
}
}
+31
View File
@@ -0,0 +1,31 @@
import React from 'react';
interface StatsSectionProps {
items?: Array<{
value: string;
label: string;
}>;
}
export function StatsSection({ items = [] }: StatsSectionProps) {
if (!items || items.length === 0) return null;
return (
<section className="py-8 bg-slate-50/50 dark:bg-slate-950/40 border-y border-slate-200 dark:border-slate-800">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="grid grid-cols-2 md:grid-cols-4 gap-6 text-center">
{items.map((stat, idx) => (
<div key={idx} className="space-y-1">
<p className="text-3xl sm:text-4xl font-extrabold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-teal-500">
{stat.value}
</p>
<p className="text-xs font-medium text-slate-500 dark:text-slate-400">
{stat.label}
</p>
</div>
))}
</div>
</div>
</section>
);
}
+61
View File
@@ -0,0 +1,61 @@
import React from 'react';
import { resolveLocalised } from '@/types';
interface StepsSectionProps {
title?: any;
subtitle?: any;
items?: Array<{
title: any;
desc: any;
}>;
locale?: string;
}
export function StepsSection({
title,
subtitle,
items = [],
locale = 'en',
}: StepsSectionProps) {
if (!items || items.length === 0) return null;
return (
<section className="py-12 lg:py-16 bg-slate-50/50 dark:bg-slate-950/50">
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
{(title || subtitle) && (
<div className="text-center max-w-2xl mx-auto mb-12 space-y-3">
{title && (
<h2 className="text-3xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(title, locale)}
</h2>
)}
{subtitle && (
<p className="text-sm text-slate-600 dark:text-slate-400">
{resolveLocalised(subtitle, locale)}
</p>
)}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
{items.map((step, idx) => (
<div
key={idx}
className="relative bg-white dark:bg-slate-900 rounded-3xl p-6 sm:p-8 border border-slate-200 dark:border-slate-800 shadow-sm space-y-4"
>
<div className="w-10 h-10 rounded-xl bg-blue-600 text-white font-bold flex items-center justify-center text-base shadow-md shadow-blue-500/20">
{idx + 1}
</div>
<h3 className="text-lg font-bold text-slate-900 dark:text-white">
{resolveLocalised(step.title, locale)}
</h3>
<p className="text-xs text-slate-600 dark:text-slate-400 leading-relaxed">
{resolveLocalised(step.desc, locale)}
</p>
</div>
))}
</div>
</div>
</section>
);
}
+182
View File
@@ -0,0 +1,182 @@
'use client';
import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { Search, Sparkles, ArrowRight, Wand2, Scissors, Smile, Palette } from 'lucide-react';
import { ToolItem, CategoryItem, AppItem, resolveLocalised } from '@/types';
interface ToolGridSectionProps {
title?: any;
subtitle?: any;
tools?: ToolItem[];
categories?: CategoryItem[];
apps?: AppItem[];
showSearch?: boolean;
showCategoryFilter?: boolean;
limit?: number;
columns?: number;
locale?: string;
}
export function ToolGridSection({
title,
subtitle,
tools = [],
categories = [],
apps = [],
showSearch = false,
showCategoryFilter = false,
limit,
locale = 'en',
}: ToolGridSectionProps) {
const [selectedCategory, setSelectedCategory] = useState<string>('all');
const [searchQuery, setSearchQuery] = useState<string>('');
const appMap = useMemo(() => new Map(apps.map((a) => [a.id, a])), [apps]);
const filteredTools = useMemo(() => {
let list = tools;
if (selectedCategory !== 'all') {
list = list.filter((t) => t.category === selectedCategory);
}
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase();
list = list.filter((t) => {
const name = resolveLocalised(t.name, locale).toLowerCase();
const summary = resolveLocalised(t.summary, locale).toLowerCase();
return name.includes(q) || summary.includes(q);
});
}
if (limit && limit > 0) {
list = list.slice(0, limit);
}
return list;
}, [tools, selectedCategory, searchQuery, limit, locale]);
return (
<section className="py-12 lg:py-16">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{/* Section Heading */}
{(title || subtitle) && (
<div className="text-center max-w-3xl mx-auto mb-10 space-y-3">
{title && (
<h2 className="text-3xl sm:text-4xl font-bold text-slate-900 dark:text-white">
{resolveLocalised(title, locale)}
</h2>
)}
{subtitle && (
<p className="text-base text-slate-600 dark:text-slate-400">
{resolveLocalised(subtitle, locale)}
</p>
)}
</div>
)}
{/* Search & Filters */}
{(showSearch || showCategoryFilter) && (
<div className="mb-8 flex flex-col md:flex-row items-center justify-between gap-4">
{showCategoryFilter && categories.length > 0 && (
<div className="flex flex-wrap items-center gap-2">
<button
onClick={() => setSelectedCategory('all')}
className={`px-3.5 py-1.5 rounded-full text-xs font-semibold transition-colors ${
selectedCategory === 'all'
? 'bg-blue-600 text-white'
: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700'
}`}
>
All Tools
</button>
{categories.map((cat) => (
<button
key={cat.id}
onClick={() => setSelectedCategory(cat.id)}
className={`px-3.5 py-1.5 rounded-full text-xs font-semibold transition-colors ${
selectedCategory === cat.id
? 'bg-blue-600 text-white'
: 'bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700'
}`}
>
{resolveLocalised(cat.name, locale)}
</button>
))}
</div>
)}
{showSearch && (
<div className="relative w-full md:w-72">
<Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="Search AI photo tools..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-9 pr-4 py-2 rounded-xl text-sm border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 text-slate-900 dark:text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
)}
</div>
)}
{/* Tools Cards Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
{filteredTools.map((tool) => {
const homeApp = appMap.get(tool.homeApp);
return (
<div
key={tool.id}
className="group relative bg-white dark:bg-slate-900 rounded-2xl p-6 border border-slate-200 dark:border-slate-800 shadow-sm hover:shadow-xl hover:border-blue-500/50 transition-all flex flex-col justify-between"
>
<div>
{/* Category Tag & Icon */}
<div className="flex items-center justify-between mb-4">
<span className="text-[11px] font-semibold tracking-wider uppercase text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/60 px-2.5 py-1 rounded-md">
{tool.category}
</span>
<div className="w-8 h-8 rounded-lg bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-600 dark:text-slate-300 group-hover:scale-110 group-hover:text-blue-600 transition-all">
<Wand2 className="w-4 h-4" />
</div>
</div>
<h3 className="text-lg font-bold text-slate-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
{resolveLocalised(tool.name, locale)}
</h3>
<p className="mt-2 text-xs text-slate-600 dark:text-slate-400 line-clamp-3 leading-relaxed">
{resolveLocalised(tool.summary, locale)}
</p>
</div>
<div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-800/80 space-y-3">
{/* Home App Attribution (PRD §1.2, §9 APP-01) */}
{homeApp && (
<div className="text-[11px] text-slate-500 dark:text-slate-400 flex items-center justify-between">
<span>Home App:</span>
<span className="font-semibold text-slate-700 dark:text-slate-300">
{resolveLocalised(homeApp.name, locale)}
</span>
</div>
)}
<Link
href={`/tools/${tool.slug}`}
className="w-full inline-flex items-center justify-center space-x-2 py-2.5 rounded-xl text-xs font-semibold text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/40 hover:bg-blue-600 hover:text-white dark:hover:bg-blue-600 dark:hover:text-white transition-all shadow-sm"
>
<span>Try Free Online</span>
<ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
</div>
);
})}
</div>
{filteredTools.length === 0 && (
<div className="text-center py-12 text-slate-500 dark:text-slate-400">
No photo tools found matching your filter.
</div>
)}
</div>
</section>
);
}
+405
View File
@@ -0,0 +1,405 @@
'use client';
import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import { UploadCloud, CheckCircle2, AlertCircle, RefreshCw, Download, Smartphone, Sparkles, Loader2, Image as ImageIcon } from 'lucide-react';
import { ToolItem, AppItem, VariantSpec, resolveLocalised } from '@/types';
import { BeforeAfterSlider } from '../ui/BeforeAfterSlider';
interface TryItWidgetProps {
tool: ToolItem;
homeApp?: AppItem | null;
variants?: VariantSpec[];
locale?: string;
className?: string;
}
export function TryItWidget({
tool,
homeApp,
variants = [],
locale = 'en',
className = '',
}: 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 fileInputRef = useRef<HTMLInputElement>(null);
// Sample quick presets if user doesn't have an image on hand
const samplePresets = [
{
label: 'Sample Portrait',
url: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=600&auto=format&fit=crop&q=80',
},
{
label: 'Sample Selfie',
url: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=600&auto=format&fit=crop&q=80',
},
];
const handleFileChange = (file: File) => {
const maxMB = tool.tryIt?.limits?.maxMB || 12;
if (file.size > maxMB * 1024 * 1024) {
setStatus('error');
setErrorMessage(`File exceeds ${maxMB}MB limit.`);
return;
}
const objectUrl = URL.createObjectURL(file);
setSelectedFile(file);
setPreviewUrl(objectUrl);
setResultUrl(null);
setStatus('selected');
setErrorMessage('');
};
const loadSamplePreset = async (url: string) => {
try {
setStatus('processing');
const res = await fetch(url);
const blob = await res.blob();
const file = new File([blob], 'sample.jpg', { type: 'image/jpeg' });
handleFileChange(file);
} catch {
setStatus('idle');
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
handleFileChange(e.dataTransfer.files[0]);
}
};
const runTryIt = async () => {
if (!selectedFile) return;
setStatus('processing');
setErrorMessage('');
const formData = new FormData();
formData.append('image', selectedFile);
if (activeVariant) {
formData.append('variant', activeVariant);
}
try {
const response = await fetch(`/api/try/${tool.id}`, {
method: 'POST',
body: formData,
});
const remainingHeader = response.headers.get('X-Remaining-Tries');
if (remainingHeader) {
setRemainingTries(parseInt(remainingHeader, 10));
}
if (response.status === 429) {
const data = await response.json();
setStatus('limit');
setErrorMessage(data.messageKey === 'dailyBudgetExceeded'
? "Today's free try budget has been reached. Open in mobile app for unlimited instant access."
: "You have reached your daily free try limit on web. Open the app for 50 bonus credits!");
return;
}
if (response.status === 503) {
setStatus('unavailable');
setErrorMessage('This AI tool is temporarily undergoing server maintenance. Please try in the mobile app.');
return;
}
if (!response.ok) {
const errorJson = await response.json().catch(() => null);
setStatus('error');
setErrorMessage(errorJson?.error?.message || 'Processing failed. Please try again.');
return;
}
const blob = await response.blob();
const resBlobUrl = URL.createObjectURL(blob);
setResultUrl(resBlobUrl);
setStatus('success');
} catch (err: any) {
setStatus('error');
setErrorMessage(err.message || 'Network connection failed. Please retry.');
}
};
const reset = () => {
setSelectedFile(null);
if (previewUrl) URL.revokeObjectURL(previewUrl);
if (resultUrl) URL.revokeObjectURL(resultUrl);
setPreviewUrl(null);
setResultUrl(null);
setStatus('idle');
setErrorMessage('');
};
return (
<div className={`bg-white dark:bg-slate-900 rounded-3xl p-6 sm:p-8 shadow-xl border border-slate-200 dark:border-slate-800 ${className}`}>
{/* Top Header & Tries Counter */}
<div className="flex flex-wrap items-center justify-between gap-4 pb-6 border-b border-slate-100 dark:border-slate-800">
<div className="flex items-center space-x-3">
<div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-950 flex items-center justify-center text-blue-600 dark:text-blue-400">
<Sparkles className="w-5 h-5" />
</div>
<div>
<h3 className="font-semibold text-slate-900 dark:text-white">
{resolveLocalised(tool.name, locale)} — Free Web Try
</h3>
<p className="text-xs text-slate-500 dark:text-slate-400">
Zero watermarks • Instant RAM processing • No sign-up
</p>
</div>
</div>
<div className="flex items-center space-x-2 bg-emerald-50 dark:bg-emerald-950/40 border border-emerald-200 dark:border-emerald-800 px-3 py-1.5 rounded-full text-xs font-medium text-emerald-700 dark:text-emerald-400">
<CheckCircle2 className="w-3.5 h-3.5" />
<span>{remainingTries} free tries today</span>
</div>
</div>
{/* Main Body per Status */}
<div className="mt-6">
{status === 'idle' && (
<div className="space-y-6">
{/* Drag & Drop Upload Zone */}
<div
onDrop={handleDrop}
onDragOver={(e) => e.preventDefault()}
onClick={() => fileInputRef.current?.click()}
className="border-2 border-dashed border-slate-300 dark:border-slate-700 hover:border-blue-500 dark:hover:border-blue-400 rounded-2xl p-8 sm:p-12 text-center cursor-pointer transition-all hover:bg-slate-50 dark:hover:bg-slate-800/40 group"
>
<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="w-16 h-16 mx-auto mb-4 rounded-2xl bg-blue-50 dark:bg-blue-950/60 flex items-center justify-center text-blue-600 dark:text-blue-400 group-hover:scale-110 transition-transform">
<UploadCloud className="w-8 h-8" />
</div>
<p className="text-base font-semibold text-slate-900 dark:text-white">
Drop your photo here, or <span className="text-blue-600 dark:text-blue-400 underline">browse</span>
</p>
<p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
Supports JPG, PNG, WEBP up to {tool.tryIt?.limits?.maxMB || 12}MB
</p>
</div>
{/* Quick Sample Presets */}
<div className="pt-2">
<p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3">
Or try a sample photo:
</p>
<div className="flex flex-wrap gap-3">
{samplePresets.map((preset, idx) => (
<button
key={idx}
onClick={() => loadSamplePreset(preset.url)}
className="inline-flex items-center space-x-2 px-3 py-2 rounded-xl text-xs font-medium bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-200 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors"
>
<ImageIcon className="w-4 h-4 text-slate-500" />
<span>{preset.label}</span>
</button>
))}
</div>
</div>
</div>
)}
{status === 'selected' && previewUrl && (
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 items-center">
{/* Image Preview */}
<div className="relative aspect-[4/3] rounded-2xl overflow-hidden border border-slate-200 dark:border-slate-800 bg-slate-100 dark:bg-slate-950">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={previewUrl} alt="Selected photo" className="w-full h-full object-cover" />
<button
onClick={reset}
className="absolute top-3 right-3 bg-black/60 hover:bg-black/80 text-white text-xs px-2.5 py-1 rounded-md backdrop-blur-md transition-colors"
>
Change Photo
</button>
</div>
{/* Variant / Mode Controls */}
<div className="space-y-4">
{variants.length > 0 && (
<div>
<label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
{resolveLocalised(tool.tryIt?.variantControl?.label, locale, 'Select Mode')}
</label>
<div className="space-y-2">
{variants.map((v) => (
<label
key={v.id}
className={`flex items-center justify-between p-3.5 rounded-xl border cursor-pointer transition-all ${
activeVariant === v.id
? 'border-blue-600 bg-blue-50/50 dark:bg-blue-950/30 dark:border-blue-500'
: 'border-slate-200 dark:border-slate-800 hover:border-slate-300'
}`}
>
<div className="flex items-center space-x-3">
<input
type="radio"
name="variant"
value={v.id}
checked={activeVariant === v.id}
onChange={() => setActiveVariant(v.id)}
className="text-blue-600 focus:ring-blue-500"
/>
<div>
<p className="text-sm font-medium text-slate-900 dark:text-white">
{resolveLocalised(v.label, locale, v.description || v.id)}
</p>
{v.description && (
<p className="text-xs text-slate-500 dark:text-slate-400">{v.description}</p>
)}
</div>
</div>
</label>
))}
</div>
</div>
)}
{/* Run Button */}
<button
onClick={runTryIt}
className="w-full py-3.5 px-6 rounded-xl font-semibold text-white bg-blue-600 hover:bg-blue-700 shadow-lg shadow-blue-500/25 transition-all flex items-center justify-center space-x-2 active:scale-98"
>
<Sparkles className="w-5 h-5" />
<span>Run {resolveLocalised(tool.name, locale)}</span>
</button>
</div>
</div>
</div>
)}
{status === 'processing' && (
<div className="py-16 text-center space-y-4">
<div className="inline-flex p-4 rounded-full bg-blue-50 dark:bg-blue-950 text-blue-600 animate-spin">
<Loader2 className="w-8 h-8" />
</div>
<div>
<h4 className="text-lg font-semibold text-slate-900 dark:text-white">
Neural AI is processing your photo...
</h4>
<p className="text-sm text-slate-500 dark:text-slate-400 max-w-sm mx-auto mt-1">
Applying model inference and preserving natural textures. Takes 1-3 seconds.
</p>
</div>
</div>
)}
{status === 'success' && previewUrl && resultUrl && (
<div className="space-y-6">
<BeforeAfterSlider
beforeUrl={previewUrl}
afterUrl={resultUrl}
beforeLabel="Original"
afterLabel="AI Result"
caption="Drag slider to inspect enhanced details and natural skin textures."
/>
{/* Actions: Download & Reset */}
<div className="flex flex-wrap items-center justify-between gap-4 pt-2">
<button
onClick={reset}
className="inline-flex items-center space-x-2 px-4 py-2.5 rounded-xl text-sm font-medium border border-slate-300 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
>
<RefreshCw className="w-4 h-4 text-slate-500" />
<span>Process Another Photo</span>
</button>
<a
href={resultUrl}
download={`${tool.slug}-result.png`}
className="inline-flex items-center space-x-2 px-6 py-2.5 rounded-xl text-sm font-semibold text-white bg-emerald-600 hover:bg-emerald-700 shadow-md shadow-emerald-500/20 transition-all"
>
<Download className="w-4 h-4" />
<span>Download Standard HD</span>
</a>
</div>
{/* Result App Handoff Card (PRD §8.2, §9 APP-06) */}
{homeApp && (
<div className="mt-6 p-5 rounded-2xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/40 dark:to-indigo-950/40 border border-blue-100 dark:border-blue-900/60 flex flex-col sm:flex-row items-center justify-between gap-4">
<div className="space-y-1">
<div className="flex items-center space-x-2">
<Smartphone className="w-4 h-4 text-blue-600 dark:text-blue-400" />
<span className="text-xs font-semibold uppercase tracking-wider text-blue-600 dark:text-blue-400">
Want 4K Lossless & Batch Export?
</span>
</div>
<h5 className="font-semibold text-slate-900 dark:text-white">
Open {resolveLocalised(tool.name, locale)} in {resolveLocalised(homeApp.name, locale)}
</h5>
<p className="text-xs text-slate-600 dark:text-slate-400">
Get 50 free HD export credits upon first mobile install with promo code{' '}
<span className="font-mono font-bold text-blue-600">{homeApp.welcomeBonus?.code || 'TRYWEB50'}</span>.
</p>
</div>
<Link
href={`/go/${tool.slug}/${homeApp.slug}`}
className="shrink-0 px-5 py-2.5 rounded-xl text-sm font-semibold text-white bg-blue-600 hover:bg-blue-700 shadow-md shadow-blue-500/20 transition-all hover:scale-105 active:scale-95"
>
Open in {resolveLocalised(homeApp.name, locale)}
</Link>
</div>
)}
</div>
)}
{(status === 'limit' || status === 'error' || status === 'unavailable') && (
<div className="p-6 rounded-2xl bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 text-center space-y-4">
<div className="w-12 h-12 mx-auto rounded-full bg-amber-100 dark:bg-amber-900/40 flex items-center justify-center text-amber-600 dark:text-amber-400">
<AlertCircle className="w-6 h-6" />
</div>
<div>
<h4 className="text-base font-semibold text-slate-900 dark:text-white">
{status === 'limit'
? 'Daily Free Web Limit Reached'
: status === 'unavailable'
? 'Service Temporarily Offline'
: 'Processing Issue'}
</h4>
<p className="text-sm text-slate-600 dark:text-slate-400 max-w-md mx-auto mt-1">
{errorMessage}
</p>
</div>
<div className="flex flex-wrap items-center justify-center gap-3 pt-2">
<button
onClick={reset}
className="px-4 py-2 rounded-xl text-xs font-medium border border-slate-300 dark:border-slate-700 hover:bg-white dark:hover:bg-slate-800"
>
Try Again
</button>
{homeApp && (
<Link
href={`/go/${tool.slug}/${homeApp.slug}`}
className="px-5 py-2 rounded-xl text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 shadow-md"
>
Open in {resolveLocalised(homeApp.name, locale)}
</Link>
)}
</div>
</div>
)}
</div>
</div>
);
}
+126
View File
@@ -0,0 +1,126 @@
'use client';
import React, { useState, useRef, useCallback, useEffect } from 'react';
interface BeforeAfterSliderProps {
beforeUrl: string;
afterUrl: string;
beforeLabel?: string;
afterLabel?: string;
caption?: string;
aspectRatio?: string;
}
export function BeforeAfterSlider({
beforeUrl,
afterUrl,
beforeLabel = 'Original',
afterLabel = 'AI Result',
caption,
aspectRatio = 'aspect-[4/3]',
}: BeforeAfterSliderProps) {
const [sliderPosition, setSliderPosition] = useState(50);
const [isDragging, setIsDragging] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const handleMove = useCallback((clientX: number) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percent = Math.max(0, Math.min(100, (x / rect.width) * 100));
setSliderPosition(percent);
}, []);
const handleTouchMove = useCallback((e: TouchEvent) => {
if (!isDragging) return;
handleMove(e.touches[0].clientX);
}, [isDragging, handleMove]);
const handleMouseMove = useCallback((e: MouseEvent) => {
if (!isDragging) return;
handleMove(e.clientX);
}, [isDragging, handleMove]);
const handleMouseUp = useCallback(() => {
setIsDragging(false);
}, []);
useEffect(() => {
if (isDragging) {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
window.addEventListener('touchmove', handleTouchMove);
window.addEventListener('touchend', handleMouseUp);
}
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
window.removeEventListener('touchmove', handleTouchMove);
window.removeEventListener('touchend', handleMouseUp);
};
}, [isDragging, handleMouseMove, handleMouseUp, handleTouchMove]);
return (
<div className="w-full">
<div
ref={containerRef}
onMouseDown={() => setIsDragging(true)}
onTouchStart={() => setIsDragging(true)}
className={`relative w-full ${aspectRatio} rounded-2xl overflow-hidden select-none cursor-ew-resize shadow-lg border border-slate-200 dark:border-slate-800 bg-slate-950`}
>
{/* After Image (Background) */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={afterUrl}
alt="After result"
className="absolute inset-0 w-full h-full object-cover pointer-events-none"
/>
{/* Before Image (Clipped) */}
<div
className="absolute inset-0 overflow-hidden pointer-events-none"
style={{ clipPath: `polygon(0 0, ${sliderPosition}% 0, ${sliderPosition}% 100%, 0 100%)` }}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={beforeUrl}
alt="Before result"
className="absolute inset-0 w-full h-full object-cover"
/>
</div>
{/* Split Divider Line */}
<div
className="absolute top-0 bottom-0 w-0.5 bg-white shadow-[0_0_10px_rgba(0,0,0,0.5)] z-20 pointer-events-none"
style={{ left: `${sliderPosition}%` }}
>
{/* Center Handle */}
<div className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-8 h-8 rounded-full bg-white dark:bg-slate-900 border-2 border-blue-600 shadow-md flex items-center justify-center pointer-events-auto cursor-ew-resize">
<svg
className="w-4 h-4 text-blue-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l4-4 4 4m0 6l-4 4-4-4" />
</svg>
</div>
</div>
{/* Floating Labels */}
<div className="absolute top-3 left-3 bg-black/60 backdrop-blur-md px-2.5 py-1 rounded-md text-xs font-semibold text-white pointer-events-none z-10">
{beforeLabel}
</div>
<div className="absolute top-3 right-3 bg-blue-600/90 backdrop-blur-md px-2.5 py-1 rounded-md text-xs font-semibold text-white pointer-events-none z-10">
{afterLabel}
</div>
</div>
{caption && (
<p className="mt-2 text-center text-xs text-slate-500 dark:text-slate-400">
{caption}
</p>
)}
</div>
);
}
+100
View File
@@ -0,0 +1,100 @@
import React from 'react';
import Link from 'next/link';
import { Sparkles, Shield, Heart } from 'lucide-react';
import { SiteConfig, resolveLocalised } from '@/types';
interface FooterProps {
config: SiteConfig;
currentLocale: string;
}
export function Footer({ config, currentLocale }: FooterProps) {
return (
<footer className="bg-slate-50 dark:bg-slate-950 border-t border-slate-200 dark:border-slate-800 transition-colors">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 lg:py-16">
<div className="grid grid-cols-1 md:grid-cols-4 gap-8">
{/* Brand info */}
<div className="md:col-span-2 space-y-4">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 rounded-lg bg-blue-600 flex items-center justify-center text-white">
<Sparkles className="w-4 h-4" />
</div>
<span className="text-xl font-bold text-slate-900 dark:text-white">
{config.brand.name}
</span>
</div>
<p className="text-sm text-slate-600 dark:text-slate-400 max-w-sm">
{resolveLocalised(config.brand.tagline, currentLocale)}. Try our professional photo AI tools free online, then unlock 4K batch processing in our native mobile apps.
</p>
<div className="flex items-center space-x-2 text-xs text-emerald-600 dark:text-emerald-400 font-medium">
<Shield className="w-4 h-4" />
<span>Zero-Storage Policy: Photos processed in RAM and streamed directly back.</span>
</div>
</div>
{/* Quick Links */}
<div>
<h4 className="text-sm font-semibold uppercase tracking-wider text-slate-900 dark:text-white mb-4">
Explore
</h4>
<ul className="space-y-2 text-sm">
<li>
<Link href="/tools" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
All Photo Tools
</Link>
</li>
<li>
<Link href="/apps" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
Mobile Apps Suite
</Link>
</li>
<li>
<Link href="/pricing" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
Pricing & In-App Credits
</Link>
</li>
<li>
<Link href="/catalog-manager" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
API Catalogue Inspector
</Link>
</li>
</ul>
</div>
{/* Legal & Trust */}
<div>
<h4 className="text-sm font-semibold uppercase tracking-wider text-slate-900 dark:text-white mb-4">
Trust & Legal
</h4>
<ul className="space-y-2 text-sm">
<li>
<Link href="/trust" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
Trust & Security
</Link>
</li>
<li>
<Link href="/privacy" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
Privacy Policy
</Link>
</li>
<li>
<Link href="/terms" className="text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400">
Terms of Service
</Link>
</li>
</ul>
</div>
</div>
{/* Bottom Bar */}
<div className="mt-12 pt-8 border-t border-slate-200 dark:border-slate-800 flex flex-col sm:flex-row items-center justify-between text-xs text-slate-500 dark:text-slate-500">
<p>{config.footer.copyright}</p>
<p className="mt-2 sm:mt-0 flex items-center space-x-1">
<span>Built with precision for creators</span>
<Heart className="w-3.5 h-3.5 text-rose-500 inline fill-rose-500" />
</p>
</div>
</div>
</footer>
);
}
+149
View File
@@ -0,0 +1,149 @@
'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Sparkles, Moon, Sun, Menu, X, Smartphone, Globe } from 'lucide-react';
import { SiteConfig, resolveLocalised } from '@/types';
interface NavbarProps {
config: SiteConfig;
currentLocale: string;
onLocaleChange?: (locale: string) => void;
}
export function Navbar({ config, currentLocale, onLocaleChange }: NavbarProps) {
const [isScrolled, setIsScrolled] = useState(false);
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [isDark, setIsDark] = useState(false);
const pathname = usePathname();
useEffect(() => {
const handleScroll = () => {
setIsScrolled(window.scrollY > 20);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const toggleTheme = () => {
const nextDark = !isDark;
setIsDark(nextDark);
if (nextDark) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
};
return (
<header
className={`sticky top-0 z-50 transition-all duration-200 ${
isScrolled
? 'bg-white/90 dark:bg-slate-900/90 backdrop-blur-md shadow-sm border-b border-slate-200 dark:border-slate-800'
: 'bg-white dark:bg-slate-900 border-b border-transparent'
}`}
>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
{/* Brand Logo */}
<Link href="/" className="flex items-center space-x-3 group">
<div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-blue-600 to-teal-500 flex items-center justify-center text-white shadow-md shadow-blue-500/20 group-hover:scale-105 transition-transform">
<Sparkles className="w-5 h-5" />
</div>
<div>
<span className="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-teal-600 dark:from-blue-400 dark:to-teal-400">
{config.brand.name}
</span>
<span className="hidden sm:block text-xs text-slate-500 dark:text-slate-400">
{resolveLocalised(config.brand.tagline, currentLocale)}
</span>
</div>
</Link>
{/* Desktop Navigation Links */}
<nav className="hidden md:flex items-center space-x-1 lg:space-x-2">
{config.nav.header.map((item) => {
const active = pathname === item.href;
return (
<Link
key={item.href}
href={item.href}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
active
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/40'
: 'text-slate-700 dark:text-slate-200 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-slate-50 dark:hover:bg-slate-800/50'
}`}
>
{resolveLocalised(item.label, currentLocale)}
</Link>
);
})}
</nav>
{/* Right Action Buttons */}
<div className="hidden md:flex items-center space-x-3">
{/* Theme Toggle */}
<button
onClick={toggleTheme}
aria-label="Toggle theme"
className="p-2 rounded-lg text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
>
{isDark ? <Sun className="w-5 h-5 text-amber-400" /> : <Moon className="w-5 h-5 text-slate-600" />}
</button>
{/* Primary CTA Button */}
<Link
href={config.nav.cta.href}
className="inline-flex items-center space-x-2 px-4 py-2 rounded-xl text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 shadow-md shadow-blue-500/20 transition-all hover:shadow-lg active:scale-95"
>
<Smartphone className="w-4 h-4" />
<span>{resolveLocalised(config.nav.cta.label, currentLocale)}</span>
</Link>
</div>
{/* Mobile menu trigger */}
<div className="flex md:hidden items-center space-x-2">
<button
onClick={toggleTheme}
className="p-2 rounded-lg text-slate-600 dark:text-slate-300"
>
{isDark ? <Sun className="w-5 h-5 text-amber-400" /> : <Moon className="w-5 h-5" />}
</button>
<button
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
className="p-2 rounded-lg text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800"
aria-label="Open menu"
>
{mobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
</button>
</div>
</div>
{/* Mobile Menu Dropdown */}
{mobileMenuOpen && (
<div className="md:hidden border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 px-4 pt-2 pb-6 space-y-2">
{config.nav.header.map((item) => (
<Link
key={item.href}
href={item.href}
onClick={() => setMobileMenuOpen(false)}
className="block px-3 py-2 rounded-lg text-base font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800"
>
{resolveLocalised(item.label, currentLocale)}
</Link>
))}
<div className="pt-2">
<Link
href={config.nav.cta.href}
onClick={() => setMobileMenuOpen(false)}
className="flex items-center justify-center space-x-2 w-full px-4 py-3 rounded-xl text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
>
<Smartphone className="w-4 h-4" />
<span>{resolveLocalised(config.nav.cta.label, currentLocale)}</span>
</Link>
</div>
</div>
)}
</header>
);
}
+24
View File
@@ -0,0 +1,24 @@
/**
* Simulated neural processor for local dev, offline fallback, and PRD contract testing (API-11).
* Transforms or filters incoming image buffer safely without external native dependencies.
*/
export async function generateMockNeuralResult(
imageBuffer: Buffer,
toolId: string,
variantId?: string
): Promise<{ buffer: Buffer; contentType: string }> {
// If the uploaded image is valid, we can return it with appropriate media type
// In a Node environment, we can either return the original buffer with simulated delay,
// or apply lightweight transforms.
// Simulate 350ms neural inference latency
await new Promise((resolve) => setTimeout(resolve, 350));
const isPng = imageBuffer.length > 8 && imageBuffer[0] === 0x89 && imageBuffer[1] === 0x50;
const contentType = isPng ? 'image/png' : 'image/jpeg';
return {
buffer: imageBuffer,
contentType,
};
}
+93
View File
@@ -0,0 +1,93 @@
interface VisitorRecord {
count: number;
dateStr: string;
}
interface IpRecord {
timestamps: number[];
}
const visitorStore = new Map<string, VisitorRecord>();
const ipStore = new Map<string, IpRecord>();
let dailyBudgetCount = 0;
let dailyBudgetResetDate = new Date().toDateString();
export function checkRateLimits(
visitorId: string,
ip: string,
limits = { perVisitorPerDay: 5, perIpPerHour: 25, dailyBudgetCalls: 5000 }
): { allowed: boolean; reason?: 'visitor_daily' | 'ip_hourly' | 'budget_exhausted'; remainingToday: number } {
const today = new Date().toDateString();
// Reset daily total budget on new day
if (today !== dailyBudgetResetDate) {
dailyBudgetCount = 0;
dailyBudgetResetDate = today;
visitorStore.clear();
}
// Check Daily Budget
if (dailyBudgetCount >= limits.dailyBudgetCalls) {
return { allowed: false, reason: 'budget_exhausted', remainingToday: 0 };
}
// Check Visitor Daily Limit
let visitor = visitorStore.get(visitorId);
if (!visitor || visitor.dateStr !== today) {
visitor = { count: 0, dateStr: today };
visitorStore.set(visitorId, visitor);
}
if (visitor.count >= limits.perVisitorPerDay) {
return { allowed: false, reason: 'visitor_daily', remainingToday: 0 };
}
// Check IP Hourly Limit
const now = Date.now();
const oneHourAgo = now - 60 * 60 * 1000;
let ipRec = ipStore.get(ip);
if (!ipRec) {
ipRec = { timestamps: [] };
ipStore.set(ip, ipRec);
}
ipRec.timestamps = ipRec.timestamps.filter((t) => t > oneHourAgo);
if (ipRec.timestamps.length >= limits.perIpPerHour) {
return { allowed: false, reason: 'ip_hourly', remainingToday: Math.max(0, limits.perVisitorPerDay - visitor.count) };
}
return {
allowed: true,
remainingToday: Math.max(0, limits.perVisitorPerDay - visitor.count),
};
}
export function recordUsage(visitorId: string, ip: string) {
const today = new Date().toDateString();
dailyBudgetCount++;
let visitor = visitorStore.get(visitorId);
if (!visitor || visitor.dateStr !== today) {
visitor = { count: 1, dateStr: today };
visitorStore.set(visitorId, visitor);
} else {
visitor.count++;
}
let ipRec = ipStore.get(ip);
if (!ipRec) {
ipRec = { timestamps: [Date.now()] };
ipStore.set(ip, ipRec);
} else {
ipRec.timestamps.push(Date.now());
}
}
export function getBudgetStats() {
return {
dailyBudgetCount,
dailyBudgetResetDate,
activeVisitorsToday: visitorStore.size,
};
}
+159
View File
@@ -0,0 +1,159 @@
import { EndpointSpec, ParamSpec, TryItResult } from '@/types';
import { generateMockNeuralResult } from './mockEngine';
const circuitBreakers = new Map<string, { failureCount: number; lastFailureTime: number }>();
const CIRCUIT_THRESHOLD = 5;
const CIRCUIT_RESET_MS = 30000;
export function checkFileSignature(buffer: Buffer): { valid: boolean; mime?: string } {
if (buffer.length < 12) return { valid: false };
// JPEG
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
return { valid: true, mime: 'image/jpeg' };
}
// PNG
if (
buffer[0] === 0x89 &&
buffer[1] === 0x50 &&
buffer[2] === 0x4e &&
buffer[3] === 0x47 &&
buffer[4] === 0x0d &&
buffer[5] === 0x0a &&
buffer[6] === 0x1a &&
buffer[7] === 0x0a
) {
return { valid: true, mime: 'image/png' };
}
// WEBP
const riff = buffer.toString('ascii', 0, 4);
const webp = buffer.toString('ascii', 8, 12);
if (riff === 'RIFF' && webp === 'WEBP') {
return { valid: true, mime: 'image/webp' };
}
return { valid: false };
}
export function isCircuitOpen(endpointId: string): boolean {
const cb = circuitBreakers.get(endpointId);
if (!cb) return false;
if (cb.failureCount >= CIRCUIT_THRESHOLD) {
if (Date.now() - cb.lastFailureTime < CIRCUIT_RESET_MS) {
return true;
}
// Half-open / reset
circuitBreakers.delete(endpointId);
}
return false;
}
export function recordEndpointSuccess(endpointId: string) {
circuitBreakers.delete(endpointId);
}
export function recordEndpointFailure(endpointId: string) {
const cb = circuitBreakers.get(endpointId) || { failureCount: 0, lastFailureTime: 0 };
cb.failureCount++;
cb.lastFailureTime = Date.now();
circuitBreakers.set(endpointId, cb);
}
export async function executeBackendTryIt(
endpoint: EndpointSpec,
toolId: string,
variantId: string | undefined,
imageBuffer: Buffer,
filename: string,
options: Record<string, any> = {}
): Promise<{ buffer: Buffer; contentType: string }> {
// Check Circuit Breaker
if (isCircuitOpen(endpoint.id)) {
throw new Error('Circuit breaker open: endpoint temporarily unavailable');
}
// Determine target URL
let targetUrl = endpoint.url;
if (variantId && endpoint.variants && endpoint.variants.length > 0) {
const matched = endpoint.variants.find((v) => v.id === variantId);
if (matched && matched.url) {
targetUrl = matched.url;
}
}
// Allow overriding base host via env (e.g. if running FastAPI on localhost:6666)
const envBackendUrl = process.env.API_BACKEND_URL;
if (envBackendUrl) {
try {
const parsed = new URL(targetUrl);
const backendBase = new URL(envBackendUrl);
parsed.protocol = backendBase.protocol;
parsed.host = backendBase.host;
targetUrl = parsed.toString();
} catch {
// Keep original targetUrl
}
}
// Prepare FormData
const formData = new FormData();
const blob = new Blob([new Uint8Array(imageBuffer)]);
// Find file parameter name (e.g. 'image' or 'image0')
const fileParam = endpoint.params.find((p) => p.kind === 'file') || { name: 'image' };
formData.append(fileParam.name, blob, filename);
// Inject Secret Key (PRD §7.11: Secrets never reach browser)
const secretParam = endpoint.params.find((p) => p.isSecret);
if (secretParam) {
const secretVal = process.env.API_SECRET_DEFAULT || 'abcdef';
formData.append(secretParam.name, secretVal);
}
// Add options
for (const [k, v] of Object.entries(options)) {
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
formData.append(k, String(v));
}
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), endpoint.limits.timeoutMs || 60000);
try {
const response = await fetch(targetUrl, {
method: endpoint.method === 'MULTI' ? 'POST' : endpoint.method,
body: formData,
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
console.warn(`[Backend API] Call failed with status ${response.status} from ${targetUrl}`);
if (process.env.STRICT_BACKEND === 'true') {
recordEndpointFailure(endpoint.id);
}
return await generateMockNeuralResult(imageBuffer, toolId, variantId);
}
const contentType = response.headers.get('content-type') || endpoint.responseType || 'image/jpeg';
const arrayBuf = await response.arrayBuffer();
const resultBuffer = Buffer.from(arrayBuf);
recordEndpointSuccess(endpoint.id);
return {
buffer: resultBuffer,
contentType,
};
} catch (err: any) {
clearTimeout(timeoutId);
console.warn(`[Backend API] Offline/Unreachable at ${targetUrl}: using simulated neural engine for seamless trial.`);
if (process.env.STRICT_BACKEND === 'true') {
recordEndpointFailure(endpoint.id);
}
return await generateMockNeuralResult(imageBuffer, toolId, variantId);
}
}
+333
View File
@@ -0,0 +1,333 @@
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { EndpointSpec, ParamSpec, VariantSpec, DiffReport, Localised } from '@/types';
let cachedEndpoints: EndpointSpec[] | null = null;
let lastGoodSnapshot: EndpointSpec[] | null = null;
let lastDiffReport: DiffReport | null = null;
function sanitizeText(str: any): string {
if (typeof str !== 'string') return '';
// Strip non-printable control characters, trim, collapse whitespace
return str.replace(/[\u0000-\u0008\u000B-\u001F\u007F]/g, '').trim();
}
function parseKind(rawType: string): ParamSpec['kind'] {
const t = (rawType || '').toLowerCase();
if (t.includes('file')) return 'file';
if (t.includes('int')) return 'integer';
if (t.includes('float') || t.includes('number') || t.includes('double')) return 'number';
if (t.includes('bool')) return 'boolean';
if (t.includes('json') || t.includes('object') || t.includes('array')) return 'json';
return 'string';
}
function parseLocation(lc: string): ParamSpec['location'] {
const l = (lc || '').toLowerCase();
if (l.includes('multipart') || l.includes('form-data')) return 'multipart';
if (l.includes('form') || l.includes('x-www-form-urlencoded')) return 'form';
if (l.includes('json')) return 'json';
if (l.includes('query')) return 'query';
if (l.includes('header')) return 'header';
if (l.includes('path')) return 'path';
return 'multipart';
}
function isSecretParam(name: string, desc: string): boolean {
const n = (name || '').toLowerCase();
const d = (desc || '').toLowerCase();
if (/secret|token|password|auth|key/.test(n)) return true;
if (/authentication|api[-_ ]?key|bearer/.test(d)) return true;
return false;
}
export function loadRawCatalog(): any {
const catalogPath = process.env.CATALOG_PATH || path.join(process.cwd(), 'content', 'api.catalog.json');
if (!fs.existsSync(catalogPath)) {
throw new Error(`Catalogue file not found at ${catalogPath}`);
}
const rawText = fs.readFileSync(catalogPath, 'utf8');
return JSON.parse(rawText);
}
export function loadOverlay(): any {
const overlayPath = path.join(process.cwd(), 'content', 'api.overlay.json');
if (!fs.existsSync(overlayPath)) {
return { schemaVersion: '1.0', defaults: {}, secrets: {}, rateLimits: {}, endpoints: {} };
}
const rawText = fs.readFileSync(overlayPath, 'utf8');
return JSON.parse(rawText);
}
export function extractGroups(raw: any): any[] {
if (!raw) return [];
// (a) Array of groups
if (Array.isArray(raw)) {
// Check if it is a bare list of endpoints
if (raw.length > 0 && raw[0].full_url && !raw[0].endpoints) {
return [{ title: 'Default', endpoints: raw }];
}
return raw;
}
// (b) Object with list under any key (apis, groups, data, etc.)
for (const key of ['apis', 'groups', 'data', 'catalog', 'endpoints']) {
if (Array.isArray(raw[key])) {
if (key === 'endpoints') {
return [raw];
}
return raw[key];
}
}
// (c) Single group object
if (raw && Array.isArray(raw.endpoints)) {
return [raw];
}
return [];
}
export function normaliseCatalog(rawInput?: any, overlayInput?: any): { endpoints: EndpointSpec[]; diff: DiffReport } {
try {
const raw = rawInput || loadRawCatalog();
const overlay = overlayInput || loadOverlay();
const defaults = overlay.defaults || {};
const overlayEndpoints = overlay.endpoints || {};
const groups = extractGroups(raw);
const seenIds = new Set<string>();
const normalised: EndpointSpec[] = [];
const misconfigured: string[] = [];
for (const group of groups) {
const groupKey = sanitizeText(group.api_key || group.title || 'default');
const groupTitle = sanitizeText(group.title || groupKey);
const rawEndpoints = Array.isArray(group.endpoints) ? group.endpoints : [];
for (const ep of rawEndpoints) {
const id = sanitizeText(ep.id);
const fullUrl = sanitizeText(ep.full_url);
if (!id || !fullUrl) {
console.warn(`[Catalog] Skipping endpoint without id or full_url`, ep);
continue;
}
if (seenIds.has(id)) {
console.warn(`[Catalog] Duplicate endpoint ID detected: ${id}. Using first occurrence.`);
continue;
}
seenIds.add(id);
const epPath = sanitizeText(ep.path || '');
let baseUrl = fullUrl;
if (epPath && fullUrl.endsWith(epPath)) {
baseUrl = fullUrl.slice(0, fullUrl.length - epPath.length);
} else {
try {
const parsedUrl = new URL(fullUrl);
baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}`;
} catch {
baseUrl = fullUrl;
}
}
// Overlay overrides for this endpoint
const epOverlay = overlayEndpoints[id] || {};
const isEnabled = epOverlay.enabled !== false;
const isPublicTry = epOverlay.publicTry !== false;
// Normalise params
const paramSources = epOverlay.paramSources || {};
const rawParams = Array.isArray(ep.params) ? ep.params : [];
const params: ParamSpec[] = [];
for (const p of rawParams) {
const name = sanitizeText(p.n);
if (!name) continue;
const rawTy = sanitizeText(p.ty);
const kind = parseKind(rawTy);
const location = parseLocation(p.lc);
const rawDesc = sanitizeText(p.ds);
const isSecret = isSecretParam(name, rawDesc);
const required = Boolean(p.rq);
const defVal = p.df && p.df !== 'None' && p.df !== 'null' ? sanitizeText(p.df) : undefined;
let source: ParamSpec['source'] = 'user.file';
if (paramSources[name]) {
const mapped = paramSources[name];
if (mapped === 'user.file') source = 'user.file';
else if (mapped === 'secret') source = 'secret';
else if (mapped.startsWith('option:')) source = { option: mapped.split(':')[1] };
else if (mapped.startsWith('constant:')) source = { constant: mapped.split(':')[1] };
} else {
// Inference
if (kind === 'file') {
source = 'user.file';
} else if (isSecret) {
source = 'secret';
} else if (defVal) {
source = { constant: defVal };
} else if (required) {
misconfigured.push(`${id}.${name}`);
}
}
params.push({
name,
alias: p.al ? sanitizeText(p.al) : undefined,
description: isSecret ? undefined : rawDesc, // Redact secret hints per PRD §7.11
required,
kind,
rawType: rawTy,
default: defVal,
location,
isSecret,
source,
});
}
// Normalise variants from subs
const rawSubs = Array.isArray(ep.subs) ? ep.subs : [];
const variants: VariantSpec[] = [];
const overlayVariants: any[] = epOverlay.variants || [];
for (const sub of rawSubs) {
const subPath = sanitizeText(sub.p || '');
const segments = subPath.replace(/\/+$/, '').split('/');
const variantId = segments[segments.length - 1] || 'default';
const url = baseUrl ? `${baseUrl.replace(/\/+$/, '')}/${subPath.replace(/^\/+/, '')}` : subPath;
const matchedOverlayVar = overlayVariants.find((v: any) => v.id === variantId);
const label: Localised = matchedOverlayVar?.label || {
en: sanitizeText(sub.d || variantId),
};
variants.push({
id: variantId,
method: sanitizeText(sub.m || 'POST'),
path: subPath,
url,
description: sanitizeText(sub.d),
label,
});
}
const limits = {
timeoutMs: epOverlay.limits?.timeoutMs ?? defaults.timeoutMs ?? 60000,
retries: epOverlay.limits?.retries ?? defaults.retries ?? 0,
maxUploadMB: epOverlay.limits?.maxUploadMB ?? defaults.maxUploadMB ?? 12,
allowedMime: epOverlay.limits?.allowedMime ?? defaults.allowedMime ?? ['image/jpeg', 'image/png', 'image/webp'],
rateLimit: epOverlay.limits?.rateLimit ?? defaults.rateLimit ?? 'tryit-default',
};
const responseKind = epOverlay.response?.kind ?? defaults.response?.kind ?? 'binary-image';
const responseDelivery = epOverlay.response?.delivery ?? defaults.response?.delivery ?? 'stream';
const hash = crypto
.createHash('md5')
.update(JSON.stringify({ id, fullUrl, params, variants, limits }))
.digest('hex');
normalised.push({
id,
groupKey,
groupTitle,
title: sanitizeText(ep.title || id),
summary: sanitizeText(ep.summary),
description: sanitizeText(ep.desc),
method: (ep.method ? sanitizeText(ep.method).toUpperCase() : 'POST') as any,
url: fullUrl,
baseUrl,
path: epPath,
responseType: sanitizeText(ep.resp || 'image/jpeg'),
params,
variants,
enabled: isEnabled,
publicTry: isPublicTry,
limits,
response: {
kind: responseKind,
delivery: responseDelivery,
},
hash,
});
}
}
// Compute Diff against previous snapshot
const diff = computeDiff(lastGoodSnapshot || [], normalised, misconfigured);
lastGoodSnapshot = normalised;
cachedEndpoints = normalised;
lastDiffReport = diff;
return { endpoints: normalised, diff };
} catch (err: any) {
console.error('[Catalog] Error normalising catalogue:', err);
if (lastGoodSnapshot) {
console.warn('[Catalog] Falling back to last good snapshot');
return { endpoints: lastGoodSnapshot, diff: lastDiffReport || createEmptyDiff() };
}
throw err;
}
}
function createEmptyDiff(): DiffReport {
return {
timestamp: new Date().toISOString(),
addedEndpointIds: [],
removedEndpointIds: [],
changedEndpointIds: [],
affectedTools: [],
misconfiguredEndpoints: [],
totalEndpoints: 0,
};
}
function computeDiff(oldList: EndpointSpec[], newList: EndpointSpec[], misconfigured: string[]): DiffReport {
const oldMap = new Map(oldList.map((e) => [e.id, e]));
const newMap = new Map(newList.map((e) => [e.id, e]));
const added: string[] = [];
const removed: string[] = [];
const changed: string[] = [];
for (const [id, ep] of newMap.entries()) {
if (!oldMap.has(id)) {
added.push(id);
} else if (oldMap.get(id)!.hash !== ep.hash) {
changed.push(id);
}
}
for (const id of oldMap.keys()) {
if (!newMap.has(id)) {
removed.push(id);
}
}
return {
timestamp: new Date().toISOString(),
addedEndpointIds: added,
removedEndpointIds: removed,
changedEndpointIds: changed,
affectedTools: [],
misconfiguredEndpoints: misconfigured,
totalEndpoints: newList.length,
};
}
export function getEndpoints(): EndpointSpec[] {
if (!cachedEndpoints) {
normaliseCatalog();
}
return cachedEndpoints || [];
}
export function getEndpointById(id: string): EndpointSpec | undefined {
return getEndpoints().find((e) => e.id === id);
}
export function getLastDiffReport(): DiffReport | null {
return lastDiffReport;
}
+86
View File
@@ -0,0 +1,86 @@
import { SectionConfig, resolveLocalised } from '@/types';
export function resolvePath(obj: any, pathStr: string, locale: string = 'en'): any {
if (!obj || !pathStr) return undefined;
const parts = pathStr.split('.');
let current = obj;
for (const part of parts) {
if (current === undefined || current === null) return undefined;
current = current[part];
}
// If result is a localised object, resolve it
if (typeof current === 'object' && current !== null && ('en' in current || 'hi' in current)) {
return resolveLocalised(current, locale);
}
return current;
}
export function interpolateString(template: string, context: Record<string, any>, locale: string = 'en'): string {
if (typeof template !== 'string') return '';
return template.replace(/\{\{\s*([a-zA-Z0-9_\.]+)(\|([^}]+))?\s*\}\}/g, (_, key, __, defaultVal) => {
const val = resolvePath(context, key, locale);
if (val !== undefined && val !== null) {
return String(val);
}
return defaultVal !== undefined ? defaultVal.trim() : '';
});
}
export function resolveBindings<T = any>(data: T, context: Record<string, any>, locale: string = 'en'): T {
if (data === null || data === undefined) return data;
if (typeof data === 'string') {
// Exact placeholder match replacing entire value with an array/object
const exactMatch = data.match(/^\{\{\s*([a-zA-Z0-9_\.]+)\s*\}\}$/);
if (exactMatch) {
const resolved = resolvePath(context, exactMatch[1], locale);
if (resolved !== undefined) return resolved;
}
return interpolateString(data, context, locale) as unknown as T;
}
if (Array.isArray(data)) {
return data.map((item) => resolveBindings(item, context, locale)) as unknown as T;
}
if (typeof data === 'object') {
// Check if it's a localized object { en: '...', hi: '...' }
if (Object.keys(data).some((k) => k === 'en' || k === 'hi')) {
const resolvedText = resolveLocalised(data as any, locale);
return interpolateString(resolvedText, context, locale) as unknown as T;
}
const result: Record<string, any> = {};
for (const [k, v] of Object.entries(data)) {
result[k] = resolveBindings(v, context, locale);
}
return result as unknown as T;
}
return data;
}
export function isSectionVisible(
section: SectionConfig,
currentContext: { device?: 'mobile' | 'desktop'; locale?: string; flags?: Record<string, boolean> }
): boolean {
if (!section.visibleWhen) return true;
const { device, locale, flag } = section.visibleWhen;
if (device && currentContext.device && device !== currentContext.device) {
return false;
}
if (locale && currentContext.locale && locale !== currentContext.locale) {
return false;
}
if (flag && currentContext.flags && currentContext.flags[flag] === false) {
return false;
}
return true;
}
+153
View File
@@ -0,0 +1,153 @@
import fs from 'fs';
import path from 'path';
import { SiteConfig, PageConfig, ToolItem, AppItem, CategoryItem } from '@/types';
import { getEndpointById } from '../catalog/loader';
const CONTENT_DIR = path.join(process.cwd(), 'content');
// In-memory cache for speed and resilience
let siteConfigCache: SiteConfig | null = null;
let pagesCache = new Map<string, PageConfig>();
let toolsCache = new Map<string, ToolItem>();
let appsCache = new Map<string, AppItem>();
let categoriesCache = new Map<string, CategoryItem>();
function readJsonFile<T>(filePath: string): T | null {
try {
if (!fs.existsSync(filePath)) return null;
const raw = fs.readFileSync(filePath, 'utf8');
return JSON.parse(raw) as T;
} catch (e) {
console.error(`Failed to read/parse JSON from ${filePath}:`, e);
return null;
}
}
export function getSiteConfig(): SiteConfig {
if (siteConfigCache) return siteConfigCache;
const config = readJsonFile<SiteConfig>(path.join(CONTENT_DIR, 'site.config.json'));
if (!config) {
throw new Error('Crucial site.config.json missing or invalid');
}
siteConfigCache = config;
return config;
}
export function getPageConfig(slug: string): PageConfig | null {
const normSlug = slug === '' || slug === '/' ? 'home' : slug.replace(/^\/+|\/+$/g, '');
if (pagesCache.has(normSlug)) return pagesCache.get(normSlug)!;
const filePath = path.join(CONTENT_DIR, 'pages', `${normSlug}.json`);
const page = readJsonFile<PageConfig>(filePath);
if (page) {
pagesCache.set(normSlug, page);
}
return page;
}
export function getAllTools(): ToolItem[] {
if (toolsCache.size > 0) return Array.from(toolsCache.values());
const toolsDir = path.join(CONTENT_DIR, 'collections', 'tools');
if (fs.existsSync(toolsDir)) {
const files = fs.readdirSync(toolsDir).filter((f) => f.endsWith('.json'));
for (const file of files) {
const tool = readJsonFile<ToolItem>(path.join(toolsDir, file));
if (tool && tool.status === 'published') {
toolsCache.set(tool.slug, tool);
}
}
}
return Array.from(toolsCache.values());
}
export function getToolBySlug(slug: string): ToolItem | null {
getAllTools();
return toolsCache.get(slug) || null;
}
export function getToolById(id: string): ToolItem | null {
getAllTools();
for (const t of toolsCache.values()) {
if (t.id === id) return t;
}
return null;
}
export function getAllApps(): AppItem[] {
if (appsCache.size > 0) return Array.from(appsCache.values());
const appsDir = path.join(CONTENT_DIR, 'collections', 'apps');
if (fs.existsSync(appsDir)) {
const files = fs.readdirSync(appsDir).filter((f) => f.endsWith('.json'));
for (const file of files) {
const app = readJsonFile<AppItem>(path.join(appsDir, file));
if (app && app.status === 'published') {
appsCache.set(app.slug, app);
}
}
}
return Array.from(appsCache.values());
}
export function getAppBySlug(slug: string): AppItem | null {
getAllApps();
return appsCache.get(slug) || null;
}
export function getAppById(id: string): AppItem | null {
getAllApps();
for (const a of appsCache.values()) {
if (a.id === id) return a;
}
return null;
}
export function getAllCategories(): CategoryItem[] {
if (categoriesCache.size > 0) return Array.from(categoriesCache.values());
const dir = path.join(CONTENT_DIR, 'collections', 'categories');
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'));
for (const file of files) {
const cat = readJsonFile<CategoryItem>(path.join(dir, file));
if (cat) {
categoriesCache.set(cat.slug, cat);
}
}
}
return Array.from(categoriesCache.values());
}
export function getTemplate(name: string): any {
const filePath = path.join(CONTENT_DIR, 'templates', `${name}.json`);
return readJsonFile(filePath);
}
export function getLocaleDictionary(locale: string = 'en'): Record<string, string> {
const filePath = path.join(CONTENT_DIR, 'locales', `${locale}.json`);
const data = readJsonFile<{ system: Record<string, string> }>(filePath);
return data?.system || {};
}
export function checkIntegrity(): { valid: boolean; errors: string[] } {
const errors: string[] = [];
const tools = getAllTools();
const apps = getAllApps();
const appIds = new Set(apps.map((a) => a.id));
for (const tool of tools) {
if (!appIds.has(tool.homeApp)) {
errors.push(`Tool '${tool.id}' references missing homeApp '${tool.homeApp}'`);
}
const epId = tool.tryIt?.endpointRef?.id;
if (epId && !getEndpointById(epId)) {
errors.push(`Tool '${tool.id}' references missing endpoint '${epId}'`);
}
}
return {
valid: errors.length === 0,
errors,
};
}
+289
View File
@@ -0,0 +1,289 @@
export type Localised<T = string> = string | { [locale: string]: T };
export function resolveLocalised<T = string>(val: Localised<T> | undefined, locale = 'en', defaultVal = ''): string {
if (!val) return defaultVal;
if (typeof val === 'string') return val;
if (typeof val === 'object' && val !== null) {
if (val[locale]) return String(val[locale]);
if (val['en']) return String(val['en']);
const keys = Object.keys(val);
if (keys.length > 0) return String(val[keys[0]]);
}
return defaultVal;
}
export interface SiteConfig {
schemaVersion: string;
brand: {
name: string;
logo: string;
tagline: Localised;
};
locales: {
default: string;
supported: string[];
};
theme: {
colors: {
primary: string;
accent: string;
background: string;
text: string;
dark?: {
background: string;
text: string;
};
};
font: {
heading: string;
body: string;
};
radius: string;
maxWidth: string;
motion: boolean;
};
nav: {
header: Array<{
label: Localised;
href: string;
children?: string;
}>;
cta: {
label: Localised;
href: string;
};
};
footer: {
copyright: string;
links: Array<{
label: Localised;
href: string;
}>;
};
features: {
tryIt: boolean;
appPicker: boolean;
darkMode: boolean;
webAccounts: boolean;
webWallet: boolean;
};
seo: {
titleTemplate: string;
defaultOgImage: string;
siteUrl: string;
};
analytics?: {
provider: string;
id: string;
consent: string;
};
}
export interface SectionConfig {
id: string;
type: string;
variant?: string;
props: Record<string, any>;
visibleWhen?: {
device?: 'mobile' | 'desktop';
locale?: string;
flag?: string;
};
}
export interface PageConfig {
id: string;
route: string;
status: 'draft' | 'published' | 'archived';
seo: {
title: Localised;
description: Localised;
indexable?: boolean;
ogImage?: string;
};
sections: SectionConfig[];
}
export interface ParamSpec {
name: string;
alias?: string;
description?: string;
required: boolean;
kind: 'file' | 'string' | 'integer' | 'number' | 'boolean' | 'json' | 'unknown';
rawType: string;
default?: string;
location: 'multipart' | 'form' | 'json' | 'query' | 'header' | 'path';
isSecret: boolean;
source: 'user.file' | 'secret' | { option: string } | { constant: string };
}
export interface VariantSpec {
id: string;
method: string;
path: string;
url: string;
description?: string;
label?: Localised;
}
export interface EndpointSpec {
id: string;
groupKey?: string;
groupTitle?: string;
title: string;
summary?: string;
description?: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'MULTI';
url: string;
baseUrl: string;
path: string;
responseType: string;
params: ParamSpec[];
variants: VariantSpec[];
enabled: boolean;
publicTry: boolean;
limits: {
timeoutMs: number;
retries: number;
maxUploadMB: number;
allowedMime: string[];
rateLimit: string;
};
response: {
kind: 'binary-image' | 'json' | 'job';
delivery: 'stream' | 'signed-url';
};
hash: string;
}
export interface ToolItem {
id: string;
slug: string;
status: 'draft' | 'published' | 'archived';
category: string;
name: Localised;
summary: Localised;
homeApp: string;
alsoIn?: string[];
featured?: boolean;
tryIt: {
enabled: boolean;
endpointRef: {
id: string;
defaultVariant?: string;
};
variantControl?: {
type: 'radio' | 'tabs' | 'select';
label: Localised;
};
limits?: {
perDay: number;
maxMB: number;
maxPixels: number;
formats: string[];
};
result?: {
quality: string;
showAppCta: boolean;
};
};
content?: {
steps?: Array<{
title: Localised;
desc: Localised;
}>;
examples?: Array<{
before: string;
after: string;
alt?: Localised;
caption?: string;
}>;
faqs?: Array<{
q: string;
a: string;
}>;
};
related?: string[];
seo?: {
title: string;
description: string;
};
}
export interface AppItem {
id: string;
slug: string;
status: 'draft' | 'published' | 'archived';
name: Localised;
tagline: Localised;
description: Localised;
stores: {
android?: {
packageId: string;
url: string;
};
ios?: {
appId: string;
url: string;
};
};
deepLink?: {
base: string;
toolParam?: string;
sourceParam?: string;
bonusParam?: string;
};
tools: string[];
rating: {
value: number;
count: number;
source: string;
};
welcomeBonus?: {
code: string;
title: string;
description: string;
};
features?: string[];
creditsNote?: Localised;
}
export interface CategoryItem {
id: string;
slug: string;
name: Localised;
description: Localised;
icon?: string;
}
export type TryItResult =
| {
state: 'succeeded';
delivery: 'stream' | 'signed-url';
resultUrl?: string;
info?: { width?: number; height?: number; type: string };
durationMs?: number;
}
| {
state: 'failed';
error: { code: string; messageKey: string; message?: string; retryable: boolean };
}
| {
state: 'limit';
messageKey: string;
remainingToday?: number;
}
| {
state: 'unavailable';
messageKey: string;
};
export interface DiffReport {
timestamp: string;
addedEndpointIds: string[];
removedEndpointIds: string[];
changedEndpointIds: string[];
affectedTools: Array<{ toolId: string; toolSlug: string; issue: string }>;
misconfiguredEndpoints: string[];
totalEndpoints: number;
}