Enhance canvas functionality with new node types and validation

- Added support for new canvas node types: curves, color-adjust, light-adjust, detail-adjust, and render.
- Implemented validation for adjustment nodes to restrict incoming edges to one.
- Updated canvas connection validation to improve user feedback on invalid connections.
- Enhanced node creation and rendering logic to accommodate new node types and their properties.
- Refactored related components and utilities for better maintainability and performance.
This commit is contained in:
Matthias
2026-04-02 11:39:05 +02:00
parent 9bab9bb93d
commit f3c5c2d8f1
52 changed files with 5755 additions and 44 deletions

View File

@@ -0,0 +1,38 @@
"use client";
import { Slider } from "@/components/ui/slider";
export function SliderRow({
label,
value,
min,
max,
step = 1,
onChange,
}: {
label: string;
value: number;
min: number;
max: number;
step?: number;
onChange: (nextValue: number) => void;
}) {
return (
<div className="space-y-1">
<div className="flex items-center justify-between text-[11px] text-muted-foreground">
<span>{label}</span>
<span className="font-medium text-foreground">{value.toFixed(step < 1 ? 2 : 0)}</span>
</div>
<Slider
value={[value]}
min={min}
max={max}
step={step}
onValueChange={(values) => {
onChange(values[0] ?? value);
}}
className="nodrag nowheel"
/>
</div>
);
}

View File

@@ -0,0 +1,220 @@
"use client";
import { useMemo } from "react";
import { useStore, type Node } from "@xyflow/react";
import { usePipelinePreview } from "@/hooks/use-pipeline-preview";
import { collectPipeline, getSourceImage, type PipelineStep } from "@/lib/image-pipeline/contracts";
const PREVIEW_PIPELINE_TYPES = new Set([
"curves",
"color-adjust",
"light-adjust",
"detail-adjust",
]);
function resolveNodeImageUrl(node: Node): string | null {
const data = (node.data ?? {}) as Record<string, unknown>;
const directUrl = typeof data.url === "string" ? data.url : null;
if (directUrl && directUrl.length > 0) {
return directUrl;
}
const previewUrl = typeof data.previewUrl === "string" ? data.previewUrl : null;
if (previewUrl && previewUrl.length > 0) {
return previewUrl;
}
return null;
}
function compactHistogram(values: readonly number[], points = 64): number[] {
if (points <= 0) {
return [];
}
if (values.length === 0) {
return Array.from({ length: points }, () => 0);
}
const bucket = values.length / points;
const compacted: number[] = [];
for (let pointIndex = 0; pointIndex < points; pointIndex += 1) {
let sum = 0;
const start = Math.floor(pointIndex * bucket);
const end = Math.min(values.length, Math.floor((pointIndex + 1) * bucket) || start + 1);
for (let index = start; index < end; index += 1) {
sum += values[index] ?? 0;
}
compacted.push(sum);
}
return compacted;
}
function histogramPolyline(values: readonly number[], maxValue: number, width: number, height: number): string {
if (values.length === 0) {
return "";
}
const divisor = Math.max(1, values.length - 1);
return values
.map((value, index) => {
const x = (index / divisor) * width;
const normalized = maxValue > 0 ? value / maxValue : 0;
const y = height - normalized * height;
return `${x.toFixed(2)},${y.toFixed(2)}`;
})
.join(" ");
}
export default function AdjustmentPreview({
nodeId,
nodeWidth,
currentType,
currentParams,
}: {
nodeId: string;
nodeWidth: number;
currentType: string;
currentParams: unknown;
}) {
const nodes = useStore((state) => state.nodes);
const edges = useStore((state) => state.edges);
const pipelineNodes = useMemo(
() => nodes.map((node) => ({ id: node.id, type: node.type ?? "", data: node.data })),
[nodes],
);
const pipelineEdges = useMemo(
() => edges.map((edge) => ({ source: edge.source, target: edge.target })),
[edges],
);
const sourceUrl = useMemo(
() =>
getSourceImage({
nodeId,
nodes: pipelineNodes,
edges: pipelineEdges,
isSourceNode: (node) =>
node.type === "image" || node.type === "ai-image" || node.type === "asset",
getSourceImageFromNode: (node) => {
const sourceNode = nodes.find((candidate) => candidate.id === node.id);
return sourceNode ? resolveNodeImageUrl(sourceNode) : null;
},
}),
[nodeId, nodes, pipelineEdges, pipelineNodes],
);
const steps = useMemo(() => {
const collected = collectPipeline({
nodeId,
nodes: pipelineNodes,
edges: pipelineEdges,
isPipelineNode: (node) => PREVIEW_PIPELINE_TYPES.has(node.type ?? ""),
});
return collected.map((step) => {
if (step.nodeId === nodeId && step.type === currentType) {
return {
...step,
params: currentParams,
} as PipelineStep;
}
return step as PipelineStep;
});
}, [currentParams, currentType, nodeId, pipelineEdges, pipelineNodes]);
const { canvasRef, histogram, isRendering, hasSource, previewAspectRatio, error } =
usePipelinePreview({
sourceUrl,
steps,
nodeWidth,
});
const histogramSeries = useMemo(() => {
const red = compactHistogram(histogram.red, 64);
const green = compactHistogram(histogram.green, 64);
const blue = compactHistogram(histogram.blue, 64);
const rgb = compactHistogram(histogram.rgb, 64);
const max = Math.max(1, ...red, ...green, ...blue, ...rgb);
return { red, green, blue, rgb, max };
}, [histogram.blue, histogram.green, histogram.red, histogram.rgb]);
const histogramPolylines = useMemo(() => {
const width = 96;
const height = 44;
return {
red: histogramPolyline(histogramSeries.red, histogramSeries.max, width, height),
green: histogramPolyline(histogramSeries.green, histogramSeries.max, width, height),
blue: histogramPolyline(histogramSeries.blue, histogramSeries.max, width, height),
rgb: histogramPolyline(histogramSeries.rgb, histogramSeries.max, width, height),
};
}, [histogramSeries.blue, histogramSeries.green, histogramSeries.max, histogramSeries.red, histogramSeries.rgb]);
return (
<div className="space-y-2">
<div
className="relative overflow-hidden rounded-md border border-border bg-muted/30"
style={{ aspectRatio: `${Math.max(0.25, previewAspectRatio)}` }}
>
{!hasSource ? (
<div className="absolute inset-0 flex items-center justify-center px-3 text-center text-[11px] text-muted-foreground">
Verbinde eine Bild-, Asset- oder KI-Bild-Node fuer Live-Preview.
</div>
) : null}
{hasSource ? (
<canvas
ref={canvasRef}
className="h-full w-full"
/>
) : null}
{isRendering ? (
<div className="absolute right-1 top-1 rounded bg-background/80 px-1.5 py-0.5 text-[10px] text-muted-foreground">
Rendering...
</div>
) : null}
<div className="absolute bottom-2 right-2 z-10 w-28 rounded-md border border-border/80 bg-background/85 px-2 py-1.5 backdrop-blur-sm">
<svg
viewBox="0 0 96 44"
className="h-11 w-full"
role="img"
aria-label="Histogramm als RGB-Linienkurven"
>
<polyline
points={histogramPolylines.rgb}
fill="none"
stroke="rgba(248, 250, 252, 0.9)"
strokeWidth={1.6}
strokeLinecap="round"
strokeLinejoin="round"
/>
<polyline
points={histogramPolylines.red}
fill="none"
stroke="rgba(248, 113, 113, 0.9)"
strokeWidth={1.2}
strokeLinecap="round"
strokeLinejoin="round"
/>
<polyline
points={histogramPolylines.green}
fill="none"
stroke="rgba(74, 222, 128, 0.85)"
strokeWidth={1.2}
strokeLinecap="round"
strokeLinejoin="round"
/>
<polyline
points={histogramPolylines.blue}
fill="none"
stroke="rgba(96, 165, 250, 0.88)"
strokeWidth={1.2}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
</div>
{error ? <p className="text-[11px] text-destructive">{error}</p> : null}
</div>
);
}

View File

@@ -11,6 +11,7 @@ import {
} from "@xyflow/react";
import { Trash2, Copy } from "lucide-react";
import { useCanvasPlacement } from "@/components/canvas/canvas-placement-context";
import { isCanvasNodeType } from "@/lib/canvas-node-types";
import { NodeErrorBoundary } from "./node-error-boundary";
interface ResizeConfig {
@@ -38,6 +39,11 @@ const RESIZE_CONFIGS: Record<string, ResizeConfig> = {
"ai-image": { minWidth: 200, minHeight: 208, keepAspectRatio: false },
compare: { minWidth: 300, minHeight: 200 },
prompt: { minWidth: 260, minHeight: 220 },
curves: { minWidth: 240, minHeight: 320 },
"color-adjust": { minWidth: 240, minHeight: 360 },
"light-adjust": { minWidth: 240, minHeight: 360 },
"detail-adjust": { minWidth: 240, minHeight: 360 },
render: { minWidth: 260, minHeight: 300, keepAspectRatio: true },
text: { minWidth: 220, minHeight: 90 },
note: { minWidth: 200, minHeight: 90 },
};
@@ -58,6 +64,19 @@ const INTERNAL_FIELDS = new Set([
"retryCount",
"url",
"canvasId",
"lastRenderedAt",
"lastRenderedHash",
"lastRenderWidth",
"lastRenderHeight",
"lastRenderFormat",
"lastRenderMimeType",
"lastRenderSizeBytes",
"lastRenderQuality",
"lastRenderSourceWidth",
"lastRenderSourceHeight",
"lastRenderWasSizeClamped",
"lastRenderError",
"lastRenderErrorHash",
]);
function NodeToolbarActions({
@@ -128,7 +147,10 @@ function NodeToolbarActions({
// Fire-and-forget: optimistic update makes the duplicate appear instantly
void createNodeWithIntersection({
type: node.type ?? "text",
type:
typeof node.type === "string" && isCanvasNodeType(node.type)
? node.type
: "text",
position: {
x: originalPosition.x + 50,
y: originalPosition.y + 50,
@@ -213,6 +235,7 @@ export default function BaseNodeWrapper({
analyzing: "border-yellow-400 animate-pulse",
clarifying: "border-amber-400",
executing: "border-yellow-400 animate-pulse",
rendering: "border-yellow-400 animate-pulse",
done: "border-green-500",
error: "border-red-500",
};

View File

@@ -0,0 +1,257 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
import { useMutation } from "convex/react";
import { Palette } from "lucide-react";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useAuthQuery } from "@/hooks/use-auth-query";
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
import { useCanvasSync } from "@/components/canvas/canvas-sync-context";
import { SliderRow } from "@/components/canvas/nodes/adjustment-controls";
import BaseNodeWrapper from "@/components/canvas/nodes/base-node-wrapper";
import AdjustmentPreview from "@/components/canvas/nodes/adjustment-preview";
import {
cloneAdjustmentData,
DEFAULT_COLOR_ADJUST_DATA,
normalizeColorAdjustData,
type ColorAdjustData,
} from "@/lib/image-pipeline/adjustment-types";
import { COLOR_PRESETS } from "@/lib/image-pipeline/presets";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "@/lib/toast";
type ColorAdjustNodeData = ColorAdjustData & {
_status?: string;
_statusMessage?: string;
};
export type ColorAdjustNodeType = Node<ColorAdjustNodeData, "color-adjust">;
type PresetDoc = {
_id: Id<"adjustmentPresets">;
name: string;
params: unknown;
};
export default function ColorAdjustNode({ id, data, selected, width }: NodeProps<ColorAdjustNodeType>) {
const { queueNodeDataUpdate } = useCanvasSync();
const savePreset = useMutation(api.presets.save);
const userPresets = (useAuthQuery(api.presets.list, { nodeType: "color-adjust" }) ?? []) as PresetDoc[];
const [localData, setLocalData] = useState<ColorAdjustData>(() =>
normalizeColorAdjustData({ ...cloneAdjustmentData(DEFAULT_COLOR_ADJUST_DATA), ...data }),
);
const [presetSelection, setPresetSelection] = useState("custom");
const localDataRef = useRef(localData);
useEffect(() => {
localDataRef.current = localData;
}, [localData]);
useEffect(() => {
const timer = window.setTimeout(() => {
setLocalData(
normalizeColorAdjustData({ ...cloneAdjustmentData(DEFAULT_COLOR_ADJUST_DATA), ...data }),
);
}, 0);
return () => {
window.clearTimeout(timer);
};
}, [data]);
const queueSave = useDebouncedCallback(() => {
void queueNodeDataUpdate({
nodeId: id as Id<"nodes">,
data: localDataRef.current,
});
}, 16);
const updateData = (updater: (draft: ColorAdjustData) => ColorAdjustData) => {
setPresetSelection("custom");
setLocalData((current) => {
const next = updater(current);
localDataRef.current = next;
queueSave();
return next;
});
};
const builtinOptions = useMemo(() => Object.entries(COLOR_PRESETS), []);
const applyPresetValue = (value: string) => {
if (value === "custom") {
setPresetSelection("custom");
return;
}
if (value.startsWith("builtin:")) {
const key = value.replace("builtin:", "");
const preset = COLOR_PRESETS[key];
if (!preset) return;
const next = cloneAdjustmentData(preset);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
return;
}
if (value.startsWith("user:")) {
const presetId = value.replace("user:", "") as Id<"adjustmentPresets">;
const preset = userPresets.find((entry) => entry._id === presetId);
if (!preset) return;
const next = normalizeColorAdjustData(preset.params);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
}
};
const handleSavePreset = async () => {
const name = window.prompt("Preset-Name");
if (!name) return;
await savePreset({
name,
nodeType: "color-adjust",
params: localData,
});
toast.success("Preset gespeichert");
};
return (
<BaseNodeWrapper
nodeType="color-adjust"
selected={selected}
status={data._status}
statusMessage={data._statusMessage}
className="min-w-[240px] border-cyan-500/30"
>
<Handle
type="target"
position={Position.Left}
className="!h-3 !w-3 !border-2 !border-background !bg-cyan-500"
/>
<div className="space-y-3 p-3">
<div className="flex items-center gap-1.5 text-xs font-medium text-cyan-700 dark:text-cyan-400">
<Palette className="h-3.5 w-3.5" />
Farbe
</div>
<div className="flex items-center gap-2">
<Select value={presetSelection} onValueChange={applyPresetValue}>
<SelectTrigger className="nodrag h-8 text-xs" size="sm">
<SelectValue placeholder="Preset" />
</SelectTrigger>
<SelectContent className="nodrag">
<SelectItem value="custom">Custom</SelectItem>
{builtinOptions.map(([name]) => (
<SelectItem key={name} value={`builtin:${name}`}>
Built-in: {name}
</SelectItem>
))}
{userPresets.map((preset) => (
<SelectItem key={preset._id} value={`user:${preset._id}`}>
User: {preset.name}
</SelectItem>
))}
</SelectContent>
</Select>
<button
type="button"
className="nodrag rounded-md border px-2 py-1 text-[11px]"
onClick={() => {
void handleSavePreset();
}}
>
Save
</button>
</div>
<AdjustmentPreview
nodeId={id}
nodeWidth={width ?? 240}
currentType="color-adjust"
currentParams={localData}
/>
<div className="space-y-2 rounded-md border border-border/80 bg-background/70 p-2">
<SliderRow
label="Hue"
value={localData.hsl.hue}
min={-180}
max={180}
onChange={(value) =>
updateData((current) => ({
...current,
hsl: { ...current.hsl, hue: value },
preset: null,
}))
}
/>
<SliderRow
label="Saturation"
value={localData.hsl.saturation}
min={-100}
max={100}
onChange={(value) =>
updateData((current) => ({
...current,
hsl: { ...current.hsl, saturation: value },
preset: null,
}))
}
/>
<SliderRow
label="Luminance"
value={localData.hsl.luminance}
min={-100}
max={100}
onChange={(value) =>
updateData((current) => ({
...current,
hsl: { ...current.hsl, luminance: value },
preset: null,
}))
}
/>
<SliderRow
label="Temperature"
value={localData.temperature}
min={-100}
max={100}
onChange={(value) =>
updateData((current) => ({ ...current, temperature: value, preset: null }))
}
/>
<SliderRow
label="Tint"
value={localData.tint}
min={-100}
max={100}
onChange={(value) =>
updateData((current) => ({ ...current, tint: value, preset: null }))
}
/>
<SliderRow
label="Vibrance"
value={localData.vibrance}
min={-100}
max={100}
onChange={(value) =>
updateData((current) => ({ ...current, vibrance: value, preset: null }))
}
/>
</div>
</div>
<Handle
type="source"
position={Position.Right}
className="!h-3 !w-3 !border-2 !border-background !bg-cyan-500"
/>
</BaseNodeWrapper>
);
}

View File

@@ -0,0 +1,232 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
import { useMutation } from "convex/react";
import { TrendingUp } from "lucide-react";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useAuthQuery } from "@/hooks/use-auth-query";
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
import { useCanvasSync } from "@/components/canvas/canvas-sync-context";
import { SliderRow } from "@/components/canvas/nodes/adjustment-controls";
import BaseNodeWrapper from "@/components/canvas/nodes/base-node-wrapper";
import AdjustmentPreview from "@/components/canvas/nodes/adjustment-preview";
import {
cloneAdjustmentData,
DEFAULT_CURVES_DATA,
normalizeCurvesData,
type CurvesData,
} from "@/lib/image-pipeline/adjustment-types";
import { CURVE_PRESETS } from "@/lib/image-pipeline/presets";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "@/lib/toast";
type CurvesNodeData = CurvesData & {
_status?: string;
_statusMessage?: string;
};
export type CurvesNodeType = Node<CurvesNodeData, "curves">;
type PresetDoc = {
_id: Id<"adjustmentPresets">;
name: string;
params: unknown;
};
export default function CurvesNode({ id, data, selected, width }: NodeProps<CurvesNodeType>) {
const { queueNodeDataUpdate } = useCanvasSync();
const savePreset = useMutation(api.presets.save);
const userPresets = (useAuthQuery(api.presets.list, { nodeType: "curves" }) ?? []) as PresetDoc[];
const [localData, setLocalData] = useState<CurvesData>(() =>
normalizeCurvesData({ ...cloneAdjustmentData(DEFAULT_CURVES_DATA), ...data }),
);
const [presetSelection, setPresetSelection] = useState("custom");
const localDataRef = useRef(localData);
useEffect(() => {
localDataRef.current = localData;
}, [localData]);
useEffect(() => {
const timer = window.setTimeout(() => {
setLocalData(
normalizeCurvesData({ ...cloneAdjustmentData(DEFAULT_CURVES_DATA), ...data }),
);
}, 0);
return () => {
window.clearTimeout(timer);
};
}, [data]);
const queueSave = useDebouncedCallback(() => {
void queueNodeDataUpdate({
nodeId: id as Id<"nodes">,
data: localDataRef.current,
});
}, 16);
const updateData = (updater: (draft: CurvesData) => CurvesData) => {
setPresetSelection("custom");
setLocalData((current) => {
const next = updater(current);
localDataRef.current = next;
queueSave();
return next;
});
};
const builtinOptions = useMemo(() => Object.entries(CURVE_PRESETS), []);
const applyPresetValue = (value: string) => {
if (value === "custom") {
setPresetSelection("custom");
return;
}
if (value.startsWith("builtin:")) {
const key = value.replace("builtin:", "");
const preset = CURVE_PRESETS[key];
if (!preset) return;
setPresetSelection(value);
setLocalData(cloneAdjustmentData(preset));
localDataRef.current = cloneAdjustmentData(preset);
queueSave();
return;
}
if (value.startsWith("user:")) {
const presetId = value.replace("user:", "") as Id<"adjustmentPresets">;
const preset = userPresets.find((entry) => entry._id === presetId);
if (!preset) return;
const next = normalizeCurvesData(preset.params);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
}
};
const handleSavePreset = async () => {
const name = window.prompt("Preset-Name");
if (!name) return;
await savePreset({
name,
nodeType: "curves",
params: localData,
});
toast.success("Preset gespeichert");
};
return (
<BaseNodeWrapper
nodeType="curves"
selected={selected}
status={data._status}
statusMessage={data._statusMessage}
className="min-w-[240px] border-emerald-500/30"
>
<Handle
type="target"
position={Position.Left}
className="!h-3 !w-3 !border-2 !border-background !bg-emerald-500"
/>
<div className="space-y-3 p-3">
<div className="flex items-center gap-1.5 text-xs font-medium text-emerald-700 dark:text-emerald-400">
<TrendingUp className="h-3.5 w-3.5" />
Kurven
</div>
<div className="flex items-center gap-2">
<Select value={presetSelection} onValueChange={applyPresetValue}>
<SelectTrigger className="nodrag h-8 text-xs" size="sm">
<SelectValue placeholder="Preset" />
</SelectTrigger>
<SelectContent className="nodrag">
<SelectItem value="custom">Custom</SelectItem>
{builtinOptions.map(([name]) => (
<SelectItem key={name} value={`builtin:${name}`}>
Built-in: {name}
</SelectItem>
))}
{userPresets.map((preset) => (
<SelectItem key={preset._id} value={`user:${preset._id}`}>
User: {preset.name}
</SelectItem>
))}
</SelectContent>
</Select>
<button
type="button"
className="nodrag rounded-md border px-2 py-1 text-[11px]"
onClick={() => {
void handleSavePreset();
}}
>
Save
</button>
</div>
<AdjustmentPreview
nodeId={id}
nodeWidth={width ?? 240}
currentType="curves"
currentParams={localData}
/>
<div className="space-y-2 rounded-md border border-border/80 bg-background/70 p-2">
<SliderRow
label="Black Point"
value={localData.levels.blackPoint}
min={0}
max={255}
onChange={(value) =>
updateData((current) => ({
...current,
levels: { ...current.levels, blackPoint: value },
preset: null,
}))
}
/>
<SliderRow
label="White Point"
value={localData.levels.whitePoint}
min={0}
max={255}
onChange={(value) =>
updateData((current) => ({
...current,
levels: { ...current.levels, whitePoint: value },
preset: null,
}))
}
/>
<SliderRow
label="Gamma"
value={localData.levels.gamma}
min={0.1}
max={3}
step={0.01}
onChange={(value) =>
updateData((current) => ({
...current,
levels: { ...current.levels, gamma: value },
preset: null,
}))
}
/>
</div>
</div>
<Handle
type="source"
position={Position.Right}
className="!h-3 !w-3 !border-2 !border-background !bg-emerald-500"
/>
</BaseNodeWrapper>
);
}

View File

@@ -0,0 +1,198 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
import { useMutation } from "convex/react";
import { Focus } from "lucide-react";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useAuthQuery } from "@/hooks/use-auth-query";
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
import { useCanvasSync } from "@/components/canvas/canvas-sync-context";
import { SliderRow } from "@/components/canvas/nodes/adjustment-controls";
import BaseNodeWrapper from "@/components/canvas/nodes/base-node-wrapper";
import AdjustmentPreview from "@/components/canvas/nodes/adjustment-preview";
import {
cloneAdjustmentData,
DEFAULT_DETAIL_ADJUST_DATA,
normalizeDetailAdjustData,
type DetailAdjustData,
} from "@/lib/image-pipeline/adjustment-types";
import { DETAIL_PRESETS } from "@/lib/image-pipeline/presets";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "@/lib/toast";
type DetailAdjustNodeData = DetailAdjustData & {
_status?: string;
_statusMessage?: string;
};
export type DetailAdjustNodeType = Node<DetailAdjustNodeData, "detail-adjust">;
type PresetDoc = {
_id: Id<"adjustmentPresets">;
name: string;
params: unknown;
};
export default function DetailAdjustNode({ id, data, selected, width }: NodeProps<DetailAdjustNodeType>) {
const { queueNodeDataUpdate } = useCanvasSync();
const savePreset = useMutation(api.presets.save);
const userPresets = (useAuthQuery(api.presets.list, { nodeType: "detail-adjust" }) ?? []) as PresetDoc[];
const [localData, setLocalData] = useState<DetailAdjustData>(() =>
normalizeDetailAdjustData({ ...cloneAdjustmentData(DEFAULT_DETAIL_ADJUST_DATA), ...data }),
);
const [presetSelection, setPresetSelection] = useState("custom");
const localDataRef = useRef(localData);
useEffect(() => {
localDataRef.current = localData;
}, [localData]);
useEffect(() => {
const timer = window.setTimeout(() => {
setLocalData(
normalizeDetailAdjustData({ ...cloneAdjustmentData(DEFAULT_DETAIL_ADJUST_DATA), ...data }),
);
}, 0);
return () => {
window.clearTimeout(timer);
};
}, [data]);
const queueSave = useDebouncedCallback(() => {
void queueNodeDataUpdate({
nodeId: id as Id<"nodes">,
data: localDataRef.current,
});
}, 16);
const updateData = (updater: (draft: DetailAdjustData) => DetailAdjustData) => {
setPresetSelection("custom");
setLocalData((current) => {
const next = updater(current);
localDataRef.current = next;
queueSave();
return next;
});
};
const builtinOptions = useMemo(() => Object.entries(DETAIL_PRESETS), []);
const applyPresetValue = (value: string) => {
if (value === "custom") {
setPresetSelection("custom");
return;
}
if (value.startsWith("builtin:")) {
const key = value.replace("builtin:", "");
const preset = DETAIL_PRESETS[key];
if (!preset) return;
const next = cloneAdjustmentData(preset);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
return;
}
if (value.startsWith("user:")) {
const presetId = value.replace("user:", "") as Id<"adjustmentPresets">;
const preset = userPresets.find((entry) => entry._id === presetId);
if (!preset) return;
const next = normalizeDetailAdjustData(preset.params);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
}
};
const handleSavePreset = async () => {
const name = window.prompt("Preset-Name");
if (!name) return;
await savePreset({
name,
nodeType: "detail-adjust",
params: localData,
});
toast.success("Preset gespeichert");
};
return (
<BaseNodeWrapper
nodeType="detail-adjust"
selected={selected}
status={data._status}
statusMessage={data._statusMessage}
className="min-w-[240px] border-indigo-500/30"
>
<Handle
type="target"
position={Position.Left}
className="!h-3 !w-3 !border-2 !border-background !bg-indigo-500"
/>
<div className="space-y-3 p-3">
<div className="flex items-center gap-1.5 text-xs font-medium text-indigo-700 dark:text-indigo-300">
<Focus className="h-3.5 w-3.5" />
Detail
</div>
<div className="flex items-center gap-2">
<Select value={presetSelection} onValueChange={applyPresetValue}>
<SelectTrigger className="nodrag h-8 text-xs" size="sm">
<SelectValue placeholder="Preset" />
</SelectTrigger>
<SelectContent className="nodrag">
<SelectItem value="custom">Custom</SelectItem>
{builtinOptions.map(([name]) => (
<SelectItem key={name} value={`builtin:${name}`}>
Built-in: {name}
</SelectItem>
))}
{userPresets.map((preset) => (
<SelectItem key={preset._id} value={`user:${preset._id}`}>
User: {preset.name}
</SelectItem>
))}
</SelectContent>
</Select>
<button
type="button"
className="nodrag rounded-md border px-2 py-1 text-[11px]"
onClick={() => {
void handleSavePreset();
}}
>
Save
</button>
</div>
<AdjustmentPreview
nodeId={id}
nodeWidth={width ?? 240}
currentType="detail-adjust"
currentParams={localData}
/>
<div className="space-y-2 rounded-md border border-border/80 bg-background/70 p-2">
<SliderRow label="Sharpen" value={localData.sharpen.amount} min={0} max={500} onChange={(value) => updateData((current) => ({ ...current, sharpen: { ...current.sharpen, amount: value }, preset: null }))} />
<SliderRow label="Radius" value={localData.sharpen.radius} min={0.5} max={5} step={0.01} onChange={(value) => updateData((current) => ({ ...current, sharpen: { ...current.sharpen, radius: value }, preset: null }))} />
<SliderRow label="Threshold" value={localData.sharpen.threshold} min={0} max={255} onChange={(value) => updateData((current) => ({ ...current, sharpen: { ...current.sharpen, threshold: value }, preset: null }))} />
<SliderRow label="Clarity" value={localData.clarity} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, clarity: value, preset: null }))} />
<SliderRow label="Denoise Luma" value={localData.denoise.luminance} min={0} max={100} onChange={(value) => updateData((current) => ({ ...current, denoise: { ...current.denoise, luminance: value }, preset: null }))} />
<SliderRow label="Denoise Color" value={localData.denoise.color} min={0} max={100} onChange={(value) => updateData((current) => ({ ...current, denoise: { ...current.denoise, color: value }, preset: null }))} />
<SliderRow label="Grain" value={localData.grain.amount} min={0} max={100} onChange={(value) => updateData((current) => ({ ...current, grain: { ...current.grain, amount: value }, preset: null }))} />
</div>
</div>
<Handle
type="source"
position={Position.Right}
className="!h-3 !w-3 !border-2 !border-background !bg-indigo-500"
/>
</BaseNodeWrapper>
);
}

View File

@@ -0,0 +1,199 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
import { useMutation } from "convex/react";
import { Sun } from "lucide-react";
import { api } from "@/convex/_generated/api";
import type { Id } from "@/convex/_generated/dataModel";
import { useAuthQuery } from "@/hooks/use-auth-query";
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
import { useCanvasSync } from "@/components/canvas/canvas-sync-context";
import { SliderRow } from "@/components/canvas/nodes/adjustment-controls";
import BaseNodeWrapper from "@/components/canvas/nodes/base-node-wrapper";
import AdjustmentPreview from "@/components/canvas/nodes/adjustment-preview";
import {
cloneAdjustmentData,
DEFAULT_LIGHT_ADJUST_DATA,
normalizeLightAdjustData,
type LightAdjustData,
} from "@/lib/image-pipeline/adjustment-types";
import { LIGHT_PRESETS } from "@/lib/image-pipeline/presets";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "@/lib/toast";
type LightAdjustNodeData = LightAdjustData & {
_status?: string;
_statusMessage?: string;
};
export type LightAdjustNodeType = Node<LightAdjustNodeData, "light-adjust">;
type PresetDoc = {
_id: Id<"adjustmentPresets">;
name: string;
params: unknown;
};
export default function LightAdjustNode({ id, data, selected, width }: NodeProps<LightAdjustNodeType>) {
const { queueNodeDataUpdate } = useCanvasSync();
const savePreset = useMutation(api.presets.save);
const userPresets = (useAuthQuery(api.presets.list, { nodeType: "light-adjust" }) ?? []) as PresetDoc[];
const [localData, setLocalData] = useState<LightAdjustData>(() =>
normalizeLightAdjustData({ ...cloneAdjustmentData(DEFAULT_LIGHT_ADJUST_DATA), ...data }),
);
const [presetSelection, setPresetSelection] = useState("custom");
const localDataRef = useRef(localData);
useEffect(() => {
localDataRef.current = localData;
}, [localData]);
useEffect(() => {
const timer = window.setTimeout(() => {
setLocalData(
normalizeLightAdjustData({ ...cloneAdjustmentData(DEFAULT_LIGHT_ADJUST_DATA), ...data }),
);
}, 0);
return () => {
window.clearTimeout(timer);
};
}, [data]);
const queueSave = useDebouncedCallback(() => {
void queueNodeDataUpdate({
nodeId: id as Id<"nodes">,
data: localDataRef.current,
});
}, 16);
const updateData = (updater: (draft: LightAdjustData) => LightAdjustData) => {
setPresetSelection("custom");
setLocalData((current) => {
const next = updater(current);
localDataRef.current = next;
queueSave();
return next;
});
};
const builtinOptions = useMemo(() => Object.entries(LIGHT_PRESETS), []);
const applyPresetValue = (value: string) => {
if (value === "custom") {
setPresetSelection("custom");
return;
}
if (value.startsWith("builtin:")) {
const key = value.replace("builtin:", "");
const preset = LIGHT_PRESETS[key];
if (!preset) return;
const next = cloneAdjustmentData(preset);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
return;
}
if (value.startsWith("user:")) {
const presetId = value.replace("user:", "") as Id<"adjustmentPresets">;
const preset = userPresets.find((entry) => entry._id === presetId);
if (!preset) return;
const next = normalizeLightAdjustData(preset.params);
setPresetSelection(value);
setLocalData(next);
localDataRef.current = next;
queueSave();
}
};
const handleSavePreset = async () => {
const name = window.prompt("Preset-Name");
if (!name) return;
await savePreset({
name,
nodeType: "light-adjust",
params: localData,
});
toast.success("Preset gespeichert");
};
return (
<BaseNodeWrapper
nodeType="light-adjust"
selected={selected}
status={data._status}
statusMessage={data._statusMessage}
className="min-w-[240px] border-amber-500/30"
>
<Handle
type="target"
position={Position.Left}
className="!h-3 !w-3 !border-2 !border-background !bg-amber-500"
/>
<div className="space-y-3 p-3">
<div className="flex items-center gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300">
<Sun className="h-3.5 w-3.5" />
Licht
</div>
<div className="flex items-center gap-2">
<Select value={presetSelection} onValueChange={applyPresetValue}>
<SelectTrigger className="nodrag h-8 text-xs" size="sm">
<SelectValue placeholder="Preset" />
</SelectTrigger>
<SelectContent className="nodrag">
<SelectItem value="custom">Custom</SelectItem>
{builtinOptions.map(([name]) => (
<SelectItem key={name} value={`builtin:${name}`}>
Built-in: {name}
</SelectItem>
))}
{userPresets.map((preset) => (
<SelectItem key={preset._id} value={`user:${preset._id}`}>
User: {preset.name}
</SelectItem>
))}
</SelectContent>
</Select>
<button
type="button"
className="nodrag rounded-md border px-2 py-1 text-[11px]"
onClick={() => {
void handleSavePreset();
}}
>
Save
</button>
</div>
<AdjustmentPreview
nodeId={id}
nodeWidth={width ?? 240}
currentType="light-adjust"
currentParams={localData}
/>
<div className="space-y-2 rounded-md border border-border/80 bg-background/70 p-2">
<SliderRow label="Brightness" value={localData.brightness} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, brightness: value, preset: null }))} />
<SliderRow label="Contrast" value={localData.contrast} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, contrast: value, preset: null }))} />
<SliderRow label="Exposure" value={localData.exposure} min={-5} max={5} step={0.01} onChange={(value) => updateData((current) => ({ ...current, exposure: value, preset: null }))} />
<SliderRow label="Highlights" value={localData.highlights} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, highlights: value, preset: null }))} />
<SliderRow label="Shadows" value={localData.shadows} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, shadows: value, preset: null }))} />
<SliderRow label="Whites" value={localData.whites} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, whites: value, preset: null }))} />
<SliderRow label="Blacks" value={localData.blacks} min={-100} max={100} onChange={(value) => updateData((current) => ({ ...current, blacks: value, preset: null }))} />
<SliderRow label="Vignette" value={localData.vignette.amount} min={0} max={1} step={0.01} onChange={(value) => updateData((current) => ({ ...current, vignette: { ...current.vignette, amount: value }, preset: null }))} />
</div>
</div>
<Handle
type="source"
position={Position.Right}
className="!h-3 !w-3 !border-2 !border-background !bg-amber-500"
/>
</BaseNodeWrapper>
);
}

File diff suppressed because it is too large Load Diff