Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-website/components/sections/WorkflowEditor.tsx
T

868 lines
47 KiB
TypeScript

"use client";
import { useState, useRef, useCallback, useEffect } from "react";
/* ─── SVG Icons ───────────────────────────────────────────────────────── */
const icons: Record<string, (c: string) => React.ReactNode> = {
inbox: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12" /><path d="M5.45 5.11L2 12v6a2 2 0 002 2h16a2 2 0 002-2v-6l-3.45-6.89A2 2 0 0016.76 4H7.24a2 2 0 00-1.79 1.11z" /></svg>,
clipboard: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2" /><rect x="8" y="2" width="8" height="4" rx="1" ry="1" /></svg>,
user: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" /><circle cx="12" cy="7" r="4" /></svg>,
package: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16.5 9.4l-9-5.19M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" /><polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" /></svg>,
calendar: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></svg>,
check: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14" /><polyline points="22 4 12 14.01 9 11.01" /></svg>,
receipt: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1z" /><path d="M8 10h8" /><path d="M8 14h4" /></svg>,
zap: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>,
mail: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2" /><path d="M22 7l-10 7L2 7" /></svg>,
database: (c) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3" /><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3" /><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5" /></svg>,
};
const palette = [
{ icon: "inbox", label: "Anfrage", color: "#4F46E5" },
{ icon: "clipboard", label: "Auftrag", color: "#F1B729" },
{ icon: "user", label: "Zuweisen", color: "#0D6E6E" },
{ icon: "package", label: "Material", color: "#F97316" },
{ icon: "calendar", label: "Termin", color: "#3B82F6" },
{ icon: "check", label: "Erledigt", color: "#22C55E" },
{ icon: "receipt", label: "Rechnung", color: "#8B5CF6" },
{ icon: "zap", label: "Trigger", color: "#EC4899" },
{ icon: "mail", label: "E-Mail", color: "#0EA5E9" },
{ icon: "database", label: "Datenbank", color: "#6366F1" },
];
/* ─── Types ───────────────────────────────────────────────────────────── */
type HandleSide = "top" | "right" | "bottom" | "left";
interface WFNode { id: string; icon: string; label: string; subtitle?: string; color: string; x: number; y: number }
interface WFEdge { id: string; from: string; fromSide: HandleSide; to: string; toSide: HandleSide }
interface CtxMenu { x: number; y: number; type: "node" | "edge" | "canvas"; targetId?: string }
const NODE_W = 220;
const NODE_H = 56;
const HANDLE_R = 6; // handle visual radius
const HANDLE_OFFSET = 14; // how far from handle center the edge endpoint stops
/* ─── Handle position for a node ──────────────────────────────────────── */
function nodeHeight(node: WFNode): number {
return node.subtitle ? 74 : NODE_H;
}
function handlePos(node: WFNode, side: HandleSide): { x: number; y: number } {
const h = nodeHeight(node);
switch (side) {
case "top": return { x: node.x + NODE_W / 2, y: node.y };
case "right": return { x: node.x + NODE_W, y: node.y + h / 2 };
case "bottom": return { x: node.x + NODE_W / 2, y: node.y + h };
case "left": return { x: node.x, y: node.y + h / 2 };
}
}
/* ─── Find nearest handle on a node to a point ────────────────────────── */
function nearestHandle(node: WFNode, px: number, py: number): HandleSide {
const sides: HandleSide[] = ["top", "right", "bottom", "left"];
let best: HandleSide = "right";
let bestDist = Infinity;
for (const s of sides) {
const h = handlePos(node, s);
const d = Math.hypot(h.x - px, h.y - py);
if (d < bestDist) { bestDist = d; best = s; }
}
return best;
}
/* ─── Direction vector for a handle side ──────────────────────────────── */
function sideDir(side: HandleSide): { dx: number; dy: number } {
switch (side) {
case "top": return { dx: 0, dy: -1 };
case "right": return { dx: 1, dy: 0 };
case "bottom": return { dx: 0, dy: 1 };
case "left": return { dx: -1, dy: 0 };
}
}
/* ─── Bezier path with direction-aware control points ─────────────────── */
// Round values that end up in SSR'd SVG attribute strings. Math.hypot (and the
// trig below) are implementation-defined in their last ULP, so Node and the
// browser can serialise a float's last digit differently → hydration mismatch.
// We use Math.sqrt (IEEE correctly-rounded, engine-identical) and round the
// string-bound numbers so server and client produce byte-identical output.
const rnd = (n: number) => Math.round(n * 1000) / 1000;
const dist2 = (dx: number, dy: number) => Math.sqrt(dx * dx + dy * dy);
function edgePath(x1: number, y1: number, s1: HandleSide, x2: number, y2: number, s2: HandleSide): string {
const d1 = sideDir(s1);
const d2 = sideDir(s2);
const dist = Math.max(40, dist2(x2 - x1, y2 - y1) * 0.4);
const cx1 = rnd(x1 + d1.dx * dist);
const cy1 = rnd(y1 + d1.dy * dist);
const cx2 = rnd(x2 + d2.dx * dist);
const cy2 = rnd(y2 + d2.dy * dist);
return `M${x1},${y1} C${cx1},${cy1} ${cx2},${cy2} ${x2},${y2}`;
}
/* ─── Arrow tip offset: move endpoint back so arrow doesn't enter node ── */
function offsetPoint(x: number, y: number, side: HandleSide, amount: number): { x: number; y: number } {
const d = sideDir(side);
return { x: x + d.dx * amount, y: y + d.dy * amount };
}
/* ─── Free-end path (when dragging a new connection) ──────────────────── */
function freePath(x1: number, y1: number, s1: HandleSide, mx: number, my: number): string {
const d = sideDir(s1);
const dist = Math.max(40, dist2(mx - x1, my - y1) * 0.4);
return `M${x1},${y1} C${rnd(x1 + d.dx * dist)},${rnd(y1 + d.dy * dist)} ${mx},${my} ${mx},${my}`;
}
/* ─── Approximate bezier path length (for consistent dot speed) ───────── */
function approxPathLength(x1: number, y1: number, s1: HandleSide, x2: number, y2: number, s2: HandleSide): number {
const d1 = sideDir(s1);
const d2 = sideDir(s2);
const dist = Math.max(40, dist2(x2 - x1, y2 - y1) * 0.4);
const cx1 = x1 + d1.dx * dist, cy1 = y1 + d1.dy * dist;
const cx2 = x2 + d2.dx * dist, cy2 = y2 + d2.dy * dist;
// Subdivide into 10 segments and sum chord lengths
let len = 0;
let px = x1, py = y1;
for (let i = 1; i <= 10; i++) {
const t = i / 10;
const u = 1 - t;
const nx = u*u*u*x1 + 3*u*u*t*cx1 + 3*u*t*t*cx2 + t*t*t*x2;
const ny = u*u*u*y1 + 3*u*u*t*cy1 + 3*u*t*t*cy2 + t*t*t*y2;
len += dist2(nx - px, ny - py);
px = nx; py = ny;
}
return len;
}
/* ─── Defaults — invoice payment flow ─────────────────────────────────── */
const defaultNodes: WFNode[] = [
{ id: "n1", icon: "receipt", label: "Rechnung senden", subtitle: "Template: Standard-Rechnung", color: "#8B5CF6", x: 30, y: 220 },
{ id: "n2", icon: "calendar", label: "2 Wochen warten", color: "#F97316", x: 320, y: 230 },
{ id: "n3", icon: "check", label: "Bezahlt?", color: "#3B82F6", x: 610, y: 230 },
{ id: "n4", icon: "mail", label: "Bestätigung senden", subtitle: "Template: Zahlungseingang", color: "#22C55E", x: 900, y: 80 },
{ id: "n5", icon: "inbox", label: "Mahnung senden", subtitle: "Template: Zahlungserinnerung", color: "#EF4444", x: 900, y: 390 },
];
let _eid = 1;
const eid = () => `e${_eid++}`;
const defaultEdges: WFEdge[] = [
{ id: eid(), from: "n1", fromSide: "right", to: "n2", toSide: "left" },
{ id: eid(), from: "n2", fromSide: "right", to: "n3", toSide: "left" },
{ id: eid(), from: "n3", fromSide: "top", to: "n4", toSide: "left" }, // Ja → Bestätigung
{ id: eid(), from: "n3", fromSide: "bottom", to: "n5", toSide: "left" }, // Nein → Mahnung
{ id: eid(), from: "n5", fromSide: "left", to: "n1", toSide: "bottom" }, // Loop: nochmal
];
/* ─── Connection drag state ───────────────────────────────────────────── */
interface ConnDrag {
/** Are we creating a new edge or reconnecting an existing one? */
mode: "new" | "reconnect";
/** The node+handle we're dragging FROM (the anchored end) */
anchorNode: string;
anchorSide: HandleSide;
/** If reconnecting, the original edge id */
edgeId?: string;
/** Current mouse position */
mx: number;
my: number;
}
/* ─── Component ───────────────────────────────────────────────────────── */
export default function WorkflowEditor({ hideHeader = false }: { hideHeader?: boolean }) {
const [nodes, setNodes] = useState<WFNode[]>(defaultNodes);
const [edges, setEdges] = useState<WFEdge[]>(defaultEdges);
const [selected, setSelected] = useState<string | null>(null);
const [selectedEdge, setSelectedEdge] = useState<string | null>(null);
const [dragging, setDragging] = useState<string | null>(null);
const [connDrag, setConnDrag] = useState<ConnDrag | null>(null);
const [ctxMenu, setCtxMenu] = useState<CtxMenu | null>(null);
const [hoveredHandle, setHoveredHandle] = useState<{ nodeId: string; side: HandleSide } | null>(null);
const [addOpen, setAddOpen] = useState(false);
const [showHint, setShowHint] = useState(false);
const hintDismissed = useRef(false);
const dragOffset = useRef({ dx: 0, dy: 0 });
const canvasRef = useRef<HTMLDivElement>(null);
const idCounter = useRef(defaultNodes.length + 1);
const getPos = useCallback((e: React.PointerEvent | PointerEvent | React.MouseEvent) => {
const r = canvasRef.current?.getBoundingClientRect();
return r ? { x: e.clientX - r.left, y: e.clientY - r.top } : { x: 0, y: 0 };
}, []);
const closeMenu = useCallback(() => setCtxMenu(null), []);
/* ── Find handle near a point (for drop targeting) ──────────────────── */
const findHandleAt = useCallback((px: number, py: number, excludeNodeId?: string): { nodeId: string; side: HandleSide } | null => {
for (const n of nodes) {
if (n.id === excludeNodeId) continue;
for (const s of ["top", "right", "bottom", "left"] as HandleSide[]) {
const h = handlePos(n, s);
if (Math.hypot(h.x - px, h.y - py) < 18) return { nodeId: n.id, side: s };
}
}
return null;
}, [nodes]);
/* ── Node drag ──────────────────────────────────────────────────────── */
const onNodeDown = useCallback((e: React.PointerEvent, id: string) => {
e.stopPropagation();
const p = getPos(e);
const n = nodes.find((n) => n.id === id);
if (!n) return;
dragOffset.current = { dx: p.x - n.x, dy: p.y - n.y };
setDragging(id);
setSelected(id);
setSelectedEdge(null);
setShowHint(false);
hintDismissed.current = true;
closeMenu();
}, [nodes, getPos, closeMenu]);
/* ── Handle pointer down — start new connection ─────────────────────── */
const onHandleDown = useCallback((e: React.PointerEvent, nodeId: string, side: HandleSide) => {
e.stopPropagation();
const p = getPos(e);
setConnDrag({ mode: "new", anchorNode: nodeId, anchorSide: side, mx: p.x, my: p.y });
setSelected(null);
setSelectedEdge(null);
closeMenu();
}, [getPos, closeMenu]);
/* ── Edge endpoint drag — start reconnect ───────────────────────────── */
const onEdgeEndpointDown = useCallback((e: React.PointerEvent, edge: WFEdge, end: "from" | "to") => {
e.stopPropagation();
const p = getPos(e);
// The anchor is the OTHER end (the one that stays)
const anchorNode = end === "to" ? edge.from : edge.to;
const anchorSide = end === "to" ? edge.fromSide : edge.toSide;
setConnDrag({ mode: "reconnect", anchorNode, anchorSide, edgeId: edge.id, mx: p.x, my: p.y });
// Temporarily remove the edge being reconnected
setEdges((prev) => prev.filter((e) => e.id !== edge.id));
setSelectedEdge(null);
closeMenu();
}, [getPos, closeMenu]);
/* ── Pointer move on canvas ─────────────────────────────────────────── */
const onCanvasMove = useCallback((e: React.PointerEvent) => {
const p = getPos(e);
if (dragging) {
setNodes((prev) => prev.map((n) => n.id === dragging ? { ...n, x: Math.max(0, p.x - dragOffset.current.dx), y: Math.max(0, p.y - dragOffset.current.dy) } : n));
}
if (connDrag) {
setConnDrag((prev) => prev ? { ...prev, mx: p.x, my: p.y } : null);
// Update hover handle
const h = findHandleAt(p.x, p.y, connDrag.anchorNode);
setHoveredHandle(h);
}
}, [dragging, connDrag, getPos, findHandleAt]);
/* ── Pointer up on canvas ───────────────────────────────────────────── */
const onCanvasUp = useCallback(() => {
if (connDrag) {
const target = findHandleAt(connDrag.mx, connDrag.my, connDrag.anchorNode);
if (target) {
// Check for duplicate
const exists = edges.some((e) =>
(e.from === connDrag.anchorNode && e.to === target.nodeId) ||
(e.from === target.nodeId && e.to === connDrag.anchorNode)
);
if (!exists) {
setEdges((prev) => [...prev, {
id: eid(),
from: connDrag.anchorNode,
fromSide: connDrag.anchorSide,
to: target.nodeId,
toSide: target.side,
}]);
}
}
// If reconnecting and dropped on nothing, the edge is already removed — gone
setConnDrag(null);
setHoveredHandle(null);
}
setDragging(null);
}, [connDrag, edges, findHandleAt]);
/* ── Canvas background click ────────────────────────────────────────── */
const onCanvasDown = useCallback((e: React.PointerEvent) => {
setSelected(null);
setSelectedEdge(null);
setAddOpen(false);
if (showHint) { setShowHint(false); hintDismissed.current = true; }
closeMenu();
}, [closeMenu, showHint]);
/* ── Edge click ─────────────────────────────────────────────────────── */
const onEdgeClick = useCallback((e: React.MouseEvent, id: string) => {
e.stopPropagation();
setSelectedEdge(id);
setSelected(null);
closeMenu();
}, [closeMenu]);
/* ── Context menus ──────────────────────────────────────────────────── */
const onNodeCtx = useCallback((e: React.MouseEvent, id: string) => {
e.preventDefault(); e.stopPropagation();
setCtxMenu({ x: e.clientX, y: e.clientY, type: "node", targetId: id });
setSelected(id); setSelectedEdge(null);
}, []);
const onEdgeCtx = useCallback((e: React.MouseEvent, id: string) => {
e.preventDefault(); e.stopPropagation();
setCtxMenu({ x: e.clientX, y: e.clientY, type: "edge", targetId: id });
setSelectedEdge(id); setSelected(null);
}, []);
const onCanvasCtx = useCallback((e: React.MouseEvent) => {
e.preventDefault();
setCtxMenu({ x: e.clientX, y: e.clientY, type: "canvas" });
}, []);
/* ── Actions ────────────────────────────────────────────────────────── */
const deleteNode = useCallback((id: string) => {
setNodes((p) => p.filter((n) => n.id !== id));
setEdges((p) => p.filter((e) => e.from !== id && e.to !== id));
if (selected === id) setSelected(null);
closeMenu();
}, [selected, closeMenu]);
const deleteEdge = useCallback((id: string) => {
setEdges((p) => p.filter((e) => e.id !== id));
if (selectedEdge === id) setSelectedEdge(null);
closeMenu();
}, [selectedEdge, closeMenu]);
const addNode = useCallback((t: typeof palette[0]) => {
const id = `n${idCounter.current++}`;
setNodes((p) => [...p, { id, icon: t.icon, label: t.label, color: t.color, x: 80 + Math.random() * 800, y: 60 + Math.random() * 320 }]);
setSelected(id);
closeMenu();
setAddOpen(false);
setShowHint(false);
}, [closeMenu]);
const reset = useCallback(() => {
_eid = 1;
setNodes([
{ id: "n1", icon: "receipt", label: "Rechnung senden", subtitle: "Template: Standard-Rechnung", color: "#8B5CF6", x: 30, y: 220 },
{ id: "n2", icon: "calendar", label: "2 Wochen warten", color: "#F97316", x: 320, y: 230 },
{ id: "n3", icon: "check", label: "Bezahlt?", color: "#3B82F6", x: 610, y: 230 },
{ id: "n4", icon: "mail", label: "Bestätigung senden", subtitle: "Template: Zahlungseingang", color: "#22C55E", x: 900, y: 80 },
{ id: "n5", icon: "inbox", label: "Mahnung senden", subtitle: "Template: Zahlungserinnerung", color: "#EF4444", x: 900, y: 390 },
]);
setEdges([
{ id: eid(), from: "n1", fromSide: "right", to: "n2", toSide: "left" },
{ id: eid(), from: "n2", fromSide: "right", to: "n3", toSide: "left" },
{ id: eid(), from: "n3", fromSide: "top", to: "n4", toSide: "left" },
{ id: eid(), from: "n3", fromSide: "bottom", to: "n5", toSide: "left" },
{ id: eid(), from: "n5", fromSide: "left", to: "n1", toSide: "bottom" },
]);
setSelected(null); setSelectedEdge(null); closeMenu(); setAddOpen(false);
idCounter.current = 6;
}, [closeMenu]);
/* ── Hint: show on scroll into view, dismiss on hover ─────────────── */
useEffect(() => {
if (!canvasRef.current || hintDismissed.current) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && !hintDismissed.current) {
setShowHint(true);
}
},
{ threshold: 0.4 }
);
observer.observe(canvasRef.current);
return () => observer.disconnect();
}, []);
const dismissHint = useCallback(() => {
if (showHint) {
setShowHint(false);
hintDismissed.current = true;
}
}, [showHint]);
/* ── Keyboard ───────────────────────────────────────────────────────── */
useEffect(() => {
const fn = (e: KeyboardEvent) => {
if ((e.target as HTMLElement).tagName === "INPUT") return;
if (e.key === "Delete" || e.key === "Backspace") {
if (selected) deleteNode(selected);
else if (selectedEdge) deleteEdge(selectedEdge);
}
if (e.key === "Escape") closeMenu();
};
window.addEventListener("keydown", fn);
return () => window.removeEventListener("keydown", fn);
}, [selected, selectedEdge, deleteNode, deleteEdge, closeMenu]);
useEffect(() => {
if (!ctxMenu) return;
const fn = () => closeMenu();
window.addEventListener("pointerdown", fn);
return () => window.removeEventListener("pointerdown", fn);
}, [ctxMenu, closeMenu]);
/* ── Render ─────────────────────────────────────────────────────────── */
return (
<section className="section-full" style={{ background: "var(--surface)", paddingBlock: hideHeader ? 40 : 80 }}>
<div className="mx-auto" style={{ maxWidth: "var(--content-width)" }}>
{!hideHeader && (
<div className="flex flex-col items-center gap-4 text-center mb-10">
<span className="text-[12px] font-semibold tracking-widest chamfer-badge px-2 py-0.5" style={{ background: "var(--accent-yellow-light)", color: "var(--accent-yellow-dark)" }}>WORKFLOW EDITOR</span>
<h2 className="text-[32px] md:text-[42px] font-bold leading-[1.15]" style={{ color: "var(--text-primary)" }}>Interaktiver Workflow Builder</h2>
<p className="text-[16px] leading-relaxed max-w-2xl" style={{ color: "var(--text-secondary)" }}>Erstellen Sie automatisierte Abläufe, visuell und ohne Code.</p>
</div>
)}
{/* Canvas — desktop only */}
<div className="relative">
{/* Pop-up hint now inside canvas below */}
<div
ref={canvasRef}
className="relative rounded-2xl select-none hidden xl:block"
style={{
height: 600, background: "#FAFBFD",
border: "1px solid var(--border-light)",
backgroundImage: "radial-gradient(circle, #E5E7EB 1px, transparent 1px)",
backgroundSize: "24px 24px",
cursor: dragging ? "grabbing" : connDrag ? "crosshair" : "default",
overflow: "hidden",
}}
onPointerDown={onCanvasDown}
onPointerMove={onCanvasMove}
onPointerUp={onCanvasUp}
onContextMenu={onCanvasCtx}
>
{/* ── Top-left buttons: + and Reset ──────────────────────── */}
<div className="absolute top-4 left-4 z-[60] flex items-center gap-2" onPointerDown={(e) => e.stopPropagation()}>
<button
onClick={() => setAddOpen((v) => !v)}
className="w-[54px] h-[54px] rounded-2xl flex items-center justify-center transition-transform hover:scale-[1.03] active:scale-95"
style={{
background: addOpen ? "var(--accent-teal)" : "rgba(241,183,41,0.12)",
color: addOpen ? "#FFFFFF" : "#1A1A1A",
border: addOpen ? "none" : "1.5px solid rgba(241,183,41,0.3)",
boxShadow: "0 2px 8px rgba(0,0,0,0.04)",
}}
>
<svg width="20" height="20" viewBox="0 0 18 18" fill="none" style={{ transform: addOpen ? "rotate(45deg)" : "none", transition: "transform 0.2s ease" }}>
<path d="M9 3v12M3 9h12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
</button>
<button
onClick={reset}
className="w-[54px] h-[54px] rounded-2xl flex items-center justify-center transition-transform hover:scale-[1.03] active:scale-95"
style={{
background: "rgba(241,183,41,0.12)",
color: "#1A1A1A",
border: "1.5px solid rgba(241,183,41,0.3)",
boxShadow: "0 2px 8px rgba(0,0,0,0.04)",
}}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="1 4 1 10 7 10" />
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" />
</svg>
</button>
{/* Dropdown */}
{addOpen && (
<div
className="absolute top-11 left-0 rounded-xl py-2 min-w-[180px]"
style={{
background: "#FFFFFF",
border: "1px solid var(--border-light)",
boxShadow: "0 12px 32px rgba(0,0,0,0.12)",
animation: "wf-dropdown-in 0.2s ease",
}}
>
<style dangerouslySetInnerHTML={{ __html: `
@keyframes wf-dropdown-in {
from { opacity: 0; transform: translateY(-6px) scale(0.96); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
`}} />
{palette.map((t) => (
<button
key={t.icon}
onClick={() => addNode(t)}
className="w-full text-left px-4 py-2 text-[13px] font-medium hover:bg-[var(--bg-muted)] transition-colors flex items-center gap-2.5"
style={{ color: "var(--text-primary)" }}
>
<div className="w-6 h-6 rounded flex items-center justify-center shrink-0" style={{ background: `${t.color}14` }}>
{icons[t.icon]?.(t.color)}
</div>
{t.label}
</button>
))}
</div>
)}
</div>
{/* ── Hint popup — centered in canvas viewport ─────────────── */}
{showHint && (
<div data-canvas-hint className="absolute inset-0 z-[55] flex items-center justify-center" style={{ pointerEvents: "none" }}>
<style dangerouslySetInnerHTML={{ __html: `
@keyframes wf-popup-in { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }
@keyframes wf-mini-drag { 0%,100% { transform: translate(0,0); } 20% { transform: translate(0,-4px); } 40% { transform: translate(34px,-4px); } 60% { transform: translate(34px,0); } 80% { transform: translate(0,0); } }
@keyframes wf-mini-cursor { 0%,15% { transform: translate(38px,24px); } 20% { transform: translate(22px,16px); } 40%,60% { transform: translate(58px,16px); } 65% { transform: translate(60px,24px); } 80%,100% { transform: translate(38px,24px); } }
`}} />
<div className="relative flex flex-col items-center gap-3 rounded-2xl px-8 py-6" style={{ background: "rgba(255,255,255,0.97)", border: "1px solid var(--border-light)", boxShadow: "0 12px 40px rgba(0,0,0,0.12)", animation: "wf-popup-in 0.3s ease both", pointerEvents: "auto" }}>
{/* X close button */}
<button
onClick={dismissHint}
className="absolute top-2.5 right-2.5 w-6 h-6 rounded-md flex items-center justify-center hover:bg-[var(--bg-muted)] transition-colors"
style={{ color: "var(--text-muted)" }}
>
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
<path d="M2 2l8 8M10 2l-8 8" />
</svg>
</button>
{/* Mini animation — large */}
<div className="relative" style={{ width: 90, height: 50 }}>
<div style={{ width: 36, height: 24, borderRadius: 6, border: "2px solid #B0B8C4", background: "#F3F4F6", animation: "wf-mini-drag 3s ease-in-out infinite", position: "absolute", top: 8, left: 6 }} />
<div style={{ width: 36, height: 24, borderRadius: 6, border: "2px solid var(--accent-teal)", background: "var(--accent-teal-light)", position: "absolute", top: 16, left: 44, opacity: 0.45 }} />
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ position: "absolute", animation: "wf-mini-cursor 3s ease-in-out infinite" }}>
<path d="M5 3l14 8-6 2-4 6z" fill="#1A1A1A" stroke="white" strokeWidth="1.5" />
</svg>
</div>
<span className="text-[15px] font-semibold" style={{ color: "var(--text-primary)" }}>Nodes verschieben & verbinden</span>
<span className="text-[12px]" style={{ color: "var(--text-muted)" }}>Klicke auf einen Node um loszulegen</span>
</div>
</div>
)}
{/* SVG layer */}
<svg className="absolute inset-0 w-full h-full" style={{ zIndex: 1, pointerEvents: "none" }}>
{edges.map((edge) => {
const fn = nodes.find((n) => n.id === edge.from);
const tn = nodes.find((n) => n.id === edge.to);
if (!fn || !tn) return null;
const p1 = offsetPoint(handlePos(fn, edge.fromSide).x, handlePos(fn, edge.fromSide).y, edge.fromSide, HANDLE_OFFSET);
const p2 = offsetPoint(handlePos(tn, edge.toSide).x, handlePos(tn, edge.toSide).y, edge.toSide, HANDLE_OFFSET);
const d = edgePath(p1.x, p1.y, edge.fromSide, p2.x, p2.y, edge.toSide);
const isSel = selectedEdge === edge.id;
const pathLen = approxPathLength(p1.x, p1.y, edge.fromSide, p2.x, p2.y, edge.toSide);
const SPEED = 80; // pixels per second
const dur = rnd(Math.max(1.5, pathLen / SPEED));
return (
<g key={edge.id}>
{/* Hit area */}
<path d={d} fill="none" stroke="transparent" strokeWidth="16" style={{ pointerEvents: "stroke", cursor: "pointer" }} onClick={(e) => onEdgeClick(e, edge.id)} onContextMenu={(e) => onEdgeCtx(e, edge.id)} />
{/* Visible edge — semi-transparent */}
<path d={d} fill="none" stroke={isSel ? "var(--accent-teal)" : "rgba(139,145,154,0.35)"} strokeWidth={isSel ? 2.5 : 1.8} style={{ pointerEvents: "none" }} />
{/* Arrowhead */}
{(() => {
const dir = sideDir(edge.toSide);
const ax = p2.x, ay = p2.y;
const angle = Math.atan2(-dir.dy, -dir.dx);
const size = 6;
const p = [
{ x: ax + Math.cos(angle) * size, y: ay + Math.sin(angle) * size },
{ x: ax + Math.cos(angle + 2.4) * size * 0.7, y: ay + Math.sin(angle + 2.4) * size * 0.7 },
{ x: ax + Math.cos(angle - 2.4) * size * 0.7, y: ay + Math.sin(angle - 2.4) * size * 0.7 },
];
return <polygon points={p.map(pt => `${rnd(pt.x)},${rnd(pt.y)}`).join(" ")} fill={isSel ? "var(--accent-teal)" : "rgba(139,145,154,0.45)"} style={{ pointerEvents: "none" }} />;
})()}
{/* Animated dot */}
{/* Animated flow dots — count based on path length for even spacing */}
{(() => {
const DOT_SPACING_PX = 80; // desired pixel distance between dots
const numDots = Math.max(1, Math.min(3, Math.floor(pathLen / DOT_SPACING_PX)));
const spacing = dur / numDots;
return Array.from({ length: numDots }, (_, di) => (
<circle key={di} r="3" fill="var(--accent-yellow)" opacity="0.55" style={{ pointerEvents: "none", filter: "drop-shadow(0 0 4px rgba(241,183,41,0.8)) drop-shadow(0 0 10px rgba(241,183,41,0.4))" }}>
<animateMotion dur={`${dur}s`} repeatCount="indefinite" begin={`${rnd(di * spacing)}s`} calcMode="linear" path={d} />
</circle>
));
})()}
{/* Draggable endpoint circles (for reconnection) */}
<circle cx={p1.x} cy={p1.y} r="8" fill="transparent" style={{ pointerEvents: "all", cursor: "grab" }} onPointerDown={(e) => { e.stopPropagation(); onEdgeEndpointDown(e as any, edge, "from"); }} />
<circle cx={p2.x} cy={p2.y} r="8" fill="transparent" style={{ pointerEvents: "all", cursor: "grab" }} onPointerDown={(e) => { e.stopPropagation(); onEdgeEndpointDown(e as any, edge, "to"); }} />
</g>
);
})}
{/* Connection being drawn */}
{connDrag && (() => {
const an = nodes.find((n) => n.id === connDrag.anchorNode);
if (!an) return null;
const ap = offsetPoint(handlePos(an, connDrag.anchorSide).x, handlePos(an, connDrag.anchorSide).y, connDrag.anchorSide, HANDLE_OFFSET);
return <path d={freePath(ap.x, ap.y, connDrag.anchorSide, connDrag.mx, connDrag.my)} fill="none" stroke="var(--accent-teal)" strokeWidth="2" strokeDasharray="6 3" opacity={0.7} style={{ pointerEvents: "none" }} />;
})()}
</svg>
{/* Nodes */}
{nodes.map((node) => {
const isSel = selected === node.id;
const isDrag = dragging === node.id;
const hasSub = !!node.subtitle;
const nodeH = hasSub ? 70 : NODE_H;
const sides: HandleSide[] = ["top", "right", "bottom", "left"];
return (
<div
key={node.id}
className="absolute flex items-center gap-2.5"
style={{
left: node.x, top: node.y, width: NODE_W, height: nodeH,
padding: "0 12px 0 16px",
background: "#FFFFFF",
borderRadius: 10,
// neutral 1px card + subtle shadow (colour lives in the accent
// bar, not the whole border) — clean, not "vibecoded"
border: `1px solid ${isSel ? node.color : "var(--border-light)"}`,
boxShadow: isSel
? `0 0 0 3px ${node.color}22, 0 4px 12px rgba(15,23,42,0.10)`
: isDrag
? "0 10px 26px rgba(15,23,42,0.14)"
: "0 1px 2px rgba(15,23,42,0.06)",
cursor: isDrag ? "grabbing" : "grab",
zIndex: isDrag ? 50 : isSel ? 40 : 10,
userSelect: "none",
transition: isDrag ? "none" : "border-color 0.15s, box-shadow 0.15s",
}}
onPointerDown={(e) => onNodeDown(e, node.id)}
onContextMenu={(e) => onNodeCtx(e, node.id)}
>
{/* left accent bar — the node's colour, not the whole border */}
<span className="absolute rounded-r-full" style={{ left: 0, top: 8, bottom: 8, width: 3, background: node.color }} />
{/* 4 handles */}
{sides.map((side) => {
const isHovered = hoveredHandle?.nodeId === node.id && hoveredHandle?.side === side;
const hh = nodeH;
const pos = side === "top" ? { left: "50%", top: -HANDLE_R, transform: "translateX(-50%)" }
: side === "right" ? { right: -HANDLE_R, top: "50%", transform: "translateY(-50%)" }
: side === "bottom" ? { left: "50%", bottom: -HANDLE_R, transform: "translateX(-50%)" }
: { left: -HANDLE_R, top: "50%", transform: "translateY(-50%)" };
return (
<div
key={side}
className="absolute rounded-full border-[2px] border-white transition-transform"
style={{
...pos,
width: HANDLE_R * 2,
height: HANDLE_R * 2,
background: isHovered ? "var(--accent-teal)" : node.color,
zIndex: 20,
cursor: "crosshair",
transform: `${pos.transform ?? ""} ${isHovered ? " scale(1.5)" : ""}`,
} as React.CSSProperties}
onPointerDown={(e) => onHandleDown(e, node.id, side)}
/>
);
})}
{/* Icon */}
<div className="w-8 h-8 rounded-md flex items-center justify-center shrink-0" style={{ background: `${node.color}14` }}>
{icons[node.icon]?.(node.color)}
</div>
{/* Label + optional subtitle */}
<div className="flex flex-col min-w-0">
<span className="text-[12px] font-semibold truncate" style={{ color: "var(--text-primary)" }}>{node.label}</span>
{node.subtitle && (
<span className="text-[10px] truncate" style={{ color: "var(--text-muted)", marginTop: 1 }}>{node.subtitle}</span>
)}
</div>
</div>
);
})}
{nodes.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center">
<p className="text-[14px] font-medium" style={{ color: "var(--text-muted)" }}>Klicke auf einen Node in der Palette um loszulegen.</p>
</div>
)}
</div>
</div>
{/* Mobile fallback — static flow diagram with branching */}
<div className="xl:hidden rounded-2xl overflow-hidden" style={{ background: "#FAFBFD", border: "1px solid var(--border-light)", padding: "24px 20px" }}>
<div className="flex flex-col items-center">
{/* ── Linear flow: Rechnung → 2 Wochen → Bezahlt? ────── */}
{[
{ id: "n1", icon: "receipt", label: "Rechnung senden", subtitle: "Template: Standard-Rechnung", color: "#8B5CF6" },
{ id: "n2", icon: "calendar", label: "2 Wochen warten", subtitle: "Frist für Zahlungseingang", color: "#F97316" },
{ id: "n3", icon: "check", label: "Bezahlt?", subtitle: "Automatische Prüfung", color: "#3B82F6" },
].map((node, i) => (
<div key={node.id} className="flex flex-col items-center w-full" style={{ maxWidth: 280 }}>
{/* Node card */}
<div
className="relative flex items-center gap-3 w-full"
style={{
padding: "12px 16px 12px 18px",
background: "#FFFFFF",
borderRadius: 10,
border: "1px solid var(--border-light)",
boxShadow: "0 1px 2px rgba(15,23,42,0.06)",
}}
>
<span className="absolute rounded-r-full" style={{ left: 0, top: 8, bottom: 8, width: 3, background: node.color }} />
<div className="w-8 h-8 rounded-md flex items-center justify-center shrink-0" style={{ background: `${node.color}14` }}>
{icons[node.icon]?.(node.color)}
</div>
<div className="flex flex-col min-w-0">
<span className="text-[13px] font-semibold" style={{ color: "var(--text-primary)" }}>{node.label}</span>
<span className="text-[10px]" style={{ color: "var(--text-muted)", marginTop: 1 }}>{node.subtitle}</span>
</div>
</div>
{/* Down-arrow connector */}
<div className="flex flex-col items-center py-1">
<svg width="16" height="24" viewBox="0 0 16 24" fill="none">
<path d="M8 0v18" stroke="#D5DBE1" strokeWidth="1.5" />
<path d="M4 16l4 6 4-6" stroke="#D5DBE1" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</div>
</div>
))}
{/* ── Branch: two columns after Bezahlt? ─────────────── */}
<div className="grid grid-cols-2 gap-3 w-full" style={{ maxWidth: 320 }}>
{/* Left branch — Ja → Bestätigung senden */}
<div className="flex flex-col items-center">
{/* Ja label */}
<span className="inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-full mb-1.5" style={{ background: "#DCFCE7", color: "#166534" }}>
Ja
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
<path d="M2 8L8 2" stroke="#166534" strokeWidth="1.5" strokeLinecap="round" />
<path d="M3 2h5v5" stroke="#166534" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
{/* Down arrow */}
<svg width="16" height="20" viewBox="0 0 16 20" fill="none" className="mb-1.5">
<path d="M8 0v14" stroke="#22C55E" strokeWidth="1.5" />
<path d="M4 12l4 6 4-6" stroke="#22C55E" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
{/* Bestätigung senden card */}
<div
className="relative flex flex-col gap-1.5 w-full"
style={{
padding: "10px 12px 10px 14px",
background: "#FFFFFF",
borderRadius: 10,
border: "1px solid var(--border-light)",
boxShadow: "0 1px 2px rgba(15,23,42,0.06)",
}}
>
<span className="absolute rounded-r-full" style={{ left: 0, top: 8, bottom: 8, width: 3, background: "#22C55E" }} />
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-md flex items-center justify-center shrink-0" style={{ background: "#22C55E14" }}>
{icons.mail("#22C55E")}
</div>
<span className="text-[12px] font-semibold leading-tight" style={{ color: "var(--text-primary)" }}>Bestätigung senden</span>
</div>
<span className="text-[9px]" style={{ color: "var(--text-muted)" }}>Template: Zahlungseingang</span>
</div>
</div>
{/* Right branch — Nein → Mahnung senden */}
<div className="flex flex-col items-center">
{/* Nein label */}
<span className="inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-full mb-1.5" style={{ background: "#FEE2E2", color: "#991B1B" }}>
Nein
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
<path d="M2 2L8 8" stroke="#991B1B" strokeWidth="1.5" strokeLinecap="round" />
<path d="M3 8h5V3" stroke="#991B1B" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
{/* Down arrow */}
<svg width="16" height="20" viewBox="0 0 16 20" fill="none" className="mb-1.5">
<path d="M8 0v14" stroke="#EF4444" strokeWidth="1.5" />
<path d="M4 12l4 6 4-6" stroke="#EF4444" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
{/* Mahnung senden card */}
<div
className="relative flex flex-col gap-1.5 w-full"
style={{
padding: "10px 12px 10px 14px",
background: "#FFFFFF",
borderRadius: 10,
border: "1px solid var(--border-light)",
boxShadow: "0 1px 2px rgba(15,23,42,0.06)",
}}
>
<span className="absolute rounded-r-full" style={{ left: 0, top: 8, bottom: 8, width: 3, background: "#EF4444" }} />
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-md flex items-center justify-center shrink-0" style={{ background: "#EF444414" }}>
{icons.inbox("#EF4444")}
</div>
<span className="text-[12px] font-semibold leading-tight" style={{ color: "var(--text-primary)" }}>Mahnung senden</span>
</div>
<span className="text-[9px]" style={{ color: "var(--text-muted)" }}>Template: Zahlungserinnerung</span>
</div>
{/* Loop arrow */}
<div className="flex items-center gap-1.5 mt-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#D5DBE1" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<polyline points="1 4 1 10 7 10" />
<path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10" />
</svg>
<span className="text-[9px] font-medium" style={{ color: "var(--text-muted)" }}>Zurück zu Schritt 1</span>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Context menu */}
{ctxMenu && (
<div className="fixed z-[9999] rounded-lg py-1 min-w-[160px]" style={{ left: ctxMenu.x, top: ctxMenu.y, background: "#FFF", border: "1px solid var(--border-light)", boxShadow: "0 8px 24px rgba(0,0,0,0.12)" }} onPointerDown={(e) => e.stopPropagation()}>
{ctxMenu.type === "node" && ctxMenu.targetId && (<>
<button className="w-full text-left px-4 py-2 text-[13px] font-medium hover:bg-[var(--bg-muted)]" style={{ color: "var(--text-primary)" }} onClick={() => { const o = nodes.find(n => n.id === ctxMenu.targetId); if (o) { const id = `n${idCounter.current++}`; setNodes(p => [...p, { ...o, id, x: o.x + 30, y: o.y + 30 }]); } closeMenu(); }}>Duplizieren</button>
<div style={{ height: 1, background: "var(--border-light)", margin: "2px 0" }} />
<button className="w-full text-left px-4 py-2 text-[13px] font-medium hover:bg-red-50" style={{ color: "#EF4444" }} onClick={() => deleteNode(ctxMenu.targetId!)}>Node löschen</button>
</>)}
{ctxMenu.type === "edge" && ctxMenu.targetId && (
<button className="w-full text-left px-4 py-2 text-[13px] font-medium hover:bg-red-50" style={{ color: "#EF4444" }} onClick={() => deleteEdge(ctxMenu.targetId!)}>Verbindung löschen</button>
)}
{ctxMenu.type === "canvas" && (<>
{palette.slice(0, 4).map((t) => (
<button key={t.icon} className="w-full text-left px-4 py-2 text-[13px] font-medium hover:bg-[var(--bg-muted)] flex items-center gap-2" style={{ color: "var(--text-primary)" }} onClick={() => addNode(t)}>{icons[t.icon]?.(t.color)} {t.label} hinzufügen</button>
))}
<div style={{ height: 1, background: "var(--border-light)", margin: "2px 0" }} />
<button className="w-full text-left px-4 py-2 text-[13px] font-medium hover:bg-[var(--bg-muted)]" style={{ color: "var(--text-secondary)" }} onClick={reset}>Alles zurücksetzen</button>
</>)}
</div>
)}
</section>
);
}