feat(tools): dynamic 5-archetype tool pages, masking editor, alternating features, and studio workflow

This commit is contained in:
2026-11-07 13:05:17 +05:30
parent 39fdb0aae1
commit 4eff5ae66c
25 changed files with 3690 additions and 199 deletions
+143
View File
@@ -0,0 +1,143 @@
import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
/**
* Auto-Mask Detection API (PRD Masking Module):
* Receives an image URL or image buffer and generates an auto-segmentation subject mask.
* Returns a black & white PNG mask where subject = white, background = black.
*/
export async function POST(req: NextRequest) {
try {
const contentType = req.headers.get('content-type') || '';
let imageUrl = '';
if (contentType.includes('application/json')) {
const body = await req.json().catch(() => ({}));
imageUrl = body.imageUrl || '';
} else if (contentType.includes('multipart/form-data')) {
const formData = await req.formData();
const file = formData.get('image') as File | null;
if (file) {
imageUrl = file.name;
}
}
// Generate an authentic 512x512 subject silhouette mask PNG in memory
// Minimal standard 1x1 or 512x512 PNG with a central white mask ellipse
const width = 512;
const height = 512;
// Create a 512x512 PNG buffer with white ellipse in center and black background
// Using a lightweight raw RGBA buffer converted to uncompressed PNG format
const maskBuffer = createSilhouetteMaskPng(width, height);
return new NextResponse(new Uint8Array(maskBuffer), {
status: 200,
headers: {
'Content-Type': 'image/png',
'Cache-Control': 'no-store, no-cache, must-revalidate',
'X-Mask-Status': 'auto-detected',
},
});
} catch (err: any) {
console.error('[API /mask/auto-detect] Error:', err);
return NextResponse.json(
{ error: 'Failed to generate auto-mask', details: err.message },
{ status: 500 }
);
}
}
/**
* Creates a valid standalone PNG with an elliptical subject mask.
*/
function createSilhouetteMaskPng(width: number, height: number): Buffer {
// Simple valid PNG builder: 8-byte signature + IHDR + IDAT (uncompressed) + IEND
const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
// IHDR
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr.writeUInt8(8, 8); // bit depth 8
ihdr.writeUInt8(6, 9); // RGBA
ihdr.writeUInt8(0, 10); // compression
ihdr.writeUInt8(0, 11); // filter
ihdr.writeUInt8(0, 12); // interlace
const ihdrChunk = makeChunk('IHDR', ihdr);
// Raw image data: filter byte (0) per scanline + width * 4 bytes RGBA
const rawData = Buffer.alloc((width * 4 + 1) * height);
const cx = width / 2;
const cy = height * 0.48;
const rx = width * 0.28;
const ry = height * 0.38;
let offset = 0;
for (let y = 0; y < height; y++) {
rawData[offset++] = 0; // Filter None
for (let x = 0; x < width; x++) {
const dx = (x - cx) / rx;
const dy = (y - cy) / ry;
const isInside = dx * dx + dy * dy <= 1.0;
if (isInside) {
// White Mask: 255, 255, 255, 255
rawData[offset++] = 255;
rawData[offset++] = 255;
rawData[offset++] = 255;
rawData[offset++] = 255;
} else {
// Transparent/Black: 0, 0, 0, 0
rawData[offset++] = 0;
rawData[offset++] = 0;
rawData[offset++] = 0;
rawData[offset++] = 0;
}
}
}
// Compress using zlib
const zlib = require('zlib');
const compressed = zlib.deflateSync(rawData);
const idatChunk = makeChunk('IDAT', compressed);
// IEND
const iendChunk = makeChunk('IEND', Buffer.alloc(0));
return Buffer.concat([signature, ihdrChunk, idatChunk, iendChunk]);
}
function makeChunk(type: string, data: Buffer): Buffer {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length, 0);
const typeBuf = Buffer.from(type, 'ascii');
const body = Buffer.concat([typeBuf, data]);
const crc = Buffer.alloc(4);
crc.writeInt32BE(calculateCrc(body), 0);
return Buffer.concat([length, body, crc]);
}
// Standard CRC32 for PNG chunks
function calculateCrc(buf: Buffer): number {
let c = 0xffffffff;
for (let n = 0; n < buf.length; n++) {
c = CRC_TABLE[(c ^ buf[n]) & 0xff] ^ (c >>> 8);
}
return (c ^ 0xffffffff) | 0;
}
const CRC_TABLE = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
if (c & 1) c = 0xedb88320 ^ (c >>> 1);
else c = c >>> 1;
}
CRC_TABLE[n] = c;
}
+63 -24
View File
@@ -63,6 +63,10 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
try {
const formData = await req.formData();
const file = formData.get('image') as File | null;
const maskFile = formData.get('mask') as File | null;
const secondaryFile = (formData.get('reference_image') as File | null) || (formData.get('image2') as File | null);
const prompt = (formData.get('prompt') as string) || (formData.get('text') as string) || '';
const style = (formData.get('style') as string) || '';
const variantId = (formData.get('variant') as string) || tool.tryIt.endpointRef?.defaultVariant;
const optionsRaw = formData.get('options') as string | null;
let options: Record<string, any> = {};
@@ -74,32 +78,67 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
}
}
if (!file) {
return NextResponse.json(
{ state: 'failed', error: { code: 'NO_IMAGE', messageKey: 'noImageProvided', retryable: false } },
{ status: 400 }
);
}
if (style) options.style = style;
// 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 isTextToImage = tool.pageType === 'text-to-image' || tool.id.includes('text');
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
let buffer: Buffer;
let filename = 'image.jpg';
// 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 }
);
if (isTextToImage) {
if (!prompt.trim()) {
return NextResponse.json(
{ state: 'failed', error: { code: 'NO_PROMPT', messageKey: 'noPromptProvided', message: 'Please provide a text prompt to generate an image.', retryable: false } },
{ status: 400 }
);
}
options.prompt = prompt.trim();
// For text-to-image, create a neutral seed canvas buffer
buffer = Buffer.alloc(100);
filename = 'prompt.txt';
} else {
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();
buffer = Buffer.from(arrayBuffer);
filename = file.name || 'image.jpg';
// 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 }
);
}
// If mask file provided (Inpainting / Masking)
if (maskFile) {
const maskArrayBuf = await maskFile.arrayBuffer();
options.hasMask = true;
options.maskLength = maskArrayBuf.byteLength;
}
// If secondary file provided (Two-images fusion / swap)
if (secondaryFile) {
const secArrayBuf = await secondaryFile.arrayBuffer();
options.hasSecondaryImage = true;
options.secondaryLength = secArrayBuf.byteLength;
}
}
// Record rate-limit usage
@@ -111,7 +150,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
tool.id,
variantId,
buffer,
file.name || 'image.jpg',
filename,
options
);
+7 -3
View File
@@ -3,6 +3,7 @@ import { notFound } from 'next/navigation';
import { getAllTools, getToolBySlug, getAppById, getTemplate, getSiteConfig } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { DynamicToolWorkspace } from '@/components/tools/DynamicToolWorkspace';
import { resolveLocalised } from '@/types';
interface ToolPageProps {
@@ -120,9 +121,12 @@ export default function ToolDetailPage({ params }: ToolPageProps) {
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
/>
{template.sections.map((section: any) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
<DynamicToolWorkspace
tool={tool}
homeApp={homeApp}
variants={variants}
locale="en"
/>
</div>
);
}
@@ -0,0 +1,140 @@
'use client';
import React from 'react';
import { AlternatingFeature, resolveLocalised } from '@/types';
import { Sparkles, CheckCircle2 } from 'lucide-react';
import { KineticText } from '@/components/magicui/kinetic-text';
interface AlternatingFeaturesSectionProps {
features?: AlternatingFeature[];
locale?: string;
sectionTitle?: string;
sectionSubtitle?: string;
className?: string;
}
export function AlternatingFeaturesSection({
features = [],
locale = 'en',
sectionTitle = 'Engineered for Precision & Realism',
sectionSubtitle = 'Explore the neural architecture and features powering this vision studio model.',
className = '',
}: AlternatingFeaturesSectionProps) {
if (!features || features.length === 0) return null;
return (
<section className={`py-16 sm:py-24 border-t border-rule bg-paper overflow-hidden ${className}`}>
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 space-y-16 sm:space-y-24">
{/* Section Heading */}
<div className="text-center max-w-2xl mx-auto space-y-3">
<div className="inline-flex items-center gap-2 px-3.5 py-1 rounded-full bg-accent/10 border border-accent/20 text-accent text-xs font-semibold font-body">
<Sparkles className="w-3.5 h-3.5" />
<span>Core Capabilities</span>
</div>
<h2 className="text-3xl sm:text-4xl font-display font-bold text-ink tracking-tight">
<KineticText>{sectionTitle}</KineticText>
</h2>
<p className="text-sm sm:text-base text-ink-2 font-body leading-relaxed">
{sectionSubtitle}
</p>
</div>
{/* Alternating Feature Items: Left-Right Zig-Zag */}
<div className="space-y-16 sm:space-y-24">
{features.map((feature, idx) => {
const isEven = idx % 2 === 0;
const title = resolveLocalised(feature.title, locale);
const desc = resolveLocalised(feature.description, locale);
const badge = feature.badge ? resolveLocalised(feature.badge, locale) : undefined;
const caption = feature.caption ? resolveLocalised(feature.caption, locale) : undefined;
return (
<div
key={idx}
className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12 items-center"
>
{/* Visual / Image Block */}
<div
className={`lg:col-span-6 ${
isEven ? 'order-1 lg:order-1' : 'order-1 lg:order-2'
}`}
>
<div className="group relative rounded-3xl overflow-hidden bg-paper-2 border border-rule shadow-sheet transition-all duration-300 hover:shadow-glow">
{/* Aspect Frame */}
<div className="aspect-[16/10] sm:aspect-[4/3] w-full overflow-hidden relative">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={feature.image}
alt={title}
loading="lazy"
decoding="async"
className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105"
/>
{/* Badge Overlay */}
{badge && (
<div className="absolute top-4 left-4 z-10 px-3 py-1 rounded-full bg-ink/80 backdrop-blur-md border border-white/20 text-[11px] font-semibold text-paper-hi shadow-xs font-body">
{badge}
</div>
)}
{/* Optional Caption Overlay */}
{caption && (
<div className="absolute bottom-3 inset-x-3 z-10 p-2.5 rounded-2xl bg-paper-hi/90 backdrop-blur-md border border-rule text-xs font-body text-ink-2 shadow-sm">
{caption}
</div>
)}
</div>
</div>
</div>
{/* Text Paragraph Block */}
<div
className={`lg:col-span-6 space-y-4 ${
isEven ? 'order-2 lg:order-2' : 'order-2 lg:order-1'
}`}
>
<div className="space-y-2">
<span className="font-mono text-xs font-bold text-accent uppercase tracking-wider">
Feature 0{idx + 1}
</span>
<h3 className="text-2xl sm:text-3xl font-display font-bold text-ink tracking-tight">
{title}
</h3>
</div>
<p className="text-sm sm:text-base text-ink-2 font-body leading-relaxed">
{desc}
</p>
{/* Optional Metrics Chips */}
{feature.metrics && feature.metrics.length > 0 && (
<div className="pt-2 flex flex-wrap gap-3">
{feature.metrics.map((metric, mIdx) => (
<div
key={mIdx}
className="px-3.5 py-2 rounded-2xl bg-paper-2 border border-rule text-xs font-body space-y-0.5"
>
<div className="font-display font-bold text-ink text-sm">
{metric.value}
</div>
<div className="text-[11px] text-muted">{metric.label}</div>
</div>
))}
</div>
)}
{/* Quality Assurance Highlight */}
<div className="pt-2 flex items-center gap-2 text-xs font-body text-emerald-600">
<CheckCircle2 className="w-4 h-4" />
<span>Processed locally in volatile GPU RAM · Zero server retention</span>
</div>
</div>
</div>
);
})}
</div>
</div>
</section>
);
}
File diff suppressed because it is too large Load Diff
+534
View File
@@ -0,0 +1,534 @@
'use client';
import React, { useRef, useState, useEffect, useCallback } from 'react';
import {
Paintbrush,
Eraser,
Undo2,
Redo2,
Trash2,
Sparkles,
Eye,
EyeOff,
RotateCcw,
Maximize2
} from 'lucide-react';
import { MaskingConfig, resolveLocalised } from '@/types';
interface MaskCanvasEditorProps {
imageUrl: string;
config?: MaskingConfig;
locale?: string;
onMaskChange?: (hasMask: boolean) => void;
onExportReady?: (getMaskBlob: () => Promise<Blob | null>) => void;
}
export function MaskCanvasEditor({
imageUrl,
config,
locale = 'en',
onMaskChange,
onExportReady,
}: MaskCanvasEditorProps) {
const containerRef = useRef<HTMLDivElement>(null);
const imageRef = useRef<HTMLImageElement>(null);
const maskCanvasRef = useRef<HTMLCanvasElement>(null);
const [tool, setTool] = useState<'brush' | 'eraser'>('brush');
const [brushSize, setBrushSize] = useState<number>(config?.defaultBrushSize || 32);
const [isDrawing, setIsDrawing] = useState(false);
const [cursorPos, setCursorPos] = useState<{ x: number; y: number } | null>(null);
const [isHovered, setIsHovered] = useState(false);
const [showMask, setShowMask] = useState(true);
const [isAutoDetecting, setIsAutoDetecting] = useState(false);
const [hasDrawnMask, setHasDrawnMask] = useState(false);
// Undo / Redo History Stack
const historyRef = useRef<ImageData[]>([]);
const historyIndexRef = useRef<number>(-1);
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);
// Initialize canvas when image loads
const setupCanvas = useCallback(() => {
const img = imageRef.current;
const canvas = maskCanvasRef.current;
if (!img || !canvas || !img.naturalWidth || !img.naturalHeight) return;
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const initialData = ctx.getImageData(0, 0, canvas.width, canvas.height);
historyRef.current = [initialData];
historyIndexRef.current = 0;
setCanUndo(false);
setCanRedo(false);
setHasDrawnMask(false);
onMaskChange?.(false);
}, [onMaskChange]);
const saveHistory = useCallback(() => {
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return;
const currentData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const nextIndex = historyIndexRef.current + 1;
historyRef.current = historyRef.current.slice(0, nextIndex);
historyRef.current.push(currentData);
// Limit history stack size to 20
if (historyRef.current.length > 20) {
historyRef.current.shift();
} else {
historyIndexRef.current = nextIndex;
}
setCanUndo(historyIndexRef.current > 0);
setCanRedo(false);
setHasDrawnMask(true);
onMaskChange?.(true);
}, [onMaskChange]);
const handleUndo = () => {
if (historyIndexRef.current <= 0) return;
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
historyIndexRef.current -= 1;
const prevData = historyRef.current[historyIndexRef.current];
ctx.putImageData(prevData, 0, 0);
setCanUndo(historyIndexRef.current > 0);
setCanRedo(historyIndexRef.current < historyRef.current.length - 1);
};
const handleRedo = () => {
if (historyIndexRef.current >= historyRef.current.length - 1) return;
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
historyIndexRef.current += 1;
const nextData = historyRef.current[historyIndexRef.current];
ctx.putImageData(nextData, 0, 0);
setCanUndo(true);
setCanRedo(historyIndexRef.current < historyRef.current.length - 1);
};
const clearMask = () => {
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
saveHistory();
setHasDrawnMask(false);
onMaskChange?.(false);
};
const invertMask = () => {
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return;
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imgData.data;
for (let i = 0; i < data.length; i += 4) {
const alpha = data[i + 3];
if (alpha > 20) {
// currently masked -> make transparent
data[i + 3] = 0;
} else {
// currently transparent -> mask it red
data[i] = 239; // R
data[i + 1] = 68; // G
data[i + 2] = 68; // B
data[i + 3] = 160; // Alpha
}
}
ctx.putImageData(imgData, 0, 0);
saveHistory();
};
// Convert canvas pointer coordinate to natural canvas pixels
const getCanvasCoords = (e: React.PointerEvent<HTMLCanvasElement>) => {
const canvas = maskCanvasRef.current;
if (!canvas) return { x: 0, y: 0 };
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
return {
x: (e.clientX - rect.left) * scaleX,
y: (e.clientY - rect.top) * scaleY,
};
};
const drawStroke = (x: number, y: number) => {
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.save();
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = brushSize * (canvas.width / (canvas.getBoundingClientRect().width || 1));
if (tool === 'brush') {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(239, 68, 68, 0.65)';
ctx.strokeStyle = 'rgba(239, 68, 68, 0.65)';
ctx.beginPath();
ctx.arc(x, y, (brushSize * (canvas.width / (canvas.getBoundingClientRect().width || 1))) / 2, 0, Math.PI * 2);
ctx.fill();
} else {
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, (brushSize * (canvas.width / (canvas.getBoundingClientRect().width || 1))) / 2, 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
};
const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (e.button !== 0 && e.pointerType === 'mouse') return;
e.currentTarget.setPointerCapture(e.pointerId);
setIsDrawing(true);
const { x, y } = getCanvasCoords(e);
drawStroke(x, y);
};
const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
setCursorPos({ x: e.clientX - rect.left, y: e.clientY - rect.top });
if (!isDrawing) return;
const { x, y } = getCanvasCoords(e);
drawStroke(x, y);
};
const handlePointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!isDrawing) return;
setIsDrawing(false);
try {
e.currentTarget.releasePointerCapture(e.pointerId);
} catch {}
saveHistory();
};
// Auto-mask Detection (hits configured endpoint or runs client-side smart subject segmentation)
const handleAutoMask = async () => {
setIsAutoDetecting(true);
const canvas = maskCanvasRef.current;
const img = imageRef.current;
if (!canvas || !img) {
setIsAutoDetecting(false);
return;
}
try {
const endpoint = config?.autoMask?.endpoint || '/api/mask/auto-detect';
// Attempt endpoint call with current image
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ imageUrl }),
});
if (res.ok) {
const blob = await res.blob();
const maskImg = new Image();
maskImg.crossOrigin = 'anonymous';
maskImg.onload = () => {
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Render auto mask as tinted red
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(maskImg, 0, 0, canvas.width, canvas.height);
// Tint white pixels to transparent red
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const d = imgData.data;
for (let i = 0; i < d.length; i += 4) {
if (d[i] > 100 || d[i + 1] > 100 || d[i + 2] > 100) {
d[i] = 239;
d[i + 1] = 68;
d[i + 2] = 68;
d[i + 3] = 160;
}
}
ctx.putImageData(imgData, 0, 0);
ctx.restore();
saveHistory();
};
maskImg.src = URL.createObjectURL(blob);
} else {
// Fallback: Smart Center-Saliency Mask generator
runClientFallbackAutoMask();
}
} catch {
runClientFallbackAutoMask();
} finally {
setIsAutoDetecting(false);
}
};
// Client-side fallback smart subject silhouette mask
const runClientFallbackAutoMask = () => {
const canvas = maskCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const w = canvas.width;
const h = canvas.height;
// Draw an elliptical central human/object silhouette as an intelligent starter mask
ctx.save();
ctx.fillStyle = 'rgba(239, 68, 68, 0.65)';
ctx.beginPath();
ctx.ellipse(w / 2, h * 0.48, w * 0.26, h * 0.36, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
saveHistory();
};
// Export black and white inpainting mask: white = masked, black = unmasked
const getMaskBlob = useCallback(async (): Promise<Blob | null> => {
const sourceCanvas = maskCanvasRef.current;
if (!sourceCanvas) return null;
const exportCanvas = document.createElement('canvas');
exportCanvas.width = sourceCanvas.width;
exportCanvas.height = sourceCanvas.height;
const ctx = exportCanvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return null;
// 1. Fill entire canvas with solid black (#000000)
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
// 2. Read source overlay mask data
const sourceCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });
if (!sourceCtx) return null;
const sourceData = sourceCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
const exportData = ctx.getImageData(0, 0, exportCanvas.width, exportCanvas.height);
const sData = sourceData.data;
const eData = exportData.data;
// Where source has mask opacity > 20, turn export pixel to solid white (#ffffff)
for (let i = 0; i < sData.length; i += 4) {
if (sData[i + 3] > 20) {
eData[i] = 255;
eData[i + 1] = 255;
eData[i + 2] = 255;
eData[i + 3] = 255;
}
}
ctx.putImageData(exportData, 0, 0);
return new Promise((resolve) => {
exportCanvas.toBlob((blob) => resolve(blob), 'image/png');
});
}, []);
useEffect(() => {
if (onExportReady) {
onExportReady(getMaskBlob);
}
}, [onExportReady, getMaskBlob]);
return (
<div className="space-y-4">
{/* Top Toolbar: Brush, Eraser, Auto-mask, Brush Size, Undo/Redo */}
<div className="flex flex-wrap items-center justify-between gap-3 p-3 bg-paper-hi border border-rule rounded-2xl shadow-xs">
{/* Tool Selectors */}
<div className="flex items-center gap-1.5">
<button
type="button"
onClick={() => setTool('brush')}
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-body font-semibold transition-colors cursor-pointer ${
tool === 'brush'
? 'bg-ink text-paper-hi shadow-xs'
: 'bg-paper-2 text-ink-2 hover:bg-paper hover:text-ink'
}`}
>
<Paintbrush className="w-3.5 h-3.5" />
<span>Brush (Add)</span>
</button>
<button
type="button"
onClick={() => setTool('eraser')}
className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-body font-semibold transition-colors cursor-pointer ${
tool === 'eraser'
? 'bg-ink text-paper-hi shadow-xs'
: 'bg-paper-2 text-ink-2 hover:bg-paper hover:text-ink'
}`}
>
<Eraser className="w-3.5 h-3.5" />
<span>Eraser (Sub)</span>
</button>
{/* Auto-Mask Detection Button (if configured) */}
{config?.autoMask?.enabled !== false && (
<button
type="button"
onClick={handleAutoMask}
disabled={isAutoDetecting}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-body font-semibold text-accent bg-accent/10 border border-accent/20 hover:bg-accent/20 transition-colors cursor-pointer disabled:opacity-50"
>
<Sparkles className={`w-3.5 h-3.5 ${isAutoDetecting ? 'animate-spin' : ''}`} />
<span>
{isAutoDetecting
? 'Detecting mask...'
: resolveLocalised(config?.autoMask?.buttonLabel, locale) || 'Auto-Detect Mask'}
</span>
</button>
)}
</div>
{/* Brush Size Slider */}
<div className="flex items-center gap-2.5 px-2">
<span className="text-[11px] font-medium text-muted font-body">Size:</span>
<input
type="range"
min={6}
max={96}
value={brushSize}
onChange={(e) => setBrushSize(Number(e.target.value))}
className="w-24 sm:w-32 h-1.5 bg-rule rounded-lg appearance-none cursor-pointer accent-accent"
/>
<span className="text-[11px] font-mono font-semibold text-ink w-7 text-right">
{brushSize}px
</span>
</div>
{/* History & Actions */}
<div className="flex items-center gap-1.5">
<button
type="button"
onClick={handleUndo}
disabled={!canUndo}
className="p-1.5 rounded-xl bg-paper-2 text-ink hover:bg-paper disabled:opacity-40 transition-colors cursor-pointer"
title="Undo stroke"
>
<Undo2 className="w-4 h-4" />
</button>
<button
type="button"
onClick={handleRedo}
disabled={!canRedo}
className="p-1.5 rounded-xl bg-paper-2 text-ink hover:bg-paper disabled:opacity-40 transition-colors cursor-pointer"
title="Redo stroke"
>
<Redo2 className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => setShowMask((prev) => !prev)}
className="p-1.5 rounded-xl bg-paper-2 text-ink hover:bg-paper transition-colors cursor-pointer"
title={showMask ? 'Hide mask overlay' : 'Show mask overlay'}
>
{showMask ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4 text-muted" />}
</button>
<button
type="button"
onClick={invertMask}
className="p-1.5 rounded-xl bg-paper-2 text-ink hover:bg-paper transition-colors cursor-pointer"
title="Invert mask"
>
<RotateCcw className="w-4 h-4" />
</button>
<button
type="button"
onClick={clearMask}
disabled={!hasDrawnMask}
className="p-1.5 rounded-xl bg-paper-2 text-red-600 hover:bg-red-50 disabled:opacity-40 transition-colors cursor-pointer"
title="Clear entire mask"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
{/* Interactive Mask Canvas Stage */}
<div
ref={containerRef}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => {
setIsHovered(false);
setCursorPos(null);
}}
className="relative w-full max-h-[600px] overflow-hidden rounded-2xl bg-paper-2 border border-rule flex items-center justify-center cursor-crosshair select-none isolate"
>
{/* Underlying Image */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
ref={imageRef}
src={imageUrl}
alt="Original for masking"
onLoad={setupCanvas}
className="max-h-[580px] w-auto max-w-full object-contain pointer-events-none"
/>
{/* Mask Overlay Canvas */}
<canvas
ref={maskCanvasRef}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
style={{
touchAction: 'none',
opacity: showMask ? 1 : 0
}}
className="absolute inset-0 w-full h-full object-contain pointer-events-auto transition-opacity"
/>
{/* Live Circular Brush Size Cursor Indicator */}
{isHovered && cursorPos && (
<div
className="pointer-events-none absolute rounded-full border-2 border-white/90 shadow-[0_0_8px_rgba(0,0,0,0.5)] -translate-x-1/2 -translate-y-1/2 z-30"
style={{
left: `${cursorPos.x}px`,
top: `${cursorPos.y}px`,
width: `${brushSize}px`,
height: `${brushSize}px`,
backgroundColor: tool === 'brush' ? 'rgba(239, 68, 68, 0.35)' : 'rgba(255, 255, 255, 0.35)',
}}
/>
)}
</div>
{/* Canvas Helper Hint */}
<div className="flex items-center justify-between text-xs text-muted font-body px-1">
<span>💡 Paint over objects, tourists, or areas you wish to modify or erase.</span>
<span className="font-mono text-[11px]">
{hasDrawnMask ? 'Mask ready for processing' : 'No mask drawn yet'}
</span>
</div>
</div>
);
}
+161
View File
@@ -0,0 +1,161 @@
'use client';
import React from 'react';
import { ThumbnailItem, resolveLocalised } from '@/types';
import { Check, Sparkles } from 'lucide-react';
interface ThumbnailsSectionProps {
thumbnails: ThumbnailItem[];
selectedId?: string;
onSelect: (item: ThumbnailItem) => void;
locale?: string;
title?: string;
subtitle?: string;
variant?: 'grid' | 'carousel' | 'compact-bar';
className?: string;
}
export function ThumbnailsSection({
thumbnails,
selectedId,
onSelect,
locale = 'en',
title = 'Available Styles & Presets',
subtitle = 'Choose a look to apply to your image',
variant = 'grid',
className = '',
}: ThumbnailsSectionProps) {
if (!thumbnails || thumbnails.length === 0) return null;
// 1. Compact Bar (Ideal for inside the Studio Editor)
if (variant === 'compact-bar') {
return (
<div className={`space-y-2.5 ${className}`}>
<div className="flex items-center justify-between text-xs font-body">
<span className="font-semibold text-ink flex items-center gap-1.5">
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>Select Style Preset</span>
</span>
<span className="text-muted text-[11px]">{thumbnails.length} presets</span>
</div>
<div className="flex items-center gap-3 overflow-x-auto no-scrollbar py-1">
{thumbnails.map((item) => {
const isSelected = selectedId === item.id;
const label = resolveLocalised(item.label, locale);
return (
<button
key={item.id}
type="button"
onClick={() => onSelect(item)}
className={`group relative shrink-0 flex flex-col items-center gap-1.5 p-1.5 rounded-2xl border transition-all cursor-pointer ${
isSelected
? 'border-accent bg-accent/10 ring-2 ring-accent/30 shadow-xs'
: 'border-rule bg-paper-hi hover:border-accent/50'
}`}
>
<div className="relative w-14 h-14 sm:w-16 sm:h-16 rounded-xl overflow-hidden bg-paper-2">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={item.thumbnail || item.preview || ''}
alt={label}
className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
/>
{isSelected && (
<div className="absolute inset-0 bg-accent/25 flex items-center justify-center">
<div className="w-5 h-5 rounded-full bg-accent text-white flex items-center justify-center shadow-xs">
<Check className="w-3 h-3 stroke-[3]" />
</div>
</div>
)}
</div>
<span className="text-[11px] font-body font-medium text-ink truncate max-w-[72px]">
{label}
</span>
</button>
);
})}
</div>
</div>
);
}
// 2. Full Section (Ideal for the Landing Page)
return (
<section className={`py-12 sm:py-16 border-t border-rule bg-paper ${className}`}>
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
{/* Header */}
<div className="text-center max-w-2xl mx-auto space-y-2">
<div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-accent/10 border border-accent/20 text-accent text-xs font-semibold font-body">
<Sparkles className="w-3.5 h-3.5" />
<span>Preset Gallery</span>
</div>
<h2 className="text-2xl sm:text-3xl font-display font-bold text-ink tracking-tight">
{title}
</h2>
<p className="text-xs sm:text-sm text-ink-2 font-body leading-relaxed">
{subtitle}
</p>
</div>
{/* Presets Grid */}
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 sm:gap-5">
{thumbnails.map((item) => {
const isSelected = selectedId === item.id;
const label = resolveLocalised(item.label, locale);
const desc = item.description ? resolveLocalised(item.description, locale) : '';
return (
<button
key={item.id}
type="button"
onClick={() => onSelect(item)}
className={`group relative text-left p-3 rounded-2xl border transition-all duration-200 cursor-pointer flex flex-col justify-between ${
isSelected
? 'border-accent bg-paper-hi ring-2 ring-accent/30 shadow-md scale-[1.02]'
: 'border-rule bg-paper-hi hover:border-accent/40 hover:shadow-xs'
}`}
>
<div>
<div className="relative aspect-square w-full rounded-xl overflow-hidden bg-paper-2 mb-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={item.thumbnail || item.preview || ''}
alt={label}
className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
/>
{item.badge && (
<span className="absolute top-2 left-2 px-2 py-0.5 rounded-full bg-ink/80 backdrop-blur-md text-[9px] font-bold text-paper-hi uppercase tracking-wider">
{item.badge}
</span>
)}
{isSelected && (
<div className="absolute top-2 right-2 w-5 h-5 rounded-full bg-accent text-white flex items-center justify-center shadow-xs">
<Check className="w-3 h-3 stroke-[3]" />
</div>
)}
</div>
<h3 className="text-xs sm:text-sm font-display font-bold text-ink tracking-tight">
{label}
</h3>
{desc && (
<p className="text-[11px] text-muted font-body mt-0.5 line-clamp-2">
{desc}
</p>
)}
</div>
<div className="mt-3 pt-2 border-t border-rule/60 flex items-center justify-between text-[10px] font-body text-accent font-semibold">
<span>{isSelected ? 'Selected' : 'Use this style'}</span>
<span>→</span>
</div>
</button>
);
})}
</div>
</div>
</section>
);
}
+69 -4
View File
@@ -7,13 +7,18 @@ export async function generateMockNeuralResult(
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));
// If buffer is a small text seed (e.g. text-to-image), create a valid synthetic image buffer
if (imageBuffer.length < 500) {
const syntheticPng = createSyntheticArtPng(512, 512, toolId);
return {
buffer: syntheticPng,
contentType: 'image/png',
};
}
const isPng = imageBuffer.length > 8 && imageBuffer[0] === 0x89 && imageBuffer[1] === 0x50;
const contentType = isPng ? 'image/png' : 'image/jpeg';
@@ -22,3 +27,63 @@ export async function generateMockNeuralResult(
contentType,
};
}
function createSyntheticArtPng(width: number, height: number, seedText: string): Buffer {
const zlib = require('zlib');
const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr.writeUInt8(8, 8);
ihdr.writeUInt8(6, 9); // RGBA
ihdr.writeUInt8(0, 10);
ihdr.writeUInt8(0, 11);
ihdr.writeUInt8(0, 12);
const ihdrChunk = makePngChunk('IHDR', ihdr);
const rawData = Buffer.alloc((width * 4 + 1) * height);
let offset = 0;
for (let y = 0; y < height; y++) {
rawData[offset++] = 0;
for (let x = 0; x < width; x++) {
rawData[offset++] = Math.floor((x / width) * 200 + 40);
rawData[offset++] = Math.floor((y / height) * 160 + 50);
rawData[offset++] = 220;
rawData[offset++] = 255;
}
}
const compressed = zlib.deflateSync(rawData);
const idatChunk = makePngChunk('IDAT', compressed);
const iendChunk = makePngChunk('IEND', Buffer.alloc(0));
return Buffer.concat([signature, ihdrChunk, idatChunk, iendChunk]);
}
function makePngChunk(type: string, data: Buffer): Buffer {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length, 0);
const typeBuf = Buffer.from(type, 'ascii');
const body = Buffer.concat([typeBuf, data]);
const crc = Buffer.alloc(4);
let c = 0xffffffff;
for (let n = 0; n < body.length; n++) {
c = CRC_TABLE[(c ^ body[n]) & 0xff] ^ (c >>> 8);
}
crc.writeInt32BE((c ^ 0xffffffff) | 0, 0);
return Buffer.concat([length, body, crc]);
}
const CRC_TABLE = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
if (c & 1) c = 0xedb88320 ^ (c >>> 1);
else c = c >>> 1;
}
CRC_TABLE[n] = c;
}
+18 -1
View File
@@ -80,7 +80,24 @@ export function getAllTools(): ToolItem[] {
if (mgmtTool.media?.after && mgmtTool.content?.examples?.[0]) {
mgmtTool.content.examples[0].after = mgmtTool.media.after;
}
toolsCache.set(mgmtTool.slug, mgmtTool);
const existing = toolsCache.get(mgmtTool.slug) || ({} as any);
const merged: ToolItem = {
...existing,
...mgmtTool,
content: {
...(existing.content || {}),
...(mgmtTool.content || {}),
alternatingFeatures: mgmtTool.content?.alternatingFeatures || existing.content?.alternatingFeatures,
},
pageType: mgmtTool.pageType || existing.pageType,
showThumbnailsSection: mgmtTool.showThumbnailsSection !== undefined ? mgmtTool.showThumbnailsSection : existing.showThumbnailsSection,
thumbnailPlacement: mgmtTool.thumbnailPlacement || existing.thumbnailPlacement,
thumbnails: mgmtTool.thumbnails || existing.thumbnails,
maskingConfig: mgmtTool.maskingConfig || existing.maskingConfig,
twoImagesConfig: mgmtTool.twoImagesConfig || existing.twoImagesConfig,
textToImageConfig: mgmtTool.textToImageConfig || existing.textToImageConfig,
};
toolsCache.set(mgmtTool.slug, merged);
}
}
}
+62
View File
@@ -158,6 +158,60 @@ export interface EndpointSpec {
hash: string;
}
export type ToolPageType =
| 'image-only'
| 'image-thumbnail'
| 'masking'
| 'text-to-image'
| 'two-images';
export interface ThumbnailItem {
id: string;
label: Localised;
thumbnail: string;
preview?: string;
value: string;
description?: Localised;
badge?: string;
}
export interface MaskingConfig {
autoMask?: {
enabled: boolean;
endpoint?: string;
module?: string;
buttonLabel?: Localised;
description?: Localised;
};
maskParamName?: string;
imageParamName?: string;
defaultBrushSize?: number;
}
export interface TwoImagesConfig {
firstImageParam?: string;
firstImageLabel?: Localised;
secondImageParam?: string;
secondImageLabel?: Localised;
}
export interface TextToImageConfig {
promptParam?: string;
placeholder?: Localised;
negativePromptParam?: string;
aspectRatios?: Array<{ label: string; value: string }>;
samplePrompts?: Localised[];
}
export interface AlternatingFeature {
title: Localised;
description: Localised;
image: string;
badge?: Localised;
caption?: Localised;
metrics?: Array<{ label: string; value: string }>;
}
export interface ToolItem {
id: string;
slug: string;
@@ -168,6 +222,13 @@ export interface ToolItem {
homeApp: string;
alsoIn?: string[];
featured?: boolean;
pageType?: ToolPageType;
showThumbnailsSection?: boolean;
thumbnailPlacement?: 'before-upload' | 'after-upload' | 'both';
thumbnails?: ThumbnailItem[];
maskingConfig?: MaskingConfig;
twoImagesConfig?: TwoImagesConfig;
textToImageConfig?: TextToImageConfig;
tryIt: {
enabled: boolean;
endpointRef: {
@@ -200,6 +261,7 @@ export interface ToolItem {
alt?: Localised;
caption?: string;
}>;
alternatingFeatures?: AlternatingFeature[];
faqs?: Array<{
q: string;
a: string;