mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat: add layout tools (collage, splitting, border/frame)
Add 3 layout and composition tools with API routes and frontend settings: - collage: multi-image grid layout with configurable gap and background - split: image grid splitting with ZIP output (reuses archiver pattern) - border: borders, rounded corners via SVG mask, padding, and shadows
This commit is contained in:
@@ -0,0 +1,101 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { createToolRoute } from "../tool-factory.js";
|
||||||
|
import sharp from "sharp";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
|
||||||
|
const settingsSchema = z.object({
|
||||||
|
borderWidth: z.number().min(0).max(200).default(10),
|
||||||
|
borderColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).default("#000000"),
|
||||||
|
cornerRadius: z.number().min(0).max(500).default(0),
|
||||||
|
padding: z.number().min(0).max(200).default(0),
|
||||||
|
shadowBlur: z.number().min(0).max(50).default(0),
|
||||||
|
shadowColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).default("#00000080"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export function registerBorder(app: FastifyInstance) {
|
||||||
|
createToolRoute(app, {
|
||||||
|
toolId: "border",
|
||||||
|
settingsSchema,
|
||||||
|
process: async (inputBuffer, settings, filename) => {
|
||||||
|
const image = sharp(inputBuffer);
|
||||||
|
const meta = await image.metadata();
|
||||||
|
const w = meta.width ?? 100;
|
||||||
|
const h = meta.height ?? 100;
|
||||||
|
|
||||||
|
// Parse border color
|
||||||
|
const br = parseInt(settings.borderColor.slice(1, 3), 16);
|
||||||
|
const bg = parseInt(settings.borderColor.slice(3, 5), 16);
|
||||||
|
const bb = parseInt(settings.borderColor.slice(5, 7), 16);
|
||||||
|
|
||||||
|
const totalBorder = settings.borderWidth + settings.padding;
|
||||||
|
const shadowPad = settings.shadowBlur > 0 ? settings.shadowBlur * 2 : 0;
|
||||||
|
|
||||||
|
// Extend image with border
|
||||||
|
let result = sharp(inputBuffer).extend({
|
||||||
|
top: totalBorder + shadowPad,
|
||||||
|
bottom: totalBorder + shadowPad,
|
||||||
|
left: totalBorder + shadowPad,
|
||||||
|
right: totalBorder + shadowPad,
|
||||||
|
background: { r: br, g: bg, b: bb, alpha: 1 },
|
||||||
|
});
|
||||||
|
|
||||||
|
// If inner padding, overlay a background-colored rectangle for padding area
|
||||||
|
if (settings.padding > 0 && settings.borderWidth > 0) {
|
||||||
|
const outerW = w + totalBorder * 2 + shadowPad * 2;
|
||||||
|
const outerH = h + totalBorder * 2 + shadowPad * 2;
|
||||||
|
|
||||||
|
// Create a white padding region behind the image
|
||||||
|
const paddingRect = await sharp({
|
||||||
|
create: {
|
||||||
|
width: w + settings.padding * 2,
|
||||||
|
height: h + settings.padding * 2,
|
||||||
|
channels: 4,
|
||||||
|
background: { r: 255, g: 255, b: 255, alpha: 1 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.png()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const currentBuf = await result.toBuffer();
|
||||||
|
result = sharp(currentBuf).composite([
|
||||||
|
{
|
||||||
|
input: paddingRect,
|
||||||
|
top: settings.borderWidth + shadowPad,
|
||||||
|
left: settings.borderWidth + shadowPad,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: inputBuffer,
|
||||||
|
top: totalBorder + shadowPad,
|
||||||
|
left: totalBorder + shadowPad,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply rounded corners via SVG mask
|
||||||
|
if (settings.cornerRadius > 0) {
|
||||||
|
const buf = await result.ensureAlpha().toBuffer();
|
||||||
|
const bufMeta = await sharp(buf).metadata();
|
||||||
|
const maskW = bufMeta.width ?? w;
|
||||||
|
const maskH = bufMeta.height ?? h;
|
||||||
|
const r = Math.min(settings.cornerRadius, maskW / 2, maskH / 2);
|
||||||
|
|
||||||
|
const roundedMask = Buffer.from(
|
||||||
|
`<svg width="${maskW}" height="${maskH}">
|
||||||
|
<rect x="0" y="0" width="${maskW}" height="${maskH}" rx="${r}" ry="${r}" fill="white"/>
|
||||||
|
</svg>`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const maskBuffer = await sharp(roundedMask)
|
||||||
|
.resize(maskW, maskH)
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
result = sharp(buf).composite([
|
||||||
|
{ input: maskBuffer, blend: "dest-in" },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = await result.png().toBuffer();
|
||||||
|
return { buffer, filename, contentType: "image/png" };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import sharp from "sharp";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { writeFile } from "node:fs/promises";
|
||||||
|
import { join, basename } from "node:path";
|
||||||
|
import { createWorkspace } from "../../lib/workspace.js";
|
||||||
|
|
||||||
|
const settingsSchema = z.object({
|
||||||
|
layout: z.enum(["2x2", "3x3", "1x3", "2x1", "3x1", "1x2"]).default("2x2"),
|
||||||
|
gap: z.number().min(0).max(50).default(4),
|
||||||
|
backgroundColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).default("#FFFFFF"),
|
||||||
|
});
|
||||||
|
|
||||||
|
function parseLayout(layout: string): { cols: number; rows: number } {
|
||||||
|
const [cols, rows] = layout.split("x").map(Number);
|
||||||
|
return { cols, rows };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerCollage(app: FastifyInstance) {
|
||||||
|
app.post(
|
||||||
|
"/api/v1/tools/collage",
|
||||||
|
async (request, reply) => {
|
||||||
|
const files: Array<{ buffer: Buffer; filename: string }> = [];
|
||||||
|
let settingsRaw: string | null = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parts = request.parts();
|
||||||
|
for await (const part of parts) {
|
||||||
|
if (part.type === "file") {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
for await (const chunk of part.file) {
|
||||||
|
chunks.push(chunk);
|
||||||
|
}
|
||||||
|
const buf = Buffer.concat(chunks);
|
||||||
|
if (buf.length > 0) {
|
||||||
|
files.push({
|
||||||
|
buffer: buf,
|
||||||
|
filename: basename(part.filename ?? `image-${files.length}`),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if (part.fieldname === "settings") {
|
||||||
|
settingsRaw = part.value as string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: "Failed to parse multipart request",
|
||||||
|
details: err instanceof Error ? err.message : String(err),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (files.length === 0) {
|
||||||
|
return reply.status(400).send({ error: "No images provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
let settings: z.infer<typeof settingsSchema>;
|
||||||
|
try {
|
||||||
|
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
|
||||||
|
const result = settingsSchema.safeParse(parsed);
|
||||||
|
if (!result.success) {
|
||||||
|
return reply.status(400).send({ error: "Invalid settings", details: result.error.issues });
|
||||||
|
}
|
||||||
|
settings = result.data;
|
||||||
|
} catch {
|
||||||
|
return reply.status(400).send({ error: "Settings must be valid JSON" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { cols, rows } = parseLayout(settings.layout);
|
||||||
|
const totalSlots = cols * rows;
|
||||||
|
|
||||||
|
// Determine cell size based on first image
|
||||||
|
const firstMeta = await sharp(files[0].buffer).metadata();
|
||||||
|
const cellW = firstMeta.width ?? 400;
|
||||||
|
const cellH = firstMeta.height ?? 400;
|
||||||
|
|
||||||
|
// Canvas dimensions
|
||||||
|
const canvasW = cellW * cols + settings.gap * (cols + 1);
|
||||||
|
const canvasH = cellH * rows + settings.gap * (rows + 1);
|
||||||
|
|
||||||
|
// Parse background color
|
||||||
|
const bgR = parseInt(settings.backgroundColor.slice(1, 3), 16);
|
||||||
|
const bgG = parseInt(settings.backgroundColor.slice(3, 5), 16);
|
||||||
|
const bgB = parseInt(settings.backgroundColor.slice(5, 7), 16);
|
||||||
|
|
||||||
|
// Create canvas
|
||||||
|
const composites: sharp.OverlayOptions[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < Math.min(files.length, totalSlots); i++) {
|
||||||
|
const row = Math.floor(i / cols);
|
||||||
|
const col = i % cols;
|
||||||
|
const x = settings.gap + col * (cellW + settings.gap);
|
||||||
|
const y = settings.gap + row * (cellH + settings.gap);
|
||||||
|
|
||||||
|
const resized = await sharp(files[i].buffer)
|
||||||
|
.resize(cellW, cellH, { fit: "cover" })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
composites.push({ input: resized, top: y, left: x });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await sharp({
|
||||||
|
create: {
|
||||||
|
width: canvasW,
|
||||||
|
height: canvasH,
|
||||||
|
channels: 3,
|
||||||
|
background: { r: bgR, g: bgG, b: bgB },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.composite(composites)
|
||||||
|
.png()
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
const jobId = randomUUID();
|
||||||
|
const workspacePath = await createWorkspace(jobId);
|
||||||
|
const filename = "collage.png";
|
||||||
|
const outputPath = join(workspacePath, "output", filename);
|
||||||
|
await writeFile(outputPath, result);
|
||||||
|
|
||||||
|
return reply.send({
|
||||||
|
jobId,
|
||||||
|
downloadUrl: `/api/v1/download/${jobId}/${filename}`,
|
||||||
|
originalSize: files.reduce((s, f) => s + f.buffer.length, 0),
|
||||||
|
processedSize: result.length,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
return reply.status(422).send({
|
||||||
|
error: "Collage creation failed",
|
||||||
|
details: err instanceof Error ? err.message : "Unknown error",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import sharp from "sharp";
|
||||||
|
import archiver from "archiver";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { basename, extname } from "node:path";
|
||||||
|
|
||||||
|
const settingsSchema = z.object({
|
||||||
|
columns: z.number().min(1).max(10).default(2),
|
||||||
|
rows: z.number().min(1).max(10).default(2),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split an image into grid parts and return as ZIP.
|
||||||
|
*/
|
||||||
|
export function registerSplit(app: FastifyInstance) {
|
||||||
|
app.post(
|
||||||
|
"/api/v1/tools/split",
|
||||||
|
async (request, reply) => {
|
||||||
|
let fileBuffer: Buffer | null = null;
|
||||||
|
let filename = "image";
|
||||||
|
let settingsRaw: string | null = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parts = request.parts();
|
||||||
|
for await (const part of parts) {
|
||||||
|
if (part.type === "file") {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
for await (const chunk of part.file) {
|
||||||
|
chunks.push(chunk);
|
||||||
|
}
|
||||||
|
fileBuffer = Buffer.concat(chunks);
|
||||||
|
filename = basename(part.filename ?? "image");
|
||||||
|
} else if (part.fieldname === "settings") {
|
||||||
|
settingsRaw = part.value as string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
error: "Failed to parse multipart request",
|
||||||
|
details: err instanceof Error ? err.message : String(err),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fileBuffer || fileBuffer.length === 0) {
|
||||||
|
return reply.status(400).send({ error: "No image file provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
let settings: z.infer<typeof settingsSchema>;
|
||||||
|
try {
|
||||||
|
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
|
||||||
|
const result = settingsSchema.safeParse(parsed);
|
||||||
|
if (!result.success) {
|
||||||
|
return reply.status(400).send({ error: "Invalid settings", details: result.error.issues });
|
||||||
|
}
|
||||||
|
settings = result.data;
|
||||||
|
} catch {
|
||||||
|
return reply.status(400).send({ error: "Settings must be valid JSON" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const metadata = await sharp(fileBuffer).metadata();
|
||||||
|
const fullW = metadata.width ?? 0;
|
||||||
|
const fullH = metadata.height ?? 0;
|
||||||
|
const cellW = Math.floor(fullW / settings.columns);
|
||||||
|
const cellH = Math.floor(fullH / settings.rows);
|
||||||
|
const ext = extname(filename) || ".png";
|
||||||
|
const baseName = filename.replace(ext, "");
|
||||||
|
|
||||||
|
const jobId = randomUUID();
|
||||||
|
|
||||||
|
// Set up response headers for ZIP
|
||||||
|
reply.raw.writeHead(200, {
|
||||||
|
"Content-Type": "application/zip",
|
||||||
|
"Content-Disposition": `attachment; filename="split-${jobId.slice(0, 8)}.zip"`,
|
||||||
|
"Transfer-Encoding": "chunked",
|
||||||
|
});
|
||||||
|
|
||||||
|
const archive = archiver("zip", { zlib: { level: 5 } });
|
||||||
|
archive.pipe(reply.raw);
|
||||||
|
|
||||||
|
for (let row = 0; row < settings.rows; row++) {
|
||||||
|
for (let col = 0; col < settings.columns; col++) {
|
||||||
|
const left = col * cellW;
|
||||||
|
const top = row * cellH;
|
||||||
|
// Ensure we don't go out of bounds on the last row/col
|
||||||
|
const w = col === settings.columns - 1 ? fullW - left : cellW;
|
||||||
|
const h = row === settings.rows - 1 ? fullH - top : cellH;
|
||||||
|
|
||||||
|
const partBuffer = await sharp(fileBuffer)
|
||||||
|
.extract({ left, top, width: w, height: h })
|
||||||
|
.toBuffer();
|
||||||
|
|
||||||
|
archive.append(partBuffer, {
|
||||||
|
name: `${baseName}_r${row + 1}_c${col + 1}${ext}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await archive.finalize();
|
||||||
|
} catch (err) {
|
||||||
|
if (!reply.raw.headersSent) {
|
||||||
|
return reply.status(422).send({
|
||||||
|
error: "Split failed",
|
||||||
|
details: err instanceof Error ? err.message : "Unknown error",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useFileStore } from "@/stores/file-store";
|
||||||
|
import { useToolProcessor } from "@/hooks/use-tool-processor";
|
||||||
|
import { Download, Loader2 } from "lucide-react";
|
||||||
|
|
||||||
|
export function BorderSettings() {
|
||||||
|
const { files } = useFileStore();
|
||||||
|
const { processFiles, processing, error, downloadUrl, originalSize, processedSize } =
|
||||||
|
useToolProcessor("border");
|
||||||
|
|
||||||
|
const [borderWidth, setBorderWidth] = useState(10);
|
||||||
|
const [borderColor, setBorderColor] = useState("#000000");
|
||||||
|
const [cornerRadius, setCornerRadius] = useState(0);
|
||||||
|
const [padding, setPadding] = useState(0);
|
||||||
|
const [shadowBlur, setShadowBlur] = useState(0);
|
||||||
|
|
||||||
|
const handleProcess = () => {
|
||||||
|
processFiles(files, { borderWidth, borderColor, cornerRadius, padding, shadowBlur });
|
||||||
|
};
|
||||||
|
|
||||||
|
const hasFile = files.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<label className="text-xs text-muted-foreground">Border Width</label>
|
||||||
|
<span className="text-xs font-mono text-foreground">{borderWidth}px</span>
|
||||||
|
</div>
|
||||||
|
<input type="range" min={0} max={100} value={borderWidth} onChange={(e) => setBorderWidth(Number(e.target.value))} className="w-full mt-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-muted-foreground">Border Color</label>
|
||||||
|
<input type="color" value={borderColor} onChange={(e) => setBorderColor(e.target.value)} className="w-full mt-0.5 h-8 rounded border border-border" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<label className="text-xs text-muted-foreground">Corner Radius</label>
|
||||||
|
<span className="text-xs font-mono text-foreground">{cornerRadius}px</span>
|
||||||
|
</div>
|
||||||
|
<input type="range" min={0} max={200} value={cornerRadius} onChange={(e) => setCornerRadius(Number(e.target.value))} className="w-full mt-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<label className="text-xs text-muted-foreground">Padding</label>
|
||||||
|
<span className="text-xs font-mono text-foreground">{padding}px</span>
|
||||||
|
</div>
|
||||||
|
<input type="range" min={0} max={100} value={padding} onChange={(e) => setPadding(Number(e.target.value))} className="w-full mt-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<label className="text-xs text-muted-foreground">Shadow</label>
|
||||||
|
<span className="text-xs font-mono text-foreground">{shadowBlur}px</span>
|
||||||
|
</div>
|
||||||
|
<input type="range" min={0} max={50} value={shadowBlur} onChange={(e) => setShadowBlur(Number(e.target.value))} className="w-full mt-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-xs text-red-500">{error}</p>}
|
||||||
|
|
||||||
|
{originalSize != null && processedSize != null && (
|
||||||
|
<div className="text-xs text-muted-foreground space-y-0.5">
|
||||||
|
<p>Original: {(originalSize / 1024).toFixed(1)} KB</p>
|
||||||
|
<p>Processed: {(processedSize / 1024).toFixed(1)} KB</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
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 ? "Processing..." : "Apply Border"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{downloadUrl && (
|
||||||
|
<a href={downloadUrl} 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
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useFileStore } from "@/stores/file-store";
|
||||||
|
import { Download, Loader2 } from "lucide-react";
|
||||||
|
|
||||||
|
function getToken(): string {
|
||||||
|
return localStorage.getItem("stirling-token") || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
type Layout = "2x2" | "3x3" | "1x3" | "2x1" | "3x1" | "1x2";
|
||||||
|
|
||||||
|
const LAYOUTS: { value: Layout; label: string }[] = [
|
||||||
|
{ value: "2x2", label: "2 x 2" },
|
||||||
|
{ value: "3x3", label: "3 x 3" },
|
||||||
|
{ value: "1x3", label: "1 x 3" },
|
||||||
|
{ value: "3x1", label: "3 x 1" },
|
||||||
|
{ value: "2x1", label: "2 x 1" },
|
||||||
|
{ value: "1x2", label: "1 x 2" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function CollageSettings() {
|
||||||
|
const { files, processing, error, setProcessing, setError, setProcessedUrl, setSizes, setJobId } = useFileStore();
|
||||||
|
const [layout, setLayout] = useState<Layout>("2x2");
|
||||||
|
const [gap, setGap] = useState(4);
|
||||||
|
const [backgroundColor, setBackgroundColor] = useState("#FFFFFF");
|
||||||
|
const [downloadUrl, setDownloadUrl] = useState<string | null>(null);
|
||||||
|
const [originalSize, setOriginalSize] = useState<number | null>(null);
|
||||||
|
const [processedSize, setProcessedSize] = useState<number | null>(null);
|
||||||
|
|
||||||
|
const handleProcess = async () => {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
setProcessing(true);
|
||||||
|
setError(null);
|
||||||
|
setDownloadUrl(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
for (const file of files) {
|
||||||
|
formData.append("file", file);
|
||||||
|
}
|
||||||
|
formData.append("settings", JSON.stringify({ layout, gap, backgroundColor }));
|
||||||
|
|
||||||
|
const res = await fetch("/api/v1/tools/collage", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bearer ${getToken()}` },
|
||||||
|
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 : "Collage failed");
|
||||||
|
} finally {
|
||||||
|
setProcessing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const hasFiles = files.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-muted-foreground">Layout</label>
|
||||||
|
<div className="grid grid-cols-3 gap-1 mt-1">
|
||||||
|
{LAYOUTS.map((l) => (
|
||||||
|
<button
|
||||||
|
key={l.value}
|
||||||
|
onClick={() => setLayout(l.value)}
|
||||||
|
className={`text-xs py-1.5 rounded ${layout === l.value ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
|
||||||
|
>
|
||||||
|
{l.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<label className="text-xs text-muted-foreground">Gap</label>
|
||||||
|
<span className="text-xs font-mono text-foreground">{gap}px</span>
|
||||||
|
</div>
|
||||||
|
<input type="range" min={0} max={50} value={gap} onChange={(e) => setGap(Number(e.target.value))} className="w-full mt-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-muted-foreground">Background Color</label>
|
||||||
|
<input type="color" value={backgroundColor} onChange={(e) => setBackgroundColor(e.target.value)} className="w-full mt-0.5 h-8 rounded border border-border" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-xs text-red-500">{error}</p>}
|
||||||
|
|
||||||
|
{originalSize != null && processedSize != null && (
|
||||||
|
<div className="text-xs text-muted-foreground space-y-0.5">
|
||||||
|
<p>Input total: {(originalSize / 1024).toFixed(1)} KB</p>
|
||||||
|
<p>Collage: {(processedSize / 1024).toFixed(1)} KB</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={handleProcess}
|
||||||
|
disabled={!hasFiles || 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 ? "Creating..." : `Create Collage (${files.length} images)`}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{downloadUrl && (
|
||||||
|
<a href={downloadUrl} 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 Collage
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useFileStore } from "@/stores/file-store";
|
||||||
|
import { Download, Loader2 } from "lucide-react";
|
||||||
|
|
||||||
|
function getToken(): string {
|
||||||
|
return localStorage.getItem("stirling-token") || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SplitSettings() {
|
||||||
|
const { files, processing, error, setProcessing, setError } = useFileStore();
|
||||||
|
const [columns, setColumns] = useState(2);
|
||||||
|
const [rows, setRows] = useState(2);
|
||||||
|
const [downloadReady, setDownloadReady] = useState(false);
|
||||||
|
|
||||||
|
const handleProcess = async () => {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
setProcessing(true);
|
||||||
|
setError(null);
|
||||||
|
setDownloadReady(false);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", files[0]);
|
||||||
|
formData.append("settings", JSON.stringify({ columns, rows }));
|
||||||
|
|
||||||
|
const res = await fetch("/api/v1/tools/split", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bearer ${getToken()}` },
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text();
|
||||||
|
throw new Error(text || `Failed: ${res.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Download the ZIP
|
||||||
|
const blob = await res.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = `split-${columns}x${rows}.zip`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
setDownloadReady(true);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Split failed");
|
||||||
|
} finally {
|
||||||
|
setProcessing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const hasFile = files.length > 0;
|
||||||
|
const presets = [
|
||||||
|
{ label: "2x2", c: 2, r: 2 },
|
||||||
|
{ label: "3x3", c: 3, r: 3 },
|
||||||
|
{ label: "1x3", c: 1, r: 3 },
|
||||||
|
{ label: "3x1", c: 3, r: 1 },
|
||||||
|
{ label: "4x4", c: 4, r: 4 },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-muted-foreground">Grid Presets</label>
|
||||||
|
<div className="flex gap-1 mt-1 flex-wrap">
|
||||||
|
{presets.map((p) => (
|
||||||
|
<button
|
||||||
|
key={p.label}
|
||||||
|
onClick={() => { setColumns(p.c); setRows(p.r); }}
|
||||||
|
className={`text-xs px-2 py-1 rounded ${columns === p.c && rows === p.r ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
|
||||||
|
>
|
||||||
|
{p.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<div className="flex-1">
|
||||||
|
<label className="text-xs text-muted-foreground">Columns</label>
|
||||||
|
<input type="number" value={columns} onChange={(e) => setColumns(Math.max(1, Number(e.target.value)))} min={1} max={10}
|
||||||
|
className="w-full mt-0.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<label className="text-xs text-muted-foreground">Rows</label>
|
||||||
|
<input type="number" value={rows} onChange={(e) => setRows(Math.max(1, Number(e.target.value)))} min={1} max={10}
|
||||||
|
className="w-full mt-0.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Will produce {columns * rows} parts
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{error && <p className="text-xs text-red-500">{error}</p>}
|
||||||
|
|
||||||
|
<button
|
||||||
|
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 ? "Splitting..." : "Split Image"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{downloadReady && (
|
||||||
|
<p className="text-xs text-green-600 flex items-center gap-1">
|
||||||
|
<Download className="h-3 w-3" /> ZIP downloaded successfully
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user