mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
fix: resolve 41 bugs and wire 21 unimplemented features in image editor
Canvas rendering: - Fix Konva filter application order (filters before cache) - Implement 6 missing filters (motionBlur, radialBlur, surfaceBlur, vignette, grain, sharpen) - Implement exposure, vibrance, warmth adjustments as custom Konva filters - Apply layer blend modes via globalCompositeOperation - Apply object effects (drop shadow, outer glow, stroke) to all shapes - Mount SmartGuidesOverlay during move tool drag - Clip pixel grid to visible viewport (200-line cap for performance) Store logic: - resizeImage now scales all objects proportionally (points, radii, fontSize) - rotate/flip/trim handle line/arrow points arrays and center-based objects - applyCrop creates cropped source image via offscreen canvas - invertSelection creates mask from bounds when no mask exists - cutObjects uses single atomic set() to prevent race conditions - sendToBack respects layer ordering in multi-layer documents - Add batchNudge() and commitHistory() for undoable nudge operations - Add updateLayerThumbnail() method Tool hooks: - Fix clone stamp/dodge/burn perf (toDataURL only on mouseUp, not every move) - Fix magic wand zoom/pixelRatio with explicit stage.toCanvas() viewport - Fix eyedropper sampling with unzoomed canvas export - Fix selection tool stale closure via isDrawingRef - Implement polygonal lasso (click-to-place vertices, double-click to close) - Implement selection subtract mode (geometric and mask-based) - Implement gradient live preview during drag - Fix transform/move tool to persist changes and handle ellipse/polygon/star UI wiring: - Mount rulers and guidelines in editor page - Wire histogram with live canvas imageData - Wire autosave recovery with blob-to-dataURL conversion - Wire fill dialog to Shift+Backspace shortcut - Wire eyedropper and transform options to options bar - Fix history panel undo/redo button reactive state via useSyncExternalStore - Fix layer row name click to select layer (timer-based click/dblclick) - Fix zoom animation coordinate drift with progressive store sync - Fix copy merged to use Konva stage composite export Tests: - 49 new unit tests (store fixes + konva filters) - 8 new E2E test files with 39 test cases
This commit is contained in:
@@ -542,9 +542,33 @@ interface AutosaveData {
|
||||
state: AutosaveState;
|
||||
}
|
||||
|
||||
export function saveEditorState(): void {
|
||||
/**
|
||||
* Convert a blob: URL to a data: URL. Returns the original string
|
||||
* if it is not a blob URL or if the fetch fails.
|
||||
*/
|
||||
async function blobUrlToDataUrl(url: string): Promise<string> {
|
||||
if (!url.startsWith("blob:")) return url;
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
const blob = await res.blob();
|
||||
return await new Promise<string>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => resolve(reader.result as string);
|
||||
reader.onerror = () => resolve(url);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveEditorState(): Promise<void> {
|
||||
try {
|
||||
const s = useEditorStore.getState();
|
||||
|
||||
// Convert blob URLs to data URLs so they survive localStorage round-trip
|
||||
const sourceImageUrl = s.sourceImageUrl ? await blobUrlToDataUrl(s.sourceImageUrl) : null;
|
||||
|
||||
const data: AutosaveData = {
|
||||
version: 1,
|
||||
timestamp: Date.now(),
|
||||
@@ -555,16 +579,21 @@ export function saveEditorState(): void {
|
||||
adjustments: s.adjustments,
|
||||
filters: s.filters,
|
||||
guides: s.guides,
|
||||
sourceImageUrl: s.sourceImageUrl,
|
||||
sourceImageUrl,
|
||||
sourceImageSize: s.sourceImageSize,
|
||||
foregroundColor: s.foregroundColor,
|
||||
backgroundColor: s.backgroundColor,
|
||||
},
|
||||
};
|
||||
localStorage.setItem(AUTOSAVE_KEY, JSON.stringify(data));
|
||||
useEditorStore.setState({ lastAutoSave: Date.now() });
|
||||
|
||||
try {
|
||||
localStorage.setItem(AUTOSAVE_KEY, JSON.stringify(data));
|
||||
useEditorStore.setState({ lastAutoSave: Date.now() });
|
||||
} catch (storageErr) {
|
||||
console.warn("[SnapOtter] Autosave failed (localStorage quota may be exceeded):", storageErr);
|
||||
}
|
||||
} catch {
|
||||
// localStorage might be full or unavailable
|
||||
// Serialization or fetch error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,10 +21,28 @@ import {
|
||||
import useImage from "use-image";
|
||||
import { useCanvasZoom } from "@/hooks/use-canvas-zoom";
|
||||
import { useEditorStore } from "@/stores/editor-store";
|
||||
import type { AdjustmentValues, CanvasObject, FilterConfig, ImageAttrs } from "@/types/editor";
|
||||
import type {
|
||||
AdjustmentValues,
|
||||
CanvasObject,
|
||||
FilterConfig,
|
||||
ImageAttrs,
|
||||
ObjectEffects,
|
||||
} from "@/types/editor";
|
||||
import { ContextMenu, useContextMenu } from "./common/context-menu";
|
||||
import { BrushCursorOverlay, useEditorCursor } from "./common/custom-cursor";
|
||||
import { LoadingOverlay } from "./common/loading-overlay";
|
||||
import { SmartGuidesOverlay } from "./common/smart-guides";
|
||||
import {
|
||||
createExposureFilter,
|
||||
createGrainFilter,
|
||||
createMotionBlurFilter,
|
||||
createRadialBlurFilter,
|
||||
createSharpenFilter,
|
||||
createSurfaceBlurFilter,
|
||||
createVibranceFilter,
|
||||
createVignetteFilter,
|
||||
createWarmthFilter,
|
||||
} from "./konva-filters";
|
||||
import { useBrushTool } from "./tools/brush-tool";
|
||||
import { useCloneStampTool } from "./tools/clone-stamp-tool";
|
||||
import { CropOverlay } from "./tools/crop-tool";
|
||||
@@ -40,6 +58,36 @@ import { useShapeTool } from "./tools/shape-tool";
|
||||
import { useTextTool } from "./tools/text-tool";
|
||||
import { TransformToolTransformer, useTransformTool } from "./tools/transform-tool";
|
||||
|
||||
// Konva's globalCompositeOperationType is not exported, so we define a compatible alias
|
||||
type GlobalCompositeOperation =
|
||||
| ""
|
||||
| "source-over"
|
||||
| "source-in"
|
||||
| "source-out"
|
||||
| "source-atop"
|
||||
| "destination-over"
|
||||
| "destination-in"
|
||||
| "destination-out"
|
||||
| "destination-atop"
|
||||
| "lighter"
|
||||
| "copy"
|
||||
| "xor"
|
||||
| "multiply"
|
||||
| "screen"
|
||||
| "overlay"
|
||||
| "darken"
|
||||
| "lighten"
|
||||
| "color-dodge"
|
||||
| "color-burn"
|
||||
| "hard-light"
|
||||
| "soft-light"
|
||||
| "difference"
|
||||
| "exclusion"
|
||||
| "hue"
|
||||
| "saturation"
|
||||
| "color"
|
||||
| "luminosity";
|
||||
|
||||
// Module-level stage ref for export dialog access (Issue #6)
|
||||
export const editorStageRefHolder: { current: Konva.Stage | null } = {
|
||||
current: null,
|
||||
@@ -80,6 +128,7 @@ function SourceImage({
|
||||
if (hasActiveAdjustments || hasActiveFilters) {
|
||||
const konvaFilters: Array<((this: Konva.Node, imageData: ImageData) => void) | string> = [];
|
||||
|
||||
// Built-in Konva adjustment filters
|
||||
if (adjustments.brightness !== 0) {
|
||||
konvaFilters.push(KonvaFilters.Filters.Brighten);
|
||||
node.brightness(adjustments.brightness / 100);
|
||||
@@ -95,6 +144,17 @@ function SourceImage({
|
||||
node.luminance(adjustments.luminance / 100);
|
||||
}
|
||||
|
||||
// FIX 3: Custom adjustment filters for exposure, vibrance, warmth
|
||||
if (adjustments.exposure !== 0) {
|
||||
konvaFilters.push(createExposureFilter(adjustments.exposure / 100));
|
||||
}
|
||||
if (adjustments.vibrance !== 0) {
|
||||
konvaFilters.push(createVibranceFilter(adjustments.vibrance));
|
||||
}
|
||||
if (adjustments.warmth !== 0) {
|
||||
konvaFilters.push(createWarmthFilter(adjustments.warmth));
|
||||
}
|
||||
|
||||
// Apply enabled filters
|
||||
for (const f of filters) {
|
||||
if (!f.enabled) continue;
|
||||
@@ -142,12 +202,63 @@ function SourceImage({
|
||||
node.kaleidoscopePower(f.params.power ?? 2);
|
||||
node.kaleidoscopeAngle(f.params.angle ?? 0);
|
||||
break;
|
||||
// FIX 2: Custom filter types
|
||||
case "motionBlur":
|
||||
konvaFilters.push(
|
||||
createMotionBlurFilter({
|
||||
angle: f.params.angle ?? 0,
|
||||
distance: f.params.distance ?? 10,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "radialBlur":
|
||||
konvaFilters.push(
|
||||
createRadialBlurFilter({
|
||||
amount: f.params.amount ?? 10,
|
||||
centerX: f.params.centerX ?? 0.5,
|
||||
centerY: f.params.centerY ?? 0.5,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "surfaceBlur":
|
||||
konvaFilters.push(
|
||||
createSurfaceBlurFilter({
|
||||
radius: f.params.radius ?? 5,
|
||||
threshold: f.params.threshold ?? 25,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "vignette":
|
||||
konvaFilters.push(
|
||||
createVignetteFilter({
|
||||
amount: f.params.amount ?? 50,
|
||||
midpoint: f.params.midpoint ?? 50,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "grain":
|
||||
konvaFilters.push(
|
||||
createGrainFilter({
|
||||
amount: f.params.amount ?? 25,
|
||||
size: f.params.size ?? 25,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "sharpen":
|
||||
konvaFilters.push(
|
||||
createSharpenFilter({
|
||||
amount: f.params.amount ?? 0,
|
||||
radius: f.params.radius ?? 1,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// FIX 1: Filters must be set BEFORE caching in Konva
|
||||
node.clearCache();
|
||||
node.cache();
|
||||
node.filters(konvaFilters);
|
||||
node.cache();
|
||||
node.getLayer()?.batchDraw();
|
||||
} else {
|
||||
node.clearCache();
|
||||
@@ -206,6 +317,58 @@ function ImageObject({
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Object Effects helpers (FIX 5)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute Konva-compatible props from an object's effects configuration.
|
||||
* Returns props for drop shadow, outer glow, and stroke that can be spread
|
||||
* onto any Konva shape node.
|
||||
*/
|
||||
function computeEffectProps(effects?: ObjectEffects): Record<string, unknown> {
|
||||
if (!effects) return {};
|
||||
const props: Record<string, unknown> = {};
|
||||
|
||||
// Drop shadow: uses Konva's built-in shadow support
|
||||
if (effects.dropShadow?.enabled) {
|
||||
const ds = effects.dropShadow;
|
||||
const rad = (ds.angle * Math.PI) / 180;
|
||||
props.shadowColor = ds.color;
|
||||
props.shadowBlur = ds.blur;
|
||||
props.shadowOffsetX = Math.cos(rad) * ds.distance;
|
||||
props.shadowOffsetY = Math.sin(rad) * ds.distance;
|
||||
props.shadowOpacity = ds.opacity;
|
||||
props.shadowEnabled = true;
|
||||
}
|
||||
|
||||
// Outer glow: like drop shadow but with zero offset
|
||||
// Only apply if drop shadow is not already active (Konva has one shadow per node)
|
||||
if (effects.outerGlow?.enabled && !effects.dropShadow?.enabled) {
|
||||
const og = effects.outerGlow;
|
||||
props.shadowColor = og.color;
|
||||
props.shadowBlur = og.blur + og.spread;
|
||||
props.shadowOffsetX = 0;
|
||||
props.shadowOffsetY = 0;
|
||||
props.shadowOpacity = og.opacity;
|
||||
props.shadowEnabled = true;
|
||||
}
|
||||
|
||||
// Stroke effect (outer or center position -- Konva draws strokes centered by default)
|
||||
if (effects.stroke?.enabled) {
|
||||
const s = effects.stroke;
|
||||
props.stroke = s.color;
|
||||
props.strokeWidth = s.position === "inside" ? s.width * 2 : s.width;
|
||||
props.strokeEnabled = true;
|
||||
// For "inside" strokes, we double the width and clip via strokeScaleEnabled
|
||||
if (s.position === "inside") {
|
||||
props.strokeScaleEnabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
return props;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canvas Object Renderer (Issue #3: wire move tool handlers)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -228,6 +391,8 @@ function CanvasObjectRenderer({
|
||||
onTransformEnd?: (e: Konva.KonvaEventObject<Event>) => void;
|
||||
}) {
|
||||
const draggable = isMoveTool;
|
||||
// FIX 5: Compute effect props (drop shadow, outer glow, stroke) for all shapes
|
||||
const fx = computeEffectProps(obj.effects);
|
||||
|
||||
switch (obj.type) {
|
||||
case "line": {
|
||||
@@ -249,6 +414,7 @@ function CanvasObjectRenderer({
|
||||
shadowColor={a.shadowColor}
|
||||
shadowOffsetX={a.shadowOffsetX}
|
||||
shadowOffsetY={a.shadowOffsetY}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -273,6 +439,7 @@ function CanvasObjectRenderer({
|
||||
onDragMove={onDragMove}
|
||||
onDragEnd={onDragEnd}
|
||||
onTransformEnd={onTransformEnd}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -296,6 +463,7 @@ function CanvasObjectRenderer({
|
||||
onDragMove={onDragMove}
|
||||
onDragEnd={onDragEnd}
|
||||
onTransformEnd={onTransformEnd}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -325,6 +493,7 @@ function CanvasObjectRenderer({
|
||||
onDragMove={onDragMove}
|
||||
onDragEnd={onDragEnd}
|
||||
onTransformEnd={onTransformEnd}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -347,6 +516,7 @@ function CanvasObjectRenderer({
|
||||
onDragMove={onDragMove}
|
||||
onDragEnd={onDragEnd}
|
||||
onTransformEnd={onTransformEnd}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -370,6 +540,7 @@ function CanvasObjectRenderer({
|
||||
onDragMove={onDragMove}
|
||||
onDragEnd={onDragEnd}
|
||||
onTransformEnd={onTransformEnd}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -394,6 +565,7 @@ function CanvasObjectRenderer({
|
||||
onDragMove={onDragMove}
|
||||
onDragEnd={onDragEnd}
|
||||
onTransformEnd={onTransformEnd}
|
||||
{...fx}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -761,7 +933,16 @@ export function EditorCanvas({
|
||||
const layerObjects = objectsByLayer.get(layer.id) ?? [];
|
||||
if (!layer.visible) return null;
|
||||
return (
|
||||
<Group key={layer.id} opacity={layer.opacity} listening={layer.id === activeLayerId}>
|
||||
<Group
|
||||
key={layer.id}
|
||||
opacity={layer.opacity}
|
||||
globalCompositeOperation={
|
||||
layer.blendMode !== "normal"
|
||||
? (layer.blendMode as GlobalCompositeOperation)
|
||||
: undefined
|
||||
}
|
||||
listening={layer.id === activeLayerId}
|
||||
>
|
||||
{layerObjects.map((obj) => (
|
||||
<CanvasObjectRenderer
|
||||
key={obj.id}
|
||||
@@ -783,6 +964,9 @@ export function EditorCanvas({
|
||||
<MoveToolTransformer transformerRef={moveTool.transformerRef} />
|
||||
)}
|
||||
|
||||
{/* FIX 6: Smart guides overlay (shown during drag with move tool) */}
|
||||
{activeTool === "move" && <SmartGuidesOverlay guides={moveTool.smartGuides} />}
|
||||
|
||||
{/* Transform tool transformer */}
|
||||
{activeTool === "transform" && (
|
||||
<TransformToolTransformer transformerRef={transformTool.transformerRef} />
|
||||
@@ -814,6 +998,9 @@ export function EditorCanvas({
|
||||
canvasWidth={canvasSize.width}
|
||||
canvasHeight={canvasSize.height}
|
||||
zoom={zoom}
|
||||
panOffset={panOffset}
|
||||
stageWidth={stageWidth}
|
||||
stageHeight={stageHeight}
|
||||
showGrid={gridVisible}
|
||||
showPixelGrid={zoom >= 8}
|
||||
/>
|
||||
@@ -839,12 +1026,18 @@ function GridOverlay({
|
||||
canvasWidth,
|
||||
canvasHeight,
|
||||
zoom,
|
||||
panOffset,
|
||||
stageWidth,
|
||||
stageHeight,
|
||||
showGrid,
|
||||
showPixelGrid,
|
||||
}: {
|
||||
canvasWidth: number;
|
||||
canvasHeight: number;
|
||||
zoom: number;
|
||||
panOffset: { x: number; y: number };
|
||||
stageWidth: number;
|
||||
stageHeight: number;
|
||||
showGrid: boolean;
|
||||
showPixelGrid: boolean;
|
||||
}) {
|
||||
@@ -868,17 +1061,38 @@ function GridOverlay({
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// FIX 7: Clip pixel grid to the visible viewport to avoid drawing
|
||||
// thousands of lines for large images. Cap at 200 lines per axis.
|
||||
if (showPixelGrid) {
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = "rgba(128, 128, 128, 0.1)";
|
||||
ctx.lineWidth = 1 / zoom;
|
||||
for (let x = 1; x < canvasWidth; x++) {
|
||||
ctx.moveTo(x, 0);
|
||||
ctx.lineTo(x, canvasHeight);
|
||||
|
||||
// Calculate visible region in canvas coordinates from pan/zoom
|
||||
const visMinX = Math.max(0, Math.floor(-panOffset.x / zoom));
|
||||
const visMinY = Math.max(0, Math.floor(-panOffset.y / zoom));
|
||||
const visMaxX = Math.min(canvasWidth, Math.ceil((stageWidth - panOffset.x) / zoom));
|
||||
const visMaxY = Math.min(canvasHeight, Math.ceil((stageHeight - panOffset.y) / zoom));
|
||||
|
||||
const MAX_LINES = 200;
|
||||
|
||||
// Determine step: if visible range exceeds max lines, skip pixels
|
||||
const xRange = visMaxX - visMinX;
|
||||
const yRange = visMaxY - visMinY;
|
||||
const xStep = xRange > MAX_LINES ? Math.ceil(xRange / MAX_LINES) : 1;
|
||||
const yStep = yRange > MAX_LINES ? Math.ceil(yRange / MAX_LINES) : 1;
|
||||
|
||||
// Align start to step boundary
|
||||
const startX = Math.max(1, visMinX - (visMinX % xStep) + xStep);
|
||||
const startY = Math.max(1, visMinY - (visMinY % yStep) + yStep);
|
||||
|
||||
for (let x = startX; x < visMaxX; x += xStep) {
|
||||
ctx.moveTo(x, visMinY);
|
||||
ctx.lineTo(x, visMaxY);
|
||||
}
|
||||
for (let y = 1; y < canvasHeight; y++) {
|
||||
ctx.moveTo(0, y);
|
||||
ctx.lineTo(canvasWidth, y);
|
||||
for (let y = startY; y < visMaxY; y += yStep) {
|
||||
ctx.moveTo(visMinX, y);
|
||||
ctx.lineTo(visMaxX, y);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
// apps/web/src/components/editor/editor-options-bar.tsx
|
||||
|
||||
import { useState } from "react";
|
||||
import { useEditorStore } from "@/stores/editor-store";
|
||||
import type { ToolType } from "@/types/editor";
|
||||
import { BrushOptions } from "./options/brush-options";
|
||||
import { CloneStampOptions } from "./options/clone-stamp-options";
|
||||
import { CropOptions } from "./options/crop-options";
|
||||
import { DodgeBurnOptions } from "./options/dodge-burn-options";
|
||||
import { EyedropperOptions, type SampleSize } from "./options/eyedropper-options";
|
||||
import { FillOptions } from "./options/fill-options";
|
||||
import { GradientOptions } from "./options/gradient-options";
|
||||
import { MoveOptions } from "./options/move-options";
|
||||
@@ -13,6 +15,8 @@ import { PixelBrushOptions } from "./options/pixel-brush-options";
|
||||
import { SelectionOptions } from "./options/selection-options";
|
||||
import { ShapeOptions } from "./options/shape-options";
|
||||
import { TextOptions } from "./options/text-options";
|
||||
import { TransformOptions } from "./options/transform-options";
|
||||
import { useTransformTool } from "./tools/transform-tool";
|
||||
|
||||
function getOptionsComponent(tool: ToolType): React.ComponentType | null {
|
||||
switch (tool) {
|
||||
@@ -53,6 +57,7 @@ function getOptionsComponent(tool: ToolType): React.ComponentType | null {
|
||||
return ShapeOptions;
|
||||
case "text":
|
||||
return TextOptions;
|
||||
// transform and eyedropper are handled separately in EditorOptionsBar
|
||||
case "transform":
|
||||
case "eyedropper":
|
||||
case "hand":
|
||||
@@ -68,6 +73,16 @@ export function EditorOptionsBar() {
|
||||
|
||||
const OptionsComponent = getOptionsComponent(activeTool);
|
||||
|
||||
// Eyedropper state (managed here since EyedropperOptions requires props)
|
||||
const [eyedropperSampleSize, setEyedropperSampleSize] = useState<SampleSize>(1);
|
||||
const [sampledColor, setSampledColor] = useState<string | null>(null);
|
||||
|
||||
// Transform tool API (managed here since TransformOptions requires props)
|
||||
const transformApi = useTransformTool();
|
||||
|
||||
// Pick sampled color from store foreground when eyedropper is active
|
||||
const foregroundColor = useEditorStore((s) => s.foregroundColor);
|
||||
|
||||
return (
|
||||
<div className="flex items-center h-10 px-3 bg-card border-b border-border gap-3">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
@@ -79,6 +94,14 @@ export function EditorOptionsBar() {
|
||||
<div className="h-4 w-px bg-border" />
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
{OptionsComponent && <OptionsComponent />}
|
||||
{activeTool === "eyedropper" && (
|
||||
<EyedropperOptions
|
||||
sampleSize={eyedropperSampleSize}
|
||||
onSampleSizeChange={setEyedropperSampleSize}
|
||||
sampledColor={sampledColor ?? foregroundColor}
|
||||
/>
|
||||
)}
|
||||
{activeTool === "transform" && <TransformOptions api={transformApi} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
// apps/web/src/components/editor/konva-filters.ts
|
||||
// Custom Konva filter factories for the image editor.
|
||||
// Each factory returns a function `(imageData: ImageData) => void` that mutates pixel data in place.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Adjustment Filters
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Exposure adjustment via gamma curve.
|
||||
* exposure > 0 brightens, exposure < 0 darkens.
|
||||
* Formula: pixel = 255 * pow(pixel/255, 1/(1 + exposure))
|
||||
*/
|
||||
export function createExposureFilter(exposure: number): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const d = imageData.data;
|
||||
const gamma = 1 / (1 + exposure);
|
||||
// Build a lookup table for performance
|
||||
const lut = new Uint8Array(256);
|
||||
for (let i = 0; i < 256; i++) {
|
||||
lut[i] = Math.min(255, Math.max(0, Math.round(255 * (i / 255) ** gamma)));
|
||||
}
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
d[i] = lut[d[i]];
|
||||
d[i + 1] = lut[d[i + 1]];
|
||||
d[i + 2] = lut[d[i + 2]];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vibrance: selective saturation boost that increases saturation more
|
||||
* for less-saturated pixels, preserving already-vivid colors.
|
||||
* amount is in [-100, 100] range.
|
||||
*/
|
||||
export function createVibranceFilter(amount: number): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const d = imageData.data;
|
||||
const amt = amount / 100;
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
const r = d[i];
|
||||
const g = d[i + 1];
|
||||
const b = d[i + 2];
|
||||
const maxC = Math.max(r, g, b);
|
||||
const minC = Math.min(r, g, b);
|
||||
// Saturation approximation (0..1)
|
||||
const sat = maxC === 0 ? 0 : (maxC - minC) / maxC;
|
||||
// Boost less-saturated pixels more
|
||||
const boost = amt * (1 - sat);
|
||||
const avg = (r + g + b) / 3;
|
||||
d[i] = Math.min(255, Math.max(0, Math.round(r + (r - avg) * boost)));
|
||||
d[i + 1] = Math.min(255, Math.max(0, Math.round(g + (g - avg) * boost)));
|
||||
d[i + 2] = Math.min(255, Math.max(0, Math.round(b + (b - avg) * boost)));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Warmth / color temperature shift.
|
||||
* Positive warmth: boost red, reduce blue (warmer).
|
||||
* Negative warmth: boost blue, reduce red (cooler).
|
||||
* amount is in [-100, 100] range.
|
||||
*/
|
||||
export function createWarmthFilter(amount: number): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const d = imageData.data;
|
||||
// Scale to a reasonable pixel shift range
|
||||
const shift = (amount / 100) * 30;
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
d[i] = Math.min(255, Math.max(0, Math.round(d[i] + shift)));
|
||||
d[i + 2] = Math.min(255, Math.max(0, Math.round(d[i + 2] - shift)));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Creative Filters
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Motion blur: directional box blur along a given angle.
|
||||
* angle in degrees, distance is the blur length in pixels.
|
||||
*/
|
||||
export function createMotionBlurFilter(params: {
|
||||
angle: number;
|
||||
distance: number;
|
||||
}): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const { angle, distance } = params;
|
||||
if (distance <= 0) return;
|
||||
|
||||
const w = imageData.width;
|
||||
const h = imageData.height;
|
||||
const d = imageData.data;
|
||||
const copy = new Uint8ClampedArray(d);
|
||||
|
||||
const rad = (angle * Math.PI) / 180;
|
||||
const dx = Math.cos(rad);
|
||||
const dy = Math.sin(rad);
|
||||
const steps = Math.max(1, Math.round(distance));
|
||||
const half = steps / 2;
|
||||
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
let rSum = 0;
|
||||
let gSum = 0;
|
||||
let bSum = 0;
|
||||
let aSum = 0;
|
||||
let count = 0;
|
||||
|
||||
for (let s = -half; s <= half; s++) {
|
||||
const sx = Math.round(x + dx * s);
|
||||
const sy = Math.round(y + dy * s);
|
||||
if (sx >= 0 && sx < w && sy >= 0 && sy < h) {
|
||||
const idx = (sy * w + sx) * 4;
|
||||
rSum += copy[idx];
|
||||
gSum += copy[idx + 1];
|
||||
bSum += copy[idx + 2];
|
||||
aSum += copy[idx + 3];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
const idx = (y * w + x) * 4;
|
||||
d[idx] = Math.round(rSum / count);
|
||||
d[idx + 1] = Math.round(gSum / count);
|
||||
d[idx + 2] = Math.round(bSum / count);
|
||||
d[idx + 3] = Math.round(aSum / count);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Radial blur: concentric blur emanating from a center point.
|
||||
* amount controls blur strength, centerX/centerY are 0..1 normalized.
|
||||
*/
|
||||
export function createRadialBlurFilter(params: {
|
||||
amount: number;
|
||||
centerX: number;
|
||||
centerY: number;
|
||||
}): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const { amount, centerX, centerY } = params;
|
||||
if (amount <= 0) return;
|
||||
|
||||
const w = imageData.width;
|
||||
const h = imageData.height;
|
||||
const d = imageData.data;
|
||||
const copy = new Uint8ClampedArray(d);
|
||||
|
||||
const cx = centerX * w;
|
||||
const cy = centerY * h;
|
||||
const maxDist = Math.sqrt(w * w + h * h) / 2;
|
||||
const samples = Math.max(2, Math.min(32, Math.round(amount / 3)));
|
||||
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
const dx = x - cx;
|
||||
const dy = y - cy;
|
||||
const dist = Math.sqrt(dx * dx + dy * dy);
|
||||
// Blur strength scales with distance from center
|
||||
const strength = (dist / maxDist) * (amount / 100);
|
||||
|
||||
let rSum = 0;
|
||||
let gSum = 0;
|
||||
let bSum = 0;
|
||||
let aSum = 0;
|
||||
let count = 0;
|
||||
|
||||
for (let s = 0; s < samples; s++) {
|
||||
const t = (s / (samples - 1)) * 2 - 1; // -1..1
|
||||
const sx = Math.round(x + dx * t * strength);
|
||||
const sy = Math.round(y + dy * t * strength);
|
||||
if (sx >= 0 && sx < w && sy >= 0 && sy < h) {
|
||||
const idx = (sy * w + sx) * 4;
|
||||
rSum += copy[idx];
|
||||
gSum += copy[idx + 1];
|
||||
bSum += copy[idx + 2];
|
||||
aSum += copy[idx + 3];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
const idx = (y * w + x) * 4;
|
||||
d[idx] = Math.round(rSum / count);
|
||||
d[idx + 1] = Math.round(gSum / count);
|
||||
d[idx + 2] = Math.round(bSum / count);
|
||||
d[idx + 3] = Math.round(aSum / count);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Surface blur: bilateral-like filter that blurs while preserving edges.
|
||||
* radius controls the spatial extent, threshold controls the edge sensitivity.
|
||||
*/
|
||||
export function createSurfaceBlurFilter(params: {
|
||||
radius: number;
|
||||
threshold: number;
|
||||
}): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const { radius, threshold } = params;
|
||||
if (radius <= 0) return;
|
||||
|
||||
const w = imageData.width;
|
||||
const h = imageData.height;
|
||||
const d = imageData.data;
|
||||
const copy = new Uint8ClampedArray(d);
|
||||
|
||||
const r = Math.min(radius, 10); // Cap radius for performance
|
||||
const threshSq = threshold * threshold;
|
||||
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
const idx = (y * w + x) * 4;
|
||||
const cR = copy[idx];
|
||||
const cG = copy[idx + 1];
|
||||
const cB = copy[idx + 2];
|
||||
|
||||
let rSum = 0;
|
||||
let gSum = 0;
|
||||
let bSum = 0;
|
||||
let wSum = 0;
|
||||
|
||||
for (let ky = -r; ky <= r; ky++) {
|
||||
const sy = y + ky;
|
||||
if (sy < 0 || sy >= h) continue;
|
||||
for (let kx = -r; kx <= r; kx++) {
|
||||
const sx = x + kx;
|
||||
if (sx < 0 || sx >= w) continue;
|
||||
|
||||
const sIdx = (sy * w + sx) * 4;
|
||||
const dR = copy[sIdx] - cR;
|
||||
const dG = copy[sIdx + 1] - cG;
|
||||
const dB = copy[sIdx + 2] - cB;
|
||||
const colorDist = dR * dR + dG * dG + dB * dB;
|
||||
|
||||
// Weight falls off as color difference increases
|
||||
const weight = colorDist < threshSq ? 1 - colorDist / threshSq : 0;
|
||||
|
||||
if (weight > 0) {
|
||||
rSum += copy[sIdx] * weight;
|
||||
gSum += copy[sIdx + 1] * weight;
|
||||
bSum += copy[sIdx + 2] * weight;
|
||||
wSum += weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (wSum > 0) {
|
||||
d[idx] = Math.round(rSum / wSum);
|
||||
d[idx + 1] = Math.round(gSum / wSum);
|
||||
d[idx + 2] = Math.round(bSum / wSum);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vignette: darken edges in a radial gradient pattern.
|
||||
* amount controls darkness (0..100), midpoint controls where falloff begins (0..100).
|
||||
*/
|
||||
export function createVignetteFilter(params: {
|
||||
amount: number;
|
||||
midpoint: number;
|
||||
}): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const { amount, midpoint } = params;
|
||||
if (amount <= 0) return;
|
||||
|
||||
const w = imageData.width;
|
||||
const h = imageData.height;
|
||||
const d = imageData.data;
|
||||
|
||||
const cx = w / 2;
|
||||
const cy = h / 2;
|
||||
const strength = amount / 100;
|
||||
const mid = midpoint / 100;
|
||||
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
const dx = (x - cx) / cx;
|
||||
const dy = (y - cy) / cy;
|
||||
const dist = Math.sqrt(dx * dx + dy * dy);
|
||||
// Smooth falloff: no darkening below midpoint, ramps up after
|
||||
const factor = Math.max(0, (dist - mid) / (Math.SQRT2 - mid));
|
||||
const darken = 1 - factor * factor * strength;
|
||||
|
||||
const idx = (y * w + x) * 4;
|
||||
d[idx] = Math.round(d[idx] * darken);
|
||||
d[idx + 1] = Math.round(d[idx + 1] * darken);
|
||||
d[idx + 2] = Math.round(d[idx + 2] * darken);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Grain: add random noise overlay to simulate film grain.
|
||||
* amount controls intensity (0..100), size controls grain size (1..100).
|
||||
*/
|
||||
export function createGrainFilter(params: {
|
||||
amount: number;
|
||||
size: number;
|
||||
}): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const { amount, size } = params;
|
||||
if (amount <= 0) return;
|
||||
|
||||
const w = imageData.width;
|
||||
const h = imageData.height;
|
||||
const d = imageData.data;
|
||||
|
||||
const intensity = (amount / 100) * 80; // Max noise amplitude in pixel values
|
||||
const grainSize = Math.max(1, Math.round((size / 100) * 4)); // 1..4 pixel blocks
|
||||
|
||||
// Pre-generate noise grid at reduced resolution for grain size > 1
|
||||
const nw = Math.ceil(w / grainSize);
|
||||
const nh = Math.ceil(h / grainSize);
|
||||
const noise = new Float32Array(nw * nh);
|
||||
for (let i = 0; i < noise.length; i++) {
|
||||
noise[i] = (Math.random() - 0.5) * 2 * intensity;
|
||||
}
|
||||
|
||||
for (let y = 0; y < h; y++) {
|
||||
const ny = Math.floor(y / grainSize);
|
||||
for (let x = 0; x < w; x++) {
|
||||
const nx = Math.floor(x / grainSize);
|
||||
const n = noise[ny * nw + nx];
|
||||
const idx = (y * w + x) * 4;
|
||||
d[idx] = Math.min(255, Math.max(0, Math.round(d[idx] + n)));
|
||||
d[idx + 1] = Math.min(255, Math.max(0, Math.round(d[idx + 1] + n)));
|
||||
d[idx + 2] = Math.min(255, Math.max(0, Math.round(d[idx + 2] + n)));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sharpen: unsharp mask convolution.
|
||||
* amount controls sharpening strength (0..100), radius controls kernel size.
|
||||
*/
|
||||
export function createSharpenFilter(params: {
|
||||
amount: number;
|
||||
radius: number;
|
||||
}): (imageData: ImageData) => void {
|
||||
return (imageData: ImageData) => {
|
||||
const { amount, radius } = params;
|
||||
if (amount <= 0) return;
|
||||
|
||||
const w = imageData.width;
|
||||
const h = imageData.height;
|
||||
const d = imageData.data;
|
||||
const copy = new Uint8ClampedArray(d);
|
||||
|
||||
const r = Math.max(1, Math.min(Math.round(radius), 5));
|
||||
const strength = amount / 100;
|
||||
|
||||
// Simple box blur for the "unsharp" step
|
||||
const blurred = new Float32Array(w * h * 4);
|
||||
|
||||
for (let y = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++) {
|
||||
let rSum = 0;
|
||||
let gSum = 0;
|
||||
let bSum = 0;
|
||||
let count = 0;
|
||||
|
||||
for (let ky = -r; ky <= r; ky++) {
|
||||
const sy = Math.min(h - 1, Math.max(0, y + ky));
|
||||
for (let kx = -r; kx <= r; kx++) {
|
||||
const sx = Math.min(w - 1, Math.max(0, x + kx));
|
||||
const sIdx = (sy * w + sx) * 4;
|
||||
rSum += copy[sIdx];
|
||||
gSum += copy[sIdx + 1];
|
||||
bSum += copy[sIdx + 2];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
const idx = (y * w + x) * 4;
|
||||
blurred[idx] = rSum / count;
|
||||
blurred[idx + 1] = gSum / count;
|
||||
blurred[idx + 2] = bSum / count;
|
||||
}
|
||||
}
|
||||
|
||||
// Unsharp mask: original + strength * (original - blurred)
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
d[i] = Math.min(255, Math.max(0, Math.round(copy[i] + strength * (copy[i] - blurred[i]))));
|
||||
d[i + 1] = Math.min(
|
||||
255,
|
||||
Math.max(0, Math.round(copy[i + 1] + strength * (copy[i + 1] - blurred[i + 1]))),
|
||||
);
|
||||
d[i + 2] = Math.min(
|
||||
255,
|
||||
Math.max(0, Math.round(copy[i + 2] + strength * (copy[i + 2] - blurred[i + 2]))),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { Wand2 } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { SliderRow } from "@/components/editor/common/slider-row";
|
||||
import { editorStageRefHolder } from "@/components/editor/editor-canvas";
|
||||
import { HistogramPanel } from "@/components/editor/panels/histogram-panel";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useEditorStore } from "@/stores/editor-store";
|
||||
@@ -1035,6 +1036,36 @@ export function AdjustmentsPanel() {
|
||||
const adjustments = useEditorStore((s) => s.adjustments);
|
||||
const filters = useEditorStore((s) => s.filters);
|
||||
const resetAdjustments = useEditorStore((s) => s.resetAdjustments);
|
||||
const canvasSize = useEditorStore((s) => s.canvasSize);
|
||||
|
||||
// Capture imageData from the Konva stage for the histogram
|
||||
const [histogramData, setHistogramData] = useState<ImageData | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function captureImageData() {
|
||||
const stage = editorStageRefHolder.current;
|
||||
if (!stage) return;
|
||||
try {
|
||||
const canvas = stage.toCanvas({
|
||||
pixelRatio: 1,
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: canvasSize.width,
|
||||
height: canvasSize.height,
|
||||
});
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
const data = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
setHistogramData(data);
|
||||
} catch {
|
||||
// Stage may not be ready yet
|
||||
}
|
||||
}
|
||||
|
||||
// Capture on mount and when adjustments/filters change
|
||||
const timer = setTimeout(captureImageData, 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [adjustments, filters, canvasSize]);
|
||||
|
||||
const hasChanges = useMemo(() => {
|
||||
const hasAdjustmentChanges = Object.values(adjustments).some((v) => v !== 0);
|
||||
@@ -1079,7 +1110,7 @@ export function AdjustmentsPanel() {
|
||||
return (
|
||||
<div className="flex flex-col gap-2 text-sm">
|
||||
{/* Histogram */}
|
||||
<HistogramPanel />
|
||||
<HistogramPanel imageData={histogramData} />
|
||||
|
||||
{/* Auto Adjustments */}
|
||||
<SectionHeader title="Auto" />
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
Type,
|
||||
Undo2,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useCallback, useMemo, useSyncExternalStore } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useEditorStore } from "@/stores/editor-store";
|
||||
|
||||
@@ -85,6 +85,18 @@ export function HistoryPanel() {
|
||||
// Force re-render when history changes by subscribing to history version
|
||||
useEditorStore((s) => s._historyVersion);
|
||||
|
||||
// Subscribe reactively to temporal state for undo/redo button disabled states
|
||||
const pastLength = useSyncExternalStore(
|
||||
(cb) => useEditorStore.temporal.subscribe(cb),
|
||||
() => useEditorStore.temporal.getState().pastStates.length,
|
||||
);
|
||||
const futureLength = useSyncExternalStore(
|
||||
(cb) => useEditorStore.temporal.subscribe(cb),
|
||||
() => useEditorStore.temporal.getState().futureStates.length,
|
||||
);
|
||||
const canUndo = pastLength > 0;
|
||||
const canRedo = futureLength > 0;
|
||||
|
||||
const undo = useCallback(() => {
|
||||
useEditorStore.temporal.getState().undo();
|
||||
}, []);
|
||||
@@ -151,10 +163,10 @@ export function HistoryPanel() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={undo}
|
||||
disabled={useEditorStore.temporal.getState().pastStates.length === 0}
|
||||
disabled={!canUndo}
|
||||
className={cn(
|
||||
"p-1 rounded transition-colors",
|
||||
useEditorStore.temporal.getState().pastStates.length > 0
|
||||
canUndo
|
||||
? "text-muted-foreground hover:text-foreground hover:bg-muted"
|
||||
: "text-muted-foreground/30 cursor-not-allowed",
|
||||
)}
|
||||
@@ -166,10 +178,10 @@ export function HistoryPanel() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={redo}
|
||||
disabled={useEditorStore.temporal.getState().futureStates.length === 0}
|
||||
disabled={!canRedo}
|
||||
className={cn(
|
||||
"p-1 rounded transition-colors",
|
||||
useEditorStore.temporal.getState().futureStates.length > 0
|
||||
canRedo
|
||||
? "text-muted-foreground hover:text-foreground hover:bg-muted"
|
||||
: "text-muted-foreground/30 cursor-not-allowed",
|
||||
)}
|
||||
@@ -178,9 +190,7 @@ export function HistoryPanel() {
|
||||
>
|
||||
<Redo2 size={14} />
|
||||
</button>
|
||||
<span className="ml-auto text-[10px] text-muted-foreground">
|
||||
{useEditorStore.temporal.getState().pastStates.length} / 50
|
||||
</span>
|
||||
<span className="ml-auto text-[10px] text-muted-foreground">{pastLength} / 50</span>
|
||||
</div>
|
||||
|
||||
{/* History list */}
|
||||
|
||||
@@ -369,9 +369,31 @@ function LayerRow({
|
||||
setEditing(false);
|
||||
}, [editName, layer.name, onRename]);
|
||||
|
||||
// Timer-based single-click vs double-click differentiation for the name button
|
||||
const clickTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const handleNameClick = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (clickTimerRef.current) {
|
||||
// Second click within threshold: enter rename mode
|
||||
clearTimeout(clickTimerRef.current);
|
||||
clickTimerRef.current = null;
|
||||
setEditing(true);
|
||||
} else {
|
||||
// First click: start timer; if no second click, select the layer
|
||||
clickTimerRef.current = setTimeout(() => {
|
||||
clickTimerRef.current = null;
|
||||
onSelect();
|
||||
}, 250);
|
||||
}
|
||||
},
|
||||
[onSelect],
|
||||
);
|
||||
|
||||
const handleDoubleClick = useCallback((e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setEditing(true);
|
||||
// Handled by the timer-based approach in handleNameClick
|
||||
}, []);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
@@ -526,6 +548,7 @@ function LayerRow({
|
||||
"block text-xs truncate text-left bg-transparent border-0 p-0 w-full cursor-pointer",
|
||||
isActive ? "text-foreground font-medium" : "text-muted-foreground",
|
||||
)}
|
||||
onClick={handleNameClick}
|
||||
onDoubleClick={handleDoubleClick}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
data-testid={`layer-name-${layer.id}`}
|
||||
|
||||
@@ -145,11 +145,25 @@ export function useCloneStampTool(stageRef: React.RefObject<Konva.Stage | null>)
|
||||
|
||||
paintDab(ctx, sourceSnapshot, x, y, offsetX, offsetY, brushSize, brushOpacity, canvasSize);
|
||||
|
||||
const dataUrl = canvas.toDataURL();
|
||||
useEditorStore.getState().updateObject(objectId, { src: dataUrl });
|
||||
// Use canvas element directly as image source during the stroke instead of
|
||||
// converting to a data URL on every mouse move (major perf fix).
|
||||
// The "image" property is a runtime-only hint for the renderer; cast to bypass strict attrs type.
|
||||
useEditorStore
|
||||
.getState()
|
||||
.updateObject(objectId, { image: canvas } as unknown as Record<string, unknown>);
|
||||
}, []);
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (stampRef.current) {
|
||||
const { canvas, objectId } = stampRef.current;
|
||||
const dataUrl = canvas.toDataURL();
|
||||
useEditorStore
|
||||
.getState()
|
||||
.updateObject(objectId, { src: dataUrl, image: undefined } as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>);
|
||||
}
|
||||
stampRef.current = null;
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -179,11 +179,24 @@ export function useDodgeBurnTool(stageRef: React.RefObject<Konva.Stage | null>)
|
||||
|
||||
applyBrushDab(ctx, sourceSnapshot, x, y, canvasSize);
|
||||
|
||||
const dataUrl = canvas.toDataURL();
|
||||
useEditorStore.getState().updateObject(objectId, { src: dataUrl });
|
||||
// Use canvas element directly as image source during the stroke instead of
|
||||
// converting to a data URL on every mouse move (major perf fix).
|
||||
useEditorStore
|
||||
.getState()
|
||||
.updateObject(objectId, { image: canvas } as unknown as Record<string, unknown>);
|
||||
}, []);
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (strokeRef.current) {
|
||||
const { canvas, objectId } = strokeRef.current;
|
||||
const dataUrl = canvas.toDataURL();
|
||||
useEditorStore
|
||||
.getState()
|
||||
.updateObject(objectId, { src: dataUrl, image: undefined } as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>);
|
||||
}
|
||||
strokeRef.current = null;
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -49,29 +49,41 @@ interface UseEyedropperToolOptions {
|
||||
sampleSize: SampleSize;
|
||||
}
|
||||
|
||||
export function useEyedropperTool({ stageRef, sampleSize }: UseEyedropperToolOptions) {
|
||||
export function useEyedropperTool({
|
||||
stageRef,
|
||||
sampleSize: _sampleSizeProp,
|
||||
}: UseEyedropperToolOptions) {
|
||||
const setForegroundColor = useEditorStore((s) => s.setForegroundColor);
|
||||
const setBackgroundColor = useEditorStore((s) => s.setBackgroundColor);
|
||||
const zoom = useEditorStore((s) => s.zoom);
|
||||
const panOffset = useEditorStore((s) => s.panOffset);
|
||||
const canvasSize = useEditorStore((s) => s.canvasSize);
|
||||
// Use the sampleSize prop directly (caller wires it from options state)
|
||||
const sampleSize: SampleSize = _sampleSizeProp;
|
||||
const [sampledColor, setSampledColor] = useState<string | null>(null);
|
||||
const canvasCache = useRef<HTMLCanvasElement | null>(null);
|
||||
|
||||
/**
|
||||
* Export the visible stage to a flat canvas for pixel sampling.
|
||||
* Uses explicit viewport options to get a consistent unzoomed canvas,
|
||||
* excluding zoom/pan transforms and device pixel ratio.
|
||||
* Cached so repeated clicks during one drag don't re-export.
|
||||
*/
|
||||
const getStageCanvas = useCallback((): HTMLCanvasElement | null => {
|
||||
const stage = stageRef.current;
|
||||
if (!stage) return null;
|
||||
|
||||
// Use toCanvas to get a composited view of all visible layers
|
||||
// Specify explicit viewport to exclude zoom/pan transforms
|
||||
const canvas = stage.toCanvas({
|
||||
pixelRatio: 1,
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: canvasSize.width,
|
||||
height: canvasSize.height,
|
||||
});
|
||||
canvasCache.current = canvas;
|
||||
return canvas;
|
||||
}, [stageRef]);
|
||||
}, [stageRef, canvasSize]);
|
||||
|
||||
/**
|
||||
* Invalidate the cache (call on mousedown so we get fresh data).
|
||||
@@ -102,8 +114,8 @@ export function useEyedropperTool({ stageRef, sampleSize }: UseEyedropperToolOpt
|
||||
const x = Math.round((pointer.x - panOffset.x) / zoom);
|
||||
const y = Math.round((pointer.y - panOffset.y) / zoom);
|
||||
|
||||
// Bounds check
|
||||
if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) {
|
||||
// Bounds check against the actual canvas dimensions (unzoomed)
|
||||
if (x < 0 || y < 0 || x >= canvasSize.width || y >= canvasSize.height) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -111,7 +123,7 @@ export function useEyedropperTool({ stageRef, sampleSize }: UseEyedropperToolOpt
|
||||
setSampledColor(color);
|
||||
return color;
|
||||
},
|
||||
[getStageCanvas, sampleSize, zoom, panOffset],
|
||||
[getStageCanvas, sampleSize, zoom, panOffset, canvasSize],
|
||||
);
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// apps/web/src/components/editor/tools/gradient-tool.tsx
|
||||
|
||||
import type Konva from "konva";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { generateId } from "@/lib/utils";
|
||||
import { useEditorStore } from "@/stores/editor-store";
|
||||
import type { CanvasObject } from "@/types/editor";
|
||||
@@ -11,8 +11,17 @@ interface DragState {
|
||||
startY: number;
|
||||
}
|
||||
|
||||
export interface GradientPreview {
|
||||
startX: number;
|
||||
startY: number;
|
||||
endX: number;
|
||||
endY: number;
|
||||
gradientType: "linear" | "radial";
|
||||
}
|
||||
|
||||
export function useGradientTool() {
|
||||
const dragRef = useRef<DragState | null>(null);
|
||||
const [preview, setPreview] = useState<GradientPreview | null>(null);
|
||||
|
||||
const handleMouseDown = useCallback((e: Konva.KonvaEventObject<MouseEvent>) => {
|
||||
const { activeTool, zoom, panOffset } = useEditorStore.getState();
|
||||
@@ -29,15 +38,34 @@ export function useGradientTool() {
|
||||
const y = (pointer.y - panOffset.y) / zoom;
|
||||
|
||||
dragRef.current = { startX: x, startY: y };
|
||||
|
||||
const { gradientType } = useEditorStore.getState();
|
||||
setPreview({ startX: x, startY: y, endX: x, endY: y, gradientType });
|
||||
}, []);
|
||||
|
||||
const handleMouseMove = useCallback((_e: Konva.KonvaEventObject<MouseEvent>) => {
|
||||
// Could show a preview line/circle here; keeping simple for now
|
||||
const handleMouseMove = useCallback((e: Konva.KonvaEventObject<MouseEvent>) => {
|
||||
if (!dragRef.current) return;
|
||||
|
||||
const { zoom, panOffset, gradientType } = useEditorStore.getState();
|
||||
|
||||
const stage = e.target.getStage();
|
||||
if (!stage) return;
|
||||
|
||||
const pointer = stage.getPointerPosition();
|
||||
if (!pointer) return;
|
||||
|
||||
const endX = (pointer.x - panOffset.x) / zoom;
|
||||
const endY = (pointer.y - panOffset.y) / zoom;
|
||||
const { startX, startY } = dragRef.current;
|
||||
|
||||
setPreview({ startX, startY, endX, endY, gradientType });
|
||||
}, []);
|
||||
|
||||
const handleMouseUp = useCallback((e: Konva.KonvaEventObject<MouseEvent>) => {
|
||||
if (!dragRef.current) return;
|
||||
|
||||
setPreview(null);
|
||||
|
||||
const {
|
||||
foregroundColor,
|
||||
backgroundColor,
|
||||
@@ -115,5 +143,5 @@ export function useGradientTool() {
|
||||
dragRef.current = null;
|
||||
}, []);
|
||||
|
||||
return { handleMouseDown, handleMouseMove, handleMouseUp };
|
||||
return { handleMouseDown, handleMouseMove, handleMouseUp, preview };
|
||||
}
|
||||
|
||||
@@ -383,22 +383,44 @@ export function useMoveTool(): MoveToolApi {
|
||||
const onTransformEnd = useCallback(
|
||||
(e: Konva.KonvaEventObject<Event>) => {
|
||||
const node = e.target;
|
||||
const id = node.id();
|
||||
const scaleX = node.scaleX();
|
||||
const scaleY = node.scaleY();
|
||||
|
||||
// Normalize scale into width/height
|
||||
// Normalize scale into absolute dimensions
|
||||
const newWidth = Math.max(1, node.width() * scaleX);
|
||||
const newHeight = Math.max(1, node.height() * scaleY);
|
||||
node.scaleX(1);
|
||||
node.scaleY(1);
|
||||
|
||||
updateObject(node.id(), {
|
||||
// Look up the object type to write the correct attributes
|
||||
const obj = useEditorStore.getState().objects.find((o) => o.id === id);
|
||||
const newAttrs: Record<string, unknown> = {
|
||||
x: node.x(),
|
||||
y: node.y(),
|
||||
width: newWidth,
|
||||
height: newHeight,
|
||||
rotation: node.rotation(),
|
||||
});
|
||||
};
|
||||
|
||||
if (obj?.type === "ellipse") {
|
||||
// Convert width/height to radiusX/radiusY for ellipses
|
||||
newAttrs.radiusX = newWidth / 2;
|
||||
newAttrs.radiusY = newHeight / 2;
|
||||
} else if (obj?.type === "polygon") {
|
||||
// Convert to radius for polygons (average of width/height / 2)
|
||||
newAttrs.radius = (newWidth + newHeight) / 4;
|
||||
} else if (obj?.type === "star") {
|
||||
// Scale outerRadius and innerRadius proportionally for stars
|
||||
const starAttrs = obj.attrs as { outerRadius: number; innerRadius: number };
|
||||
const avgScale = (Math.abs(scaleX) + Math.abs(scaleY)) / 2;
|
||||
newAttrs.outerRadius = starAttrs.outerRadius * avgScale;
|
||||
newAttrs.innerRadius = starAttrs.innerRadius * avgScale;
|
||||
} else {
|
||||
// Rectangles, images, text: use width/height directly
|
||||
newAttrs.width = newWidth;
|
||||
newAttrs.height = newHeight;
|
||||
}
|
||||
|
||||
updateObject(id, newAttrs);
|
||||
},
|
||||
[updateObject],
|
||||
);
|
||||
|
||||
@@ -113,11 +113,24 @@ export function usePixelBrushTool(stageRef: React.RefObject<Konva.Stage | null>)
|
||||
strokeRef.current.lastX = x;
|
||||
strokeRef.current.lastY = y;
|
||||
|
||||
const dataUrl = canvas.toDataURL();
|
||||
useEditorStore.getState().updateObject(objectId, { src: dataUrl });
|
||||
// Use canvas element directly as image source during the stroke instead of
|
||||
// converting to a data URL on every mouse move (major perf fix).
|
||||
useEditorStore
|
||||
.getState()
|
||||
.updateObject(objectId, { image: canvas } as unknown as Record<string, unknown>);
|
||||
}, []);
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (strokeRef.current) {
|
||||
const { canvas, objectId } = strokeRef.current;
|
||||
const dataUrl = canvas.toDataURL();
|
||||
useEditorStore
|
||||
.getState()
|
||||
.updateObject(objectId, { src: dataUrl, image: undefined } as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>);
|
||||
}
|
||||
strokeRef.current = null;
|
||||
}, []);
|
||||
|
||||
@@ -203,12 +216,7 @@ function applyBoxBlur(
|
||||
for (let kx = -kernelSize; kx <= kernelSize; kx++) {
|
||||
const sx = startX + px + kx;
|
||||
const sy = startY + py + ky;
|
||||
if (
|
||||
sx < 0 ||
|
||||
sx >= sourceWidth ||
|
||||
sy < 0 ||
|
||||
sy >= source.height / (source.width / sourceWidth)
|
||||
) {
|
||||
if (sx < 0 || sx >= sourceWidth || sy < 0 || sy >= source.height) {
|
||||
continue;
|
||||
}
|
||||
const si = (sy * sourceWidth + sx) * 4;
|
||||
|
||||
@@ -238,6 +238,9 @@ export function useSelectionTool(): SelectionToolApi {
|
||||
const [isDrawing, setIsDrawing] = useState(false);
|
||||
const [currentPoints, setCurrentPoints] = useState<number[]>([]);
|
||||
const startRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
|
||||
const isDrawingRef = useRef(false);
|
||||
// Polygon vertices for lasso-poly mode
|
||||
const polyVerticesRef = useRef<number[]>([]);
|
||||
|
||||
const selectionMode = useEditorStore((s) => s.selectionMode);
|
||||
|
||||
@@ -256,71 +259,227 @@ export function useSelectionTool(): SelectionToolApi {
|
||||
const nb = newSel.bounds;
|
||||
|
||||
if (mode === "add") {
|
||||
// Union of the two bounding boxes
|
||||
const x = Math.min(eb.x, nb.x);
|
||||
const y = Math.min(eb.y, nb.y);
|
||||
setSelection({
|
||||
...newSel,
|
||||
bounds: {
|
||||
x,
|
||||
y,
|
||||
width: Math.max(eb.x + eb.width, nb.x + nb.width) - x,
|
||||
height: Math.max(eb.y + eb.height, nb.y + nb.height) - y,
|
||||
},
|
||||
});
|
||||
const right = Math.max(eb.x + eb.width, nb.x + nb.width);
|
||||
const bottom = Math.max(eb.y + eb.height, nb.y + nb.height);
|
||||
|
||||
// For mask-based selections (wand, lasso), merge masks
|
||||
if (existingSelection.mask && newSel.mask) {
|
||||
const unionW = right - x;
|
||||
const unionH = bottom - y;
|
||||
const merged = new Uint8Array(unionW * unionH);
|
||||
// Copy existing mask into merged
|
||||
for (let row = 0; row < eb.height; row++) {
|
||||
for (let col = 0; col < eb.width; col++) {
|
||||
const si = row * eb.width + col;
|
||||
const di = (row + eb.y - y) * unionW + (col + eb.x - x);
|
||||
if (existingSelection.mask[si]) merged[di] = 1;
|
||||
}
|
||||
}
|
||||
// OR new mask into merged
|
||||
for (let row = 0; row < nb.height; row++) {
|
||||
for (let col = 0; col < nb.width; col++) {
|
||||
const si = row * nb.width + col;
|
||||
const di = (row + nb.y - y) * unionW + (col + nb.x - x);
|
||||
if (newSel.mask?.[si]) merged[di] = 1;
|
||||
}
|
||||
}
|
||||
setSelection({
|
||||
type: newSel.type,
|
||||
points: [],
|
||||
bounds: { x, y, width: unionW, height: unionH },
|
||||
mask: merged,
|
||||
});
|
||||
} else {
|
||||
setSelection({
|
||||
...newSel,
|
||||
bounds: { x, y, width: right - x, height: bottom - y },
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// subtract: use the new bounds minus overlap (simplified)
|
||||
setSelection(newSel);
|
||||
// Subtract mode: remove the intersection of the new selection from the existing one
|
||||
if (existingSelection.mask && newSel.mask) {
|
||||
// Mask-based subtract: AND inverse of new mask with old mask
|
||||
const result = new Uint8Array(eb.width * eb.height);
|
||||
for (let row = 0; row < eb.height; row++) {
|
||||
for (let col = 0; col < eb.width; col++) {
|
||||
const absX = eb.x + col;
|
||||
const absY = eb.y + row;
|
||||
const ei = row * eb.width + col;
|
||||
// Check if this pixel is in the new selection's mask
|
||||
const relX = absX - nb.x;
|
||||
const relY = absY - nb.y;
|
||||
let inNew = false;
|
||||
if (relX >= 0 && relX < nb.width && relY >= 0 && relY < nb.height) {
|
||||
inNew = newSel.mask?.[relY * nb.width + relX] === 1;
|
||||
}
|
||||
result[ei] = existingSelection.mask[ei] && !inNew ? 1 : 0;
|
||||
}
|
||||
}
|
||||
setSelection({
|
||||
type: existingSelection.type,
|
||||
points: existingSelection.points,
|
||||
bounds: eb,
|
||||
mask: result,
|
||||
});
|
||||
} else {
|
||||
// Geometric subtract for rectangular selections
|
||||
// If the new selection fully contains the old one, deselect
|
||||
if (
|
||||
nb.x <= eb.x &&
|
||||
nb.y <= eb.y &&
|
||||
nb.x + nb.width >= eb.x + eb.width &&
|
||||
nb.y + nb.height >= eb.y + eb.height
|
||||
) {
|
||||
setSelection(null);
|
||||
return;
|
||||
}
|
||||
// Otherwise keep the existing selection with its bounds reduced where they overlap
|
||||
// This is a simplified approach: we keep the existing bounds but trim from the side
|
||||
// with the largest overlap
|
||||
const overlapX1 = Math.max(eb.x, nb.x);
|
||||
const overlapY1 = Math.max(eb.y, nb.y);
|
||||
const overlapX2 = Math.min(eb.x + eb.width, nb.x + nb.width);
|
||||
const overlapY2 = Math.min(eb.y + eb.height, nb.y + nb.height);
|
||||
|
||||
// No overlap means nothing to subtract
|
||||
if (overlapX2 <= overlapX1 || overlapY2 <= overlapY1) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine which side the overlap is on and trim accordingly
|
||||
const trimLeft = overlapX1 === eb.x ? overlapX2 - eb.x : 0;
|
||||
const trimRight = overlapX2 === eb.x + eb.width ? eb.x + eb.width - overlapX1 : 0;
|
||||
const trimTop = overlapY1 === eb.y ? overlapY2 - eb.y : 0;
|
||||
const trimBottom = overlapY2 === eb.y + eb.height ? eb.y + eb.height - overlapY1 : 0;
|
||||
|
||||
const maxTrim = Math.max(trimLeft, trimRight, trimTop, trimBottom);
|
||||
let newBounds = { ...eb };
|
||||
if (maxTrim === trimLeft && trimLeft > 0) {
|
||||
newBounds = {
|
||||
x: eb.x + trimLeft,
|
||||
y: eb.y,
|
||||
width: eb.width - trimLeft,
|
||||
height: eb.height,
|
||||
};
|
||||
} else if (maxTrim === trimRight && trimRight > 0) {
|
||||
newBounds = { x: eb.x, y: eb.y, width: eb.width - trimRight, height: eb.height };
|
||||
} else if (maxTrim === trimTop && trimTop > 0) {
|
||||
newBounds = {
|
||||
x: eb.x,
|
||||
y: eb.y + trimTop,
|
||||
width: eb.width,
|
||||
height: eb.height - trimTop,
|
||||
};
|
||||
} else if (maxTrim === trimBottom && trimBottom > 0) {
|
||||
newBounds = { x: eb.x, y: eb.y, width: eb.width, height: eb.height - trimBottom };
|
||||
}
|
||||
|
||||
if (newBounds.width <= 0 || newBounds.height <= 0) {
|
||||
setSelection(null);
|
||||
} else {
|
||||
setSelection({
|
||||
type: existingSelection.type,
|
||||
points: existingSelection.points,
|
||||
bounds: newBounds,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
[existingSelection, setSelection],
|
||||
);
|
||||
|
||||
const isPolyLasso = useCallback(() => {
|
||||
return useEditorStore.getState().activeTool === "lasso-poly";
|
||||
}, []);
|
||||
|
||||
const onMouseDown = useCallback(
|
||||
(pos: { x: number; y: number }, _stage?: Konva.Stage) => {
|
||||
setIsDrawing(true);
|
||||
startRef.current = pos;
|
||||
if (selectionType === "lasso") {
|
||||
setCurrentPoints([pos.x, pos.y]);
|
||||
if (selectionType === "lasso" && isPolyLasso()) {
|
||||
// Polygonal lasso: each click adds a vertex
|
||||
if (!isDrawingRef.current) {
|
||||
// Start a new polygon
|
||||
setIsDrawing(true);
|
||||
isDrawingRef.current = true;
|
||||
polyVerticesRef.current = [pos.x, pos.y];
|
||||
setCurrentPoints([pos.x, pos.y]);
|
||||
} else {
|
||||
// Add another vertex
|
||||
polyVerticesRef.current = [...polyVerticesRef.current, pos.x, pos.y];
|
||||
setCurrentPoints([...polyVerticesRef.current]);
|
||||
}
|
||||
} else {
|
||||
setCurrentPoints([]);
|
||||
// Freehand lasso, rect, or ellipse
|
||||
setIsDrawing(true);
|
||||
isDrawingRef.current = true;
|
||||
startRef.current = pos;
|
||||
if (selectionType === "lasso") {
|
||||
setCurrentPoints([pos.x, pos.y]);
|
||||
} else {
|
||||
setCurrentPoints([]);
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectionType],
|
||||
[selectionType, isPolyLasso],
|
||||
);
|
||||
|
||||
const onMouseMove = useCallback(
|
||||
(pos: { x: number; y: number }) => {
|
||||
if (!isDrawing) return;
|
||||
if (!isDrawingRef.current) return;
|
||||
|
||||
if (selectionType === "lasso") {
|
||||
if (selectionType === "lasso" && isPolyLasso()) {
|
||||
// Polygonal lasso: show rubber band line from last vertex to cursor
|
||||
const verts = polyVerticesRef.current;
|
||||
setCurrentPoints([...verts, pos.x, pos.y]);
|
||||
} else if (selectionType === "lasso") {
|
||||
// Freehand lasso
|
||||
setCurrentPoints((prev) => [...prev, pos.x, pos.y]);
|
||||
} else {
|
||||
const s = startRef.current;
|
||||
setCurrentPoints([s.x, s.y, pos.x, pos.y]);
|
||||
}
|
||||
},
|
||||
[isDrawing, selectionType],
|
||||
[selectionType, isPolyLasso],
|
||||
);
|
||||
|
||||
const onMouseUp = useCallback(() => {
|
||||
if (!isDrawing) return;
|
||||
setIsDrawing(false);
|
||||
|
||||
if (selectionType === "lasso") {
|
||||
if (currentPoints.length < 6) {
|
||||
const finalizeLasso = useCallback(
|
||||
(points: number[]) => {
|
||||
if (points.length < 6) {
|
||||
setSelection(null);
|
||||
setCurrentPoints([]);
|
||||
return;
|
||||
}
|
||||
const xs = currentPoints.filter((_, i) => i % 2 === 0);
|
||||
const ys = currentPoints.filter((_, i) => i % 2 === 1);
|
||||
const xs = points.filter((_, i) => i % 2 === 0);
|
||||
const ys = points.filter((_, i) => i % 2 === 1);
|
||||
const bounds = {
|
||||
x: Math.min(...xs),
|
||||
y: Math.min(...ys),
|
||||
width: Math.max(...xs) - Math.min(...xs),
|
||||
height: Math.max(...ys) - Math.min(...ys),
|
||||
};
|
||||
mergeSelection({ type: "lasso", points: currentPoints, bounds }, selectionMode);
|
||||
mergeSelection({ type: "lasso", points, bounds }, selectionMode);
|
||||
setCurrentPoints([]);
|
||||
},
|
||||
[selectionMode, mergeSelection, setSelection],
|
||||
);
|
||||
|
||||
const onMouseUp = useCallback(() => {
|
||||
if (!isDrawingRef.current) return;
|
||||
|
||||
if (selectionType === "lasso" && isPolyLasso()) {
|
||||
// Polygonal lasso: mouseUp does NOT close the polygon, only dblclick does.
|
||||
// The vertex was already added in onMouseDown, so nothing to do here.
|
||||
return;
|
||||
}
|
||||
|
||||
setIsDrawing(false);
|
||||
isDrawingRef.current = false;
|
||||
|
||||
if (selectionType === "lasso") {
|
||||
finalizeLasso(currentPoints);
|
||||
} else {
|
||||
if (currentPoints.length < 4) {
|
||||
setCurrentPoints([]);
|
||||
@@ -346,30 +505,26 @@ export function useSelectionTool(): SelectionToolApi {
|
||||
);
|
||||
}
|
||||
setCurrentPoints([]);
|
||||
}, [isDrawing, currentPoints, selectionType, selectionMode, mergeSelection, setSelection]);
|
||||
}, [
|
||||
currentPoints,
|
||||
selectionType,
|
||||
selectionMode,
|
||||
mergeSelection,
|
||||
setSelection,
|
||||
finalizeLasso,
|
||||
isPolyLasso,
|
||||
]);
|
||||
|
||||
const onDoubleClick = useCallback(() => {
|
||||
// Close polygonal lasso
|
||||
if (selectionType === "lasso" && currentPoints.length >= 6) {
|
||||
if (selectionType === "lasso" && isDrawingRef.current) {
|
||||
setIsDrawing(false);
|
||||
const xs = currentPoints.filter((_, i) => i % 2 === 0);
|
||||
const ys = currentPoints.filter((_, i) => i % 2 === 1);
|
||||
mergeSelection(
|
||||
{
|
||||
type: "lasso",
|
||||
points: currentPoints,
|
||||
bounds: {
|
||||
x: Math.min(...xs),
|
||||
y: Math.min(...ys),
|
||||
width: Math.max(...xs) - Math.min(...xs),
|
||||
height: Math.max(...ys) - Math.min(...ys),
|
||||
},
|
||||
},
|
||||
selectionMode,
|
||||
);
|
||||
setCurrentPoints([]);
|
||||
isDrawingRef.current = false;
|
||||
const verts = polyVerticesRef.current;
|
||||
finalizeLasso(verts);
|
||||
polyVerticesRef.current = [];
|
||||
}
|
||||
}, [selectionType, currentPoints, selectionMode, mergeSelection]);
|
||||
}, [selectionType, finalizeLasso]);
|
||||
|
||||
const selectAll = useCallback(() => {
|
||||
setSelection({
|
||||
@@ -385,16 +540,33 @@ export function useSelectionTool(): SelectionToolApi {
|
||||
|
||||
const magicWandSelect = useCallback(
|
||||
(stage: Konva.Stage, x: number, y: number, tolerance: number, contiguous: boolean) => {
|
||||
const canvas = stage.toCanvas();
|
||||
// Use explicit viewport options to get a consistent unzoomed canvas,
|
||||
// ignoring zoom/pan transforms and device pixel ratio
|
||||
const canvas = stage.toCanvas({
|
||||
pixelRatio: 1,
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: canvasSize.width,
|
||||
height: canvasSize.height,
|
||||
});
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
const imageData = ctx.getImageData(0, 0, canvasSize.width, canvasSize.height);
|
||||
const mask = floodFillMask(imageData, x, y, tolerance, contiguous);
|
||||
const bounds = maskToBounds(mask);
|
||||
if (!bounds) return;
|
||||
mergeSelection({ type: "rect", points: [], bounds }, selectionMode);
|
||||
|
||||
// Convert the boolean[][] mask to a flat Uint8Array within the bounds region
|
||||
const flatMask = new Uint8Array(bounds.width * bounds.height);
|
||||
for (let row = 0; row < bounds.height; row++) {
|
||||
for (let col = 0; col < bounds.width; col++) {
|
||||
flatMask[row * bounds.width + col] = mask[bounds.y + row][bounds.x + col] ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
mergeSelection({ type: "wand", points: [], bounds, mask: flatMask }, selectionMode);
|
||||
},
|
||||
[selectionMode, mergeSelection],
|
||||
[selectionMode, mergeSelection, canvasSize],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -204,14 +204,49 @@ export function TransformToolTransformer({
|
||||
const handleTransformEnd = useCallback(
|
||||
(e: Konva.KonvaEventObject<Event>) => {
|
||||
const node = e.target;
|
||||
const id = node.id();
|
||||
const scaleX = node.scaleX();
|
||||
const scaleY = node.scaleY();
|
||||
const newW = Math.max(1, node.width() * scaleX);
|
||||
const newH = Math.max(1, node.height() * scaleY);
|
||||
|
||||
// Reset scale on the Konva node
|
||||
node.scaleX(1);
|
||||
node.scaleY(1);
|
||||
node.width(newW);
|
||||
node.height(newH);
|
||||
|
||||
// Directly update the store with the new attributes
|
||||
if (id) {
|
||||
const obj = useEditorStore.getState().objects.find((o) => o.id === id);
|
||||
const newAttrs: Record<string, unknown> = {
|
||||
x: node.x(),
|
||||
y: node.y(),
|
||||
rotation: node.rotation(),
|
||||
};
|
||||
|
||||
if (obj?.type === "ellipse") {
|
||||
// Convert width/height to radiusX/radiusY for ellipses
|
||||
newAttrs.radiusX = newW / 2;
|
||||
newAttrs.radiusY = newH / 2;
|
||||
} else if (obj?.type === "polygon") {
|
||||
// Convert width/height to radius for polygons
|
||||
newAttrs.radius = (newW + newH) / 4;
|
||||
} else if (obj?.type === "star") {
|
||||
// Scale outerRadius and innerRadius proportionally for stars
|
||||
const starAttrs = obj.attrs as { outerRadius: number; innerRadius: number };
|
||||
const avgScale = (Math.abs(scaleX) + Math.abs(scaleY)) / 2;
|
||||
newAttrs.outerRadius = starAttrs.outerRadius * avgScale;
|
||||
newAttrs.innerRadius = starAttrs.innerRadius * avgScale;
|
||||
} else {
|
||||
// Rectangles, images, text: use width/height directly
|
||||
newAttrs.width = newW;
|
||||
newAttrs.height = newH;
|
||||
}
|
||||
|
||||
useEditorStore.getState().updateObject(id, newAttrs);
|
||||
}
|
||||
|
||||
onTransformEnd?.(e);
|
||||
},
|
||||
[onTransformEnd],
|
||||
|
||||
Reference in New Issue
Block a user