feat: Etiketten-Editor erheblich verbessert - Import/Export, Zoom, Duplizieren

- Vorlage als JSON exportieren/importieren, damit man sich ein Etikett
  auch per KI erstellen und danach importieren kann
- Zoom-Regler fuer den Canvas (50-200%), da Etikettgroessen stark variieren
- X/Y-Positionsfelder pro Element fuer praezise Platzierung statt nur Drag
- Element duplizieren-Button
- Entf/Backspace loescht das ausgewaehlte Element
This commit is contained in:
Nick Szaunig committed 2026-09-01 19:21:24 +02:00
1 parent 55b6dff31b
commit 9659b8d266
3 files changed
+233 -29

No files matched your search

@@ -1,6 +1,6 @@
"use client";
import { Bold, Italic, Trash2 } from "lucide-react";
import { Bold, Copy, Italic, Trash2 } from "lucide-react";
import {
LabelElement,
LabelFontFamily,
@@ -36,12 +36,14 @@ interface ElementPropertiesPanelProps {
element: LabelElement;
onChange: (patch: Partial<LabelElement>) => void;
onDelete: () => void;
onDuplicate: () => void;
}
export function ElementPropertiesPanel({
element,
onChange,
onDelete,
onDuplicate,
}: ElementPropertiesPanelProps) {
return (
<div className="flex flex-col gap-4">
@@ -49,9 +51,37 @@ export function ElementPropertiesPanel({
<p className="text-sm font-medium text-muted-foreground">
{element.type === "text" ? "Text" : element.type === "qrCode" ? "QR-Code" : element.type === "image" ? "Bild" : "Linie"}
</p>
<Button type="button" variant="ghost" size="icon-sm" onClick={onDelete}>
<Trash2 className="size-3.5 text-destructive" />
</Button>
<div className="flex gap-1">
<Button type="button" variant="ghost" size="icon-sm" onClick={onDuplicate} title="Duplizieren">
<Copy className="size-3.5" />
</Button>
<Button type="button" variant="ghost" size="icon-sm" onClick={onDelete} title="Löschen">
<Trash2 className="size-3.5 text-destructive" />
</Button>
</div>
</div>
<div className="flex gap-3">
<div className="flex flex-1 flex-col gap-2">
<Label htmlFor="element-x">X (mm)</Label>
<Input
id="element-x"
type="number"
inputMode="decimal"
value={element.x}
onChange={(event) => onChange({ x: Number(event.target.value) })}
/>
</div>
<div className="flex flex-1 flex-col gap-2">
<Label htmlFor="element-y">Y (mm)</Label>
<Input
id="element-y"
type="number"
inputMode="decimal"
value={element.y}
onChange={(event) => onChange({ y: Number(event.target.value) })}
/>
</div>
</div>
{element.type === "text" ? <TextFields element={element} onChange={onChange} /> : null}
@@ -8,7 +8,7 @@ import {
} from "@/lib/label-templates/types";
import { cn } from "@/lib/utils";
export const CANVAS_SCALE = 4; // px per mm
export const BASE_SCALE = 4; // px per mm at 100% zoom
const PT_TO_MM = 25.4 / 72;
const MIN_SIZE_MM = 5;
@@ -27,6 +27,7 @@ interface LabelCanvasProps {
heightMm: number;
elements: LabelElement[];
selectedId: string | null;
zoom?: number;
onSelect: (id: string | null) => void;
onChangeElement: (id: string, patch: Partial<LabelElement>) => void;
}
@@ -36,9 +37,12 @@ export function LabelCanvas({
heightMm,
elements,
selectedId,
zoom = 1,
onSelect,
onChangeElement,
}: LabelCanvasProps) {
const scale = BASE_SCALE * zoom;
function startDrag(
event: ReactPointerEvent,
element: LabelElement,
@@ -52,8 +56,8 @@ export function LabelCanvas({
const origin = element;
function onMove(moveEvent: PointerEvent) {
const dxMm = (moveEvent.clientX - startX) / CANVAS_SCALE;
const dyMm = (moveEvent.clientY - startY) / CANVAS_SCALE;
const dxMm = (moveEvent.clientX - startX) / scale;
const dyMm = (moveEvent.clientY - startY) / scale;
if (mode === "move") {
onChangeElement(origin.id, {
@@ -92,13 +96,14 @@ export function LabelCanvas({
return (
<div
className="relative overflow-hidden rounded-lg border border-dashed border-border bg-white shadow-sm"
style={{ width: widthMm * CANVAS_SCALE, height: heightMm * CANVAS_SCALE }}
style={{ width: widthMm * scale, height: heightMm * scale }}
onPointerDown={() => onSelect(null)}
>
{elements.map((element) => (
<ElementBox
key={element.id}
element={element}
scale={scale}
selected={element.id === selectedId}
onStartMove={(event) => startDrag(event, element, "move")}
onStartResize={(event) => startDrag(event, element, "resize")}
@@ -110,16 +115,18 @@ export function LabelCanvas({
function ElementBox({
element,
scale,
selected,
onStartMove,
onStartResize,
}: {
element: LabelElement;
scale: number;
selected: boolean;
onStartMove: (event: ReactPointerEvent) => void;
onStartResize: (event: ReactPointerEvent) => void;
}) {
const box = boxFor(element);
const box = boxFor(element, scale);
return (
<div
@@ -135,7 +142,7 @@ function ElementBox({
}}
onPointerDown={onStartMove}
>
{renderContent(element)}
{renderContent(element, scale)}
{selected ? (
<div
className="absolute right-0 bottom-0 size-3 translate-x-1/2 translate-y-1/2 cursor-nwse-resize rounded-full border-2 border-primary bg-background"
@@ -149,27 +156,30 @@ function ElementBox({
);
}
function boxFor(element: LabelElement): {
function boxFor(
element: LabelElement,
scale: number,
): {
left: number;
top: number;
width: number;
height: number;
} {
const left = element.x * CANVAS_SCALE;
const top = element.y * CANVAS_SCALE;
const left = element.x * scale;
const top = element.y * scale;
if (element.type === "qrCode") {
return { left, top, width: element.size * CANVAS_SCALE, height: element.size * CANVAS_SCALE };
return { left, top, width: element.size * scale, height: element.size * scale };
}
if (element.type === "line") {
const thicknessPx = Math.max(2, element.thickness * PT_TO_MM * CANVAS_SCALE);
const thicknessPx = Math.max(2, element.thickness * PT_TO_MM * scale);
return element.orientation === "horizontal"
? { left, top: top - thicknessPx / 2, width: element.length * CANVAS_SCALE, height: thicknessPx }
: { left: left - thicknessPx / 2, top, width: thicknessPx, height: element.length * CANVAS_SCALE };
? { left, top: top - thicknessPx / 2, width: element.length * scale, height: thicknessPx }
: { left: left - thicknessPx / 2, top, width: thicknessPx, height: element.length * scale };
}
return { left, top, width: element.width * CANVAS_SCALE, height: element.height * CANVAS_SCALE };
return { left, top, width: element.width * scale, height: element.height * scale };
}
function renderContent(element: LabelElement) {
function renderContent(element: LabelElement, scale: number) {
switch (element.type) {
case "text": {
const display = element.placeholderKey
@@ -180,7 +190,7 @@ function renderContent(element: LabelElement) {
className="size-full overflow-hidden whitespace-pre-wrap"
style={{
fontFamily: FONT_CSS[element.fontFamily],
fontSize: element.fontSize * PT_TO_MM * CANVAS_SCALE,
fontSize: element.fontSize * PT_TO_MM * scale,
fontWeight: element.bold ? 700 : 400,
fontStyle: element.italic ? "italic" : "normal",
color: element.color,
@@ -1,8 +1,17 @@
"use client";
import { ChangeEvent, useState } from "react";
import { ChangeEvent, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Image as ImageIcon, Minus, QrCode, Type } from "lucide-react";
import {
Download,
Image as ImageIcon,
Minus,
QrCode,
Type,
Upload,
ZoomIn,
ZoomOut,
} from "lucide-react";
import { toast } from "sonner";
import {
LabelElement,
@@ -25,6 +34,17 @@ import {
import { LabelCanvas } from "./label-canvas";
import { ElementPropertiesPanel } from "./element-properties-panel";
const ELEMENT_TYPES = ["text", "qrCode", "image", "line"] as const;
const ZOOM_STEPS: number[] = [0.5, 0.75, 1, 1.25, 1.5, 2];
const ZOOM_MIN = ZOOM_STEPS[0];
const ZOOM_MAX = ZOOM_STEPS[ZOOM_STEPS.length - 1];
function nextZoomStep(current: number, direction: 1 | -1): number {
const index = ZOOM_STEPS.indexOf(current);
const nextIndex = Math.min(Math.max(index + direction, 0), ZOOM_STEPS.length - 1);
return ZOOM_STEPS[nextIndex];
}
function newId(): string {
return crypto.randomUUID();
}
@@ -57,6 +77,35 @@ export interface LabelDesignerValue {
isDefault: boolean;
}
// Loose runtime check for imported JSON (own export, or hand/AI-authored) -
// only verifies the shape is plausible enough to load into the canvas;
// the backend's own DTO validation is still the real boundary check on save.
function isLabelElementArray(value: unknown): value is LabelElement[] {
return (
Array.isArray(value) &&
value.every(
(item) =>
typeof item === "object" &&
item !== null &&
"id" in item &&
"type" in item &&
"x" in item &&
"y" in item &&
ELEMENT_TYPES.includes((item as { type: unknown }).type as (typeof ELEMENT_TYPES)[number]),
)
);
}
function slugify(name: string): string {
return (
name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-$)/g, "") || "etikett"
);
}
interface LabelDesignerProps {
initial?: LabelDesignerValue;
onSubmit: (value: LabelDesignerValue) => Promise<void>;
@@ -72,6 +121,7 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
const [elements, setElements] = useState<LabelElement[]>(initial?.elements ?? []);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [zoom, setZoom] = useState(1);
const selectedElement = elements.find((element) => element.id === selectedId) ?? null;
@@ -88,12 +138,34 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
);
}
function deleteSelected() {
if (!selectedId) return;
setElements((current) => current.filter((element) => element.id !== selectedId));
setSelectedId(null);
function deleteElement(id: string) {
setElements((current) => current.filter((element) => element.id !== id));
setSelectedId((current) => (current === id ? null : current));
}
function duplicateElement(id: string) {
const source = elements.find((element) => element.id === id);
if (!source) return;
const copy = { ...source, id: newId(), x: source.x + 4, y: source.y + 4 };
addElement(copy);
}
// Delete/Backspace removes the selected element, but never while the user
// is typing in a text field - only when focus is on the canvas itself.
useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (event.key !== "Delete" && event.key !== "Backspace") return;
const target = event.target as HTMLElement | null;
if (target && ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)) return;
if (selectedId) {
event.preventDefault();
deleteElement(selectedId);
}
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [selectedId, elements]);
function handlePlaceholderInsert(key: PlaceholderKey) {
addElement(newTextElement({ placeholderKey: key, text: "" }));
}
@@ -117,6 +189,48 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
reader.readAsDataURL(file);
}
function handleExport() {
const payload: LabelDesignerValue = { name, elements, widthMm, heightMm, isDefault };
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `${slugify(name)}.json`;
link.click();
URL.revokeObjectURL(url);
}
function handleImportFile(event: ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
try {
const parsed: unknown = JSON.parse(String(reader.result));
const importedElements = Array.isArray(parsed)
? parsed
: (parsed as { elements?: unknown })?.elements;
if (!isLabelElementArray(importedElements)) {
toast.error("Datei enthält keine gültige Etikettenvorlage.");
return;
}
setElements(importedElements.map((element) => ({ ...element, id: newId() })));
if (!Array.isArray(parsed)) {
const value = parsed as Partial<LabelDesignerValue>;
if (typeof value.name === "string" && value.name && !name) setName(value.name);
if (typeof value.widthMm === "number") setWidthMm(value.widthMm);
if (typeof value.heightMm === "number") setHeightMm(value.heightMm);
}
setSelectedId(null);
toast.success("Vorlage importiert.");
} catch {
toast.error("Datei konnte nicht gelesen werden - ist es gültiges JSON?");
}
};
reader.readAsText(file);
}
async function handleSubmit() {
if (!name.trim()) {
toast.error("Bitte einen Namen für die Vorlage angeben.");
@@ -185,8 +299,31 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
</Card>
<Card>
<CardHeader>
<CardHeader className="flex flex-row items-center justify-between gap-2">
<CardTitle className="text-base">Elemente</CardTitle>
<div className="flex items-center gap-1">
<Button
type="button"
variant="ghost"
size="sm"
render={
<label className="cursor-pointer">
<Upload className="size-4" />
Importieren
<input
type="file"
accept="application/json"
className="hidden"
onChange={handleImportFile}
/>
</label>
}
/>
<Button type="button" variant="ghost" size="sm" onClick={handleExport}>
<Download className="size-4" />
Exportieren
</Button>
</div>
</CardHeader>
<CardContent className="flex flex-wrap items-center gap-2">
<Button
@@ -251,12 +388,37 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
</CardContent>
</Card>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="icon-sm"
disabled={zoom <= ZOOM_MIN}
onClick={() => setZoom((current) => nextZoomStep(current, -1))}
>
<ZoomOut className="size-3.5" />
</Button>
<span className="w-12 text-center text-sm text-muted-foreground">
{Math.round(zoom * 100)}%
</span>
<Button
type="button"
variant="outline"
size="icon-sm"
disabled={zoom >= ZOOM_MAX}
onClick={() => setZoom((current) => nextZoomStep(current, 1))}
>
<ZoomIn className="size-3.5" />
</Button>
</div>
<div className="overflow-auto rounded-lg bg-muted/30 p-6">
<LabelCanvas
widthMm={widthMm}
heightMm={heightMm}
elements={elements}
selectedId={selectedId}
zoom={zoom}
onSelect={setSelectedId}
onChangeElement={changeElement}
/>
@@ -276,11 +438,13 @@ export function LabelDesigner({ initial, onSubmit, submitLabel }: LabelDesignerP
<ElementPropertiesPanel
element={selectedElement}
onChange={(patch) => changeElement(selectedElement.id, patch)}
onDelete={deleteSelected}
onDelete={() => deleteElement(selectedElement.id)}
onDuplicate={() => duplicateElement(selectedElement.id)}
/>
) : (
<p className="text-sm text-muted-foreground">
Element im Etikett anklicken, um es zu bearbeiten.
Element im Etikett anklicken, um es zu bearbeiten. Entf/Backspace löscht das
ausgewählte Element.
</p>
)}
</CardContent>