Files
SnapOtter/apps/web/src/components/tools/vectorize-settings.tsx
T
a1e11dff74 feat(gif-tools): SOTA upgrade with 6 processing modes (#52)
* feat(find-duplicates): upgrade to 128-bit dHash with metadata and thumbnails

* feat(find-duplicates): add custom-results display mode and duplicate store

* feat(find-duplicates): add results overview grid and detail comparison view

* feat(find-duplicates): overhaul settings with sensitivity presets and download actions

* feat(find-duplicates): update i18n description

* chore: replace jsqr with zxing-wasm for barcode reading

* feat(barcode-read): rewrite backend with zxing-wasm for all barcode types

* feat(barcode-read): rewrite frontend with multi-file, results table, progress, export

- Multi-file sequential processing with per-file progress
- Structured results table with type badges and copy per-result
- Copy All and Export CSV functionality
- Thorough scan toggle (maps to tryHarder in zxing-wasm)
- Before/after view shows annotated image with bounding boxes
- Updated tool description in constants and i18n

* feat(stitch): update tool name and description for redesign

* feat(stitch): add grid layout, alignment, border, radius, quality, and new resize modes

* feat(stitch): redesign settings UI with grid, alignment, border, radius, quality

* test(stitch): add stitch to e2e tool navigation suite

* feat(vectorize): redesign with dual-engine backend and preset-driven UI

- Backend: potrace for B&W, VTracer (@neplex/vectorizer) for full-color vectorization
- Frontend: 5 presets (logo, illustration, photo, sketch, custom)
- Settings: color precision, gradient step, detail, smoothing, corner threshold, invert
- Updated OpenAPI spec and i18n description

* feat(border): redesign with presets, shadow, padding color, swatches

- Add 8 one-click presets (Clean White, Gallery Black, Shadow, Rounded, Polaroid, Vintage, Minimal, Cinematic)
- Implement proper shadow rendering with blur, offset X/Y, color, opacity
- Add padding color control (was hardcoded white)
- Add color swatches for quick color selection
- Wrap in form for Enter key submission
- Add smart validation (requires at least one effect active)
- Align frontend/backend slider ranges
- Organize UI with sections and collapsible shadow toggle

* feat(split): overhaul image splitting with live grid overlay and tile preview

- Add interactive-split display mode with SplitCanvas component
- Live SVG grid overlay on uploaded image showing split boundaries
- Two split modes: Grid (NxM) and Tile Size (px dimensions)
- 9 grid presets (2x1, 1x2, 2x2, 3x1, 1x3, 3x3, 2x3, 3x2, 4x4)
- Output format selection (original/PNG/JPG/WebP) with quality slider
- Post-split tile preview thumbnails with individual download
- Download All as ZIP button
- HEIC/HEIF preview with loading spinner
- Backend: tile-size mode, output format conversion, quality control
- Zustand store for split state management

* feat(split): rewrite backend and frontend settings

Backend: tile-size mode, output format conversion, quality control.
Frontend: split modes, presets, format selector, tile preview grid.

* feat(border): add live CSS preview and remove before/after slider

- Add imageWrapperStyle prop to ImageViewer for live border preview
- Add onImageStyle callback through tool-page to settings components
- Change border displayMode to no-comparison (no slider)
- BorderControls sends live CSS styles (border, padding, radius, shadow)
- Preview updates instantly as user adjusts sliders or clicks presets

* fix: repair i18n file corrupted by formatter during merge conflict resolution

* feat(border): enable live CSS preview in right pane as settings change

* fix(border): keep CSS preview visible after processing for WYSIWYG consistency

* chore(gif-tools): scaffold for SOTA upgrade

- Add animated GIF test fixture (3 frames, 100x100)
- Update tool description to reflect new capabilities
- Add fflate dependency to API for ZIP creation

* feat(gif-tools): rewrite backend with 6 processing modes

Modes: resize (with percentage), optimize (colors/dither/effort),
speed (delay manipulation), reverse (frame reorder), extract
(single/range/all with ZIP), rotate (90/180/270 + flip).

Adds /api/v1/tools/gif-tools/info metadata endpoint.

* test(gif-tools): add integration tests for all 6 modes

Tests metadata endpoint, resize (pixel + percentage), optimize,
speed, reverse, extract (single/range/all), and rotate (angle + flip).

Fix animated.gif fixture to be a real 3-frame animation (was a single
100x300 frame). Fix reverse and rotate modes to process frames
individually and reassemble via GIF binary concatenation, since
Sharp 0.33.x loses page-height metadata when reconstructing from raw
pixel data.

* feat(gif-tools): rewrite frontend with tabbed 6-mode UI

- useGifInfo hook for metadata (frame count, dimensions, duration)
- Info bar showing GIF properties
- 3x2 mode grid: Resize, Optimize, Speed, Reverse, Extract, Rotate
- Animation modes disabled for static images
- Loop control (infinite/once/custom)
- Batch processing support

* test(gif-tools): add to representative tools in e2e suite

---------

Co-authored-by: Siddharth Kumar Sah <siddharth123sk@gmail.com>
2026-04-13 16:23:07 +08:00

402 lines
13 KiB
TypeScript

import { Download, Loader2 } from "lucide-react";
import { useState } from "react";
import { formatHeaders } from "@/lib/api";
import { useFileStore } from "@/stores/file-store";
type ColorMode = "bw" | "color";
type PathMode = "none" | "polygon" | "spline";
type Detail = "low" | "medium" | "high";
type Preset = "logo" | "illustration" | "photo" | "sketch" | "custom";
interface VectorizeState {
colorMode: ColorMode;
threshold: number;
colorPrecision: number;
layerDifference: number;
filterSpeckle: number;
pathMode: PathMode;
cornerThreshold: number;
invert: boolean;
}
const PRESET_SETTINGS: Record<Exclude<Preset, "custom">, VectorizeState> = {
logo: {
colorMode: "bw",
threshold: 128,
colorPrecision: 6,
layerDifference: 6,
filterSpeckle: 2,
pathMode: "spline",
cornerThreshold: 60,
invert: false,
},
illustration: {
colorMode: "color",
threshold: 128,
colorPrecision: 4,
layerDifference: 16,
filterSpeckle: 8,
pathMode: "spline",
cornerThreshold: 60,
invert: false,
},
photo: {
colorMode: "color",
threshold: 128,
colorPrecision: 8,
layerDifference: 5,
filterSpeckle: 4,
pathMode: "spline",
cornerThreshold: 60,
invert: false,
},
sketch: {
colorMode: "bw",
threshold: 100,
colorPrecision: 6,
layerDifference: 6,
filterSpeckle: 1,
pathMode: "polygon",
cornerThreshold: 60,
invert: false,
},
};
const DETAIL_TO_SPECKLE: Record<Detail, number> = { low: 16, medium: 4, high: 1 };
function speckleToDetail(speckle: number): Detail {
if (speckle >= 10) return "low";
if (speckle >= 3) return "medium";
return "high";
}
export function VectorizeSettings() {
const { files, processing, error, setProcessing, setError, setProcessedUrl, setSizes, setJobId } =
useFileStore();
const [preset, setPreset] = useState<Preset>("logo");
const [colorMode, setColorMode] = useState<ColorMode>("bw");
const [threshold, setThreshold] = useState(128);
const [colorPrecision, setColorPrecision] = useState(6);
const [layerDifference, setLayerDifference] = useState(6);
const [filterSpeckle, setFilterSpeckle] = useState(2);
const [pathMode, setPathMode] = useState<PathMode>("spline");
const [cornerThreshold, setCornerThreshold] = useState(60);
const [invert, setInvert] = useState(false);
const [downloadUrl, setDownloadUrl] = useState<string | null>(null);
const [originalSize, setOriginalSize] = useState<number | null>(null);
const [processedSize, setProcessedSize] = useState<number | null>(null);
const applyPreset = (p: Preset) => {
setPreset(p);
if (p === "custom") return;
const s = PRESET_SETTINGS[p];
setColorMode(s.colorMode);
setThreshold(s.threshold);
setColorPrecision(s.colorPrecision);
setLayerDifference(s.layerDifference);
setFilterSpeckle(s.filterSpeckle);
setPathMode(s.pathMode);
setCornerThreshold(s.cornerThreshold);
setInvert(s.invert);
};
const updateSetting = <T,>(setter: (v: T) => void) => {
return (v: T) => {
setPreset("custom");
setter(v);
};
};
const handleProcess = async () => {
if (files.length === 0) return;
setProcessing(true);
setError(null);
setDownloadUrl(null);
try {
const formData = new FormData();
formData.append("file", files[0]);
formData.append(
"settings",
JSON.stringify({
colorMode,
threshold,
colorPrecision,
layerDifference,
filterSpeckle,
pathMode,
cornerThreshold,
invert,
}),
);
const res = await fetch("/api/v1/tools/vectorize", {
method: "POST",
headers: formatHeaders(),
body: formData,
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || `Failed: ${res.status}`);
}
const result = await res.json();
setJobId(result.jobId);
setProcessedUrl(result.downloadUrl);
setDownloadUrl(result.downloadUrl);
setOriginalSize(result.originalSize);
setProcessedSize(result.processedSize);
setSizes(result.originalSize, result.processedSize);
} catch (err) {
setError(err instanceof Error ? err.message : "Vectorization failed");
} finally {
setProcessing(false);
}
};
const hasFile = files.length > 0;
const detail = speckleToDetail(filterSpeckle);
return (
<div className="space-y-4">
{/* Preset */}
<div>
<p className="text-xs text-muted-foreground">Preset</p>
<div className="grid grid-cols-3 gap-1 mt-1">
{(["logo", "illustration", "photo"] as const).map((p) => (
<button
type="button"
key={p}
onClick={() => applyPreset(p)}
className={`capitalize text-xs py-1.5 rounded ${preset === p ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
>
{p}
</button>
))}
</div>
<div className="grid grid-cols-2 gap-1 mt-1">
{(["sketch", "custom"] as const).map((p) => (
<button
type="button"
key={p}
onClick={() => applyPreset(p)}
className={`capitalize text-xs py-1.5 rounded ${preset === p ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
>
{p}
</button>
))}
</div>
</div>
<div className="border-t border-border" />
{/* Color Mode */}
<div>
<p className="text-xs text-muted-foreground">Color Mode</p>
<div className="flex gap-1 mt-1">
{(["bw", "color"] as const).map((m) => (
<button
type="button"
key={m}
onClick={() => updateSetting(setColorMode)(m)}
className={`flex-1 text-xs py-1.5 rounded ${colorMode === m ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
>
{m === "bw" ? "Black & White" : "Color"}
</button>
))}
</div>
</div>
{/* Color-specific settings */}
{colorMode === "color" && (
<>
<div>
<div className="flex justify-between items-center">
<label htmlFor="vectorize-color-precision" className="text-xs text-muted-foreground">
Color Precision
</label>
<span className="text-xs font-mono text-foreground">{colorPrecision}</span>
</div>
<input
id="vectorize-color-precision"
type="range"
min={1}
max={8}
value={colorPrecision}
onChange={(e) => updateSetting(setColorPrecision)(Number(e.target.value))}
className="w-full mt-1"
/>
<div className="flex justify-between text-[10px] text-muted-foreground mt-0.5">
<span>Fewer colors</span>
<span>More colors</span>
</div>
</div>
<div>
<div className="flex justify-between items-center">
<label htmlFor="vectorize-layer-diff" className="text-xs text-muted-foreground">
Gradient Step
</label>
<span className="text-xs font-mono text-foreground">{layerDifference}</span>
</div>
<input
id="vectorize-layer-diff"
type="range"
min={1}
max={64}
value={layerDifference}
onChange={(e) => updateSetting(setLayerDifference)(Number(e.target.value))}
className="w-full mt-1"
/>
<div className="flex justify-between text-[10px] text-muted-foreground mt-0.5">
<span>Smooth gradients</span>
<span>Flat colors</span>
</div>
</div>
</>
)}
{/* B&W-specific settings */}
{colorMode === "bw" && (
<div>
<div className="flex justify-between items-center">
<label htmlFor="vectorize-threshold" className="text-xs text-muted-foreground">
Threshold
</label>
<span className="text-xs font-mono text-foreground">{threshold}</span>
</div>
<input
id="vectorize-threshold"
type="range"
min={0}
max={255}
value={threshold}
onChange={(e) => updateSetting(setThreshold)(Number(e.target.value))}
className="w-full mt-1"
/>
<div className="flex justify-between text-[10px] text-muted-foreground mt-0.5">
<span>More white</span>
<span>More black</span>
</div>
</div>
)}
<div className="border-t border-border" />
{/* Detail */}
<div>
<p className="text-xs text-muted-foreground">Detail</p>
<div className="grid grid-cols-3 gap-1 mt-1">
{(["low", "medium", "high"] as const).map((d) => (
<button
type="button"
key={d}
onClick={() => updateSetting(setFilterSpeckle)(DETAIL_TO_SPECKLE[d])}
className={`capitalize text-xs py-1.5 rounded ${detail === d ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
>
{d}
</button>
))}
</div>
</div>
{/* Smoothing */}
<div>
<p className="text-xs text-muted-foreground">Smoothing</p>
<div className="grid grid-cols-3 gap-1 mt-1">
{(["none", "polygon", "spline"] as const).map((m) => (
<button
type="button"
key={m}
onClick={() => updateSetting(setPathMode)(m)}
className={`capitalize text-xs py-1.5 rounded ${pathMode === m ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
>
{m}
</button>
))}
</div>
</div>
{/* Corner Threshold (color mode) */}
{colorMode === "color" && (
<div>
<div className="flex justify-between items-center">
<label htmlFor="vectorize-corner" className="text-xs text-muted-foreground">
Corner Threshold
</label>
<span className="text-xs font-mono text-foreground">{cornerThreshold}deg</span>
</div>
<input
id="vectorize-corner"
type="range"
min={0}
max={180}
value={cornerThreshold}
onChange={(e) => updateSetting(setCornerThreshold)(Number(e.target.value))}
className="w-full mt-1"
/>
<div className="flex justify-between text-[10px] text-muted-foreground mt-0.5">
<span>More corners</span>
<span>Smoother</span>
</div>
</div>
)}
{/* Invert toggle */}
<div className="flex items-center justify-between">
<span className="text-xs text-muted-foreground">Invert Colors</span>
<button
type="button"
onClick={() => updateSetting(setInvert)(!invert)}
className={`w-9 h-5 rounded-full transition-colors ${invert ? "bg-primary" : "bg-muted"}`}
>
<span
className={`block w-4 h-4 rounded-full bg-white shadow transition-transform ${invert ? "translate-x-4" : "translate-x-0.5"}`}
/>
</button>
</div>
<div className="border-t border-border" />
{/* Error */}
{error && <p className="text-xs text-red-500">{error}</p>}
{/* Size info */}
{originalSize != null && processedSize != null && (
<div className="text-xs text-muted-foreground space-y-0.5">
<p>Original: {(originalSize / 1024).toFixed(1)} KB</p>
<p>SVG: {(processedSize / 1024).toFixed(1)} KB</p>
</div>
)}
{/* Submit */}
<button
type="button"
data-testid="vectorize-submit"
onClick={handleProcess}
disabled={!hasFile || processing}
className="w-full py-2.5 rounded-lg bg-primary text-primary-foreground font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{processing && <Loader2 className="h-4 w-4 animate-spin" />}
{processing ? "Vectorizing..." : "Vectorize"}
</button>
{/* Download */}
{downloadUrl && (
<a
href={downloadUrl}
download
data-testid="vectorize-download"
className="w-full py-2.5 rounded-lg border border-primary text-primary font-medium flex items-center justify-center gap-2 hover:bg-primary/5"
>
<Download className="h-4 w-4" />
Download SVG
</a>
)}
</div>
);
}