Files
flypic/frontend/src/components/ImageEditor.jsx
T

1788 lines
73 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* ImageEditor — fabric.js 图片编辑器
* 工具:选择 / 文字(大小·颜色·发光·旋转·透明度)/ 表情 / 自媒体文字模板 /
* 贴图(添加图片)/ 水印(单个·平铺)/ AI(高清·去背景·抠图·去水印涂抹·换脸)
* 裁剪(比例·三分线·拖拽)/ 旋转翻转 / 图像大小 / 调色(亮度·对比度·饱和度·色相·模糊·黑白·反色·复古·自动色阶)
* 保存:覆盖原图 / 另存为新图(后端转码并重建缩略图)
*/
import { useState, useEffect, useRef } from 'react';
import { Canvas, FabricImage, IText, Shadow, ActiveSelection, Point } from 'fabric';
import {
MousePointer2, Type, Smile, LayoutTemplate, ImagePlus, Stamp, Sparkles,
Pencil, X, Trash2, Loader2, Eraser, Wand2, LayoutGrid, Undo2, Redo2,
Crop, SlidersHorizontal, RotateCw, RotateCcw, FlipHorizontal, FlipVertical, Maximize2
} from 'lucide-react';
import { useUIStore } from '../stores/useUIStore';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { imageAPI } from '../api';
import { getToken } from '../api/client';
import MergeCollage from './MergeCollage';
const EMOJIS = [
'😀', '😂', '🤣', '😍', '🥰', '😎', '🤔', '😭',
'😅', '😡', '🥳', '😱', '👍', '👎', '👏', '🙏',
'💪', '🤝', '✌️', '👌', '🤙', '❤️', '🔥', '⭐',
'✨', '💯', '🎉', '🎊', '💰', '📈', '📉', '🎯',
'📌', '💡', '📸', '🎵', '🚀', '🏆', '🥇', '✅',
'🍉', '🍔', '☕', '🐶', '🐱', '🌈', '⏰', '📝'
];
const TEMPLATES = [
{ label: '爆款标题', text: '爆款标题', style: { fontSize: 72, fill: '#fff200', stroke: '#1a1a1a', strokeWidth: 6, paintFirst: 'stroke', fontWeight: 'bold' } },
{ label: '干货满满', text: '干货满满', style: { fontSize: 56, fill: '#ffffff', textBackgroundColor: '#e11d48', fontWeight: 'bold' } },
{ label: '点击关注', text: '点击关注', style: { fontSize: 48, fill: '#ffffff', textBackgroundColor: '#2563eb', fontWeight: 'bold' } },
{ label: '限时免费', text: '限时免费', style: { fontSize: 52, fill: '#ffffff', textBackgroundColor: '#f59e0b', fontWeight: 'bold' } },
{ label: '建议收藏', text: '建议收藏', style: { fontSize: 44, fill: '#ffffff', textBackgroundColor: '#16a34a', fontWeight: 'bold' } },
{ label: '文末有惊喜', text: '文末有惊喜', style: { fontSize: 44, fill: '#fff200', stroke: '#1a1a1a', strokeWidth: 4, paintFirst: 'stroke', fontWeight: 'bold' } },
{ label: '每日更新', text: '每日更新', style: { fontSize: 40, fill: '#a21caf', textBackgroundColor: '#fce7f3', fontWeight: 'bold' } },
{ label: '全网最全', text: '全网最全', style: { fontSize: 48, fill: '#0ea5e9', stroke: '#ffffff', strokeWidth: 3, paintFirst: 'stroke', fontWeight: 'bold' } },
{ label: '关注不迷路', text: '关注我,不迷路', style: { fontSize: 40, fill: '#ffffff', textBackgroundColor: '#111827', fontWeight: 'bold' } },
{ label: '记得点赞', text: '记得点赞', style: { fontSize: 40, fill: '#e11d48', fontWeight: 'bold' } }
];
const ASPECTS = [
{ key: 'free', label: '自由', r: 0 },
{ key: '1:1', label: '1:1', r: 1 },
{ key: '4:3', label: '4:3', r: 4 / 3 },
{ key: '3:2', label: '3:2', r: 1.5 },
{ key: '16:9', label: '16:9', r: 16 / 9 },
{ key: '9:16', label: '9:16', r: 9 / 16 }
];
const ADJ_DEFAULT = {
brightness: 0, contrast: 0, saturate: 0, hue: 0, blur: 0,
grayscale: false, invert: false, sepia: false, autoLevel: false
};
const ADJ_SLIDERS = [
{ k: 'brightness', label: '亮度', min: -100, max: 100 },
{ k: 'contrast', label: '对比度', min: -100, max: 100 },
{ k: 'saturate', label: '饱和度', min: -100, max: 100 },
{ k: 'hue', label: '色相', min: 0, max: 360, unit: '°' },
{ k: 'blur', label: '模糊', min: 0, max: 20, unit: 'px' }
];
const ADJ_TOGGLES = [
{ k: 'grayscale', label: '黑白' },
{ k: 'invert', label: '反色' },
{ k: 'sepia', label: '复古' },
{ k: 'autoLevel', label: '自动色阶' }
];
const TOOLS = [
{ id: 'select', icon: MousePointer2, label: '选择' },
{ id: 'text', icon: Type, label: '文字' },
{ id: 'sticker', icon: Smile, label: '表情' },
{ id: 'template', icon: LayoutTemplate, label: '模板' },
{ id: 'image', icon: ImagePlus, label: '贴图' },
{ id: 'watermark', icon: Stamp, label: '水印' },
{ id: 'merge', icon: LayoutGrid, label: '合拼' },
{ id: 'crop', icon: Crop, label: '裁剪' },
{ id: 'adjust', icon: SlidersHorizontal, label: '调色' },
{ id: 'ai', icon: Sparkles, label: 'AI工具' }
];
function ImageEditor() {
const { editingImage, setEditingImage } = useUIStore();
const { currentLibraryId } = useLibraryStore();
const { updateImage, bumpRefresh } = useImageStore();
const canvasElRef = useRef(null);
const maskCanvasRef = useRef(null);
const stickerInputRef = useRef(null);
const faceInputRef = useRef(null);
const fabricRef = useRef(null);
const baseInfoRef = useRef({ naturalW: 0, naturalH: 0, displayW: 0, displayH: 0 });
const baseBlobRef = useRef(null);
const dirtyRef = useRef(false);
const drawingRef = useRef(false);
const lastPtRef = useRef(null);
const [size, setSize] = useState({ w: 0, h: 0 });
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [activeTool, setActiveTool] = useState('select');
const [selProps, setSelProps] = useState(null);
const [aiBusy, setAiBusy] = useState('');
const [saving, setSaving] = useState(false);
const [status, setStatus] = useState('');
// 文字工具
const [newFontSize, setNewFontSize] = useState(48);
// 水印
const [wmText, setWmText] = useState('我的水印');
const [wmSize, setWmSize] = useState(5);
const [wmOpacity, setWmOpacity] = useState(30);
// 去水印涂抹
const [maskMode, setMaskMode] = useState(false);
const [brushSize, setBrushSize] = useState(30);
// 抠图底色
const [bgColor, setBgColor] = useState('#ffffff');
// 裁剪
const [cropAspect, setCropAspect] = useState('free');
const [cropRect, setCropRect] = useState(null);
const [resizeW, setResizeW] = useState('');
const cropDragRef = useRef(null);
// 调色
const [adj, setAdj] = useState(ADJ_DEFAULT);
const [adjBusy, setAdjBusy] = useState(false);
const adjSourceRef = useRef(null); // 调色基准图(Blob)
const adjImgRef = useRef(null); // 解码后的基准图(预览复用)
const adjDirtyRef = useRef(false); // 有未应用的调色预览
const adjSeqRef = useRef(0); // 预览序号(丢弃过期渲染)
// ---------- 初始化画布 ----------
useEffect(() => {
if (!editingImage || !currentLibraryId || !canvasElRef.current) return;
let disposed = false;
(async () => {
setLoading(true);
setError('');
try {
const url = imageAPI.getOriginalUrl(currentLibraryId, editingImage.path);
const headers = getToken() ? { Authorization: `Bearer ${getToken()}` } : {};
const resp = await fetch(url, { headers });
if (!resp.ok) throw new Error(`原图加载失败 (${resp.status})`);
const blob = await resp.blob();
if (disposed) return;
baseBlobRef.current = blob;
const objUrl = URL.createObjectURL(blob);
const img = await FabricImage.fromURL(objUrl);
URL.revokeObjectURL(objUrl);
if (disposed) return;
// 适配显示尺寸(小图适度放大便于编辑,导出时按原始分辨率输出)
const maxW = 900;
const maxH = 640;
const scale = Math.min(maxW / img.width, maxH / img.height, 4);
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
setSize({ w, h });
baseInfoRef.current = { naturalW: img.width, naturalH: img.height, displayW: w, displayH: h };
const canvas = new Canvas(canvasElRef.current, {
width: w,
height: h,
backgroundColor: 'transparent',
preserveObjectStacking: true,
selection: true
});
img.set({ left: 0, top: 0, scaleX: scale, scaleY: scale });
canvas.backgroundImage = img;
canvas.requestRenderAll();
const syncProps = () => {
const obj = canvas.getActiveObject();
if (!obj) return setSelProps(null);
if (obj.type === 'activeSelection') return setSelProps({ type: 'multi' });
setSelProps({
type: obj.type,
text: obj.text ?? '',
fontSize: obj.fontSize ?? 48,
fill: typeof obj.fill === 'string' ? obj.fill : '#ffffff',
angle: Math.round(obj.angle ?? 0),
opacity: Math.round((obj.opacity ?? 1) * 100),
glowOn: !!obj.shadow,
glowColor: (obj.shadow && obj.shadow.color) || '#ffff00',
glowBlur: (obj.shadow && obj.shadow.blur) || 20
});
};
canvas.on('selection:created', syncProps);
canvas.on('selection:updated', syncProps);
canvas.on('selection:cleared', () => setSelProps(null));
canvas.on('object:modified', syncProps);
canvas.on('object:added', () => { dirtyRef.current = true; });
canvas.on('object:removed', () => { dirtyRef.current = true; });
fabricRef.current = canvas;
dirtyRef.current = false;
} catch (err) {
if (!disposed) setError(err.message || '初始化失败');
} finally {
if (!disposed) setLoading(false);
}
})();
return () => {
disposed = true;
if (fabricRef.current) {
fabricRef.current.dispose();
fabricRef.current = null;
}
setSize({ w: 0, h: 0 });
setSelProps(null);
setMaskMode(false);
dirtyRef.current = false;
};
}, [editingImage, currentLibraryId]);
// ---------- 裁剪:进入工具时初始化选区 / 离开时清理 ----------
useEffect(() => {
if (activeTool !== 'crop') { setCropRect(null); return; }
if (!size.w) return;
const W = baseInfoRef.current.displayW;
const H = baseInfoRef.current.displayH;
if (!W || !H) return;
const a = ASPECTS.find((x) => x.key === cropAspect);
let w = W * 0.84;
let h = H * 0.84;
if (a && a.r) { w = Math.min(w, h * a.r); h = w / a.r; }
setCropRect({ x: Math.round((W - w) / 2), y: Math.round((H - h) / 2), w: Math.round(w), h: Math.round(h) });
setResizeW(String(baseInfoRef.current.naturalW || ''));
const cv = fabricRef.current;
if (cv) { cv.discardActiveObject(); cv.requestRenderAll(); }
setSelProps(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeTool, size.w, editingImage]);
// ---------- 调色:进入工具时缓存解码基准图 ----------
useEffect(() => {
if (activeTool !== 'adjust' || !editingImage) return;
initAdjustSource();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeTool, editingImage]);
// ---------- 多选「合拼」带图进入:自动切到合拼工具 ----------
useEffect(() => {
if (!editingImage) return;
const st = useUIStore.getState();
if (st.mergeImages && st.mergeImages.length >= 1) {
setActiveTool('merge');
}
}, [editingImage]);
// ---------- AI 结果替换底层图片(保留文字/贴图叠加层) ----------
const replaceBaseImage = async (blob) => {
const canvas = fabricRef.current;
if (!canvas) return;
const { displayW } = baseInfoRef.current;
const objUrl = URL.createObjectURL(blob);
try {
const img = await FabricImage.fromURL(objUrl);
const scale = displayW / img.width;
img.set({ left: 0, top: 0, scaleX: scale, scaleY: scale });
canvas.backgroundImage = img;
baseInfoRef.current = {
...baseInfoRef.current,
naturalW: img.width,
naturalH: img.height
};
baseBlobRef.current = blob;
dirtyRef.current = true;
canvas.requestRenderAll();
syncAdjustSource(blob);
} finally {
URL.revokeObjectURL(objUrl);
}
};
// ---------- 合拼结果替换底图(宽高比可能变化,需同步画布尺寸) ----------
const replaceBaseImageSized = async (blob) => {
const canvas = fabricRef.current;
if (!canvas) return;
const objUrl = URL.createObjectURL(blob);
try {
const img = await FabricImage.fromURL(objUrl);
// 与初始化一致的显示适配规则
const maxW = 900;
const maxH = 640;
const scale = Math.min(maxW / img.width, maxH / img.height, 4);
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
const oldW = baseInfoRef.current.displayW || w;
const oldH = baseInfoRef.current.displayH || h;
canvas.setDimensions({ width: w, height: h });
setSize({ w, h });
// 已有叠加对象按新旧尺寸比例迁移位置/大小
const rx = oldW ? w / oldW : 1;
const ry = oldH ? h / oldH : 1;
canvas.getObjects().forEach((o) => {
o.set({
left: (o.left || 0) * rx,
top: (o.top || 0) * ry,
scaleX: (o.scaleX || 1) * rx,
scaleY: (o.scaleY || 1) * ry
});
o.setCoords();
});
img.set({ left: 0, top: 0, scaleX: scale, scaleY: scale });
canvas.backgroundImage = img;
baseInfoRef.current = {
naturalW: img.width,
naturalH: img.height,
displayW: w,
displayH: h
};
baseBlobRef.current = blob;
dirtyRef.current = true;
canvas.requestRenderAll();
syncAdjustSource(blob);
} finally {
URL.revokeObjectURL(objUrl);
}
};
const callAI = async (action, buildForm, label) => {
setAiBusy(label);
setStatus('');
try {
await ensureAdjustCommitted();
const fd = new FormData();
fd.append('action', action);
buildForm(fd);
const resp = await fetch('/api/edit/ai', {
method: 'POST',
headers: getToken() ? { Authorization: `Bearer ${getToken()}` } : {},
body: fd
});
if (!resp.ok) {
let msg = `AI 处理失败 (${resp.status})`;
try {
const j = await resp.json();
if (j.error) msg = j.error;
} catch (_) { /* 非 JSON */ }
throw new Error(msg);
}
const blob = await resp.blob();
await replaceBaseImage(blob);
setStatus(`${label}完成`);
} catch (err) {
setStatus(err.message || 'AI 处理失败');
} finally {
setAiBusy('');
}
};
// ---------- 对象操作 ----------
const getActive = () => fabricRef.current && fabricRef.current.getActiveObject();
const updateActive = (patch) => {
const canvas = fabricRef.current;
const obj = getActive();
if (!canvas || !obj || obj.type === 'activeSelection') return;
obj.set(patch);
obj.setCoords();
canvas.requestRenderAll();
// 重新同步
setSelProps((prev) => (prev ? { ...prev, ...patch, angle: Math.round(patch.angle ?? obj.angle ?? 0), opacity: patch.opacity ?? prev.opacity } : prev));
};
const setGlow = (on, color, blur) => {
const canvas = fabricRef.current;
const obj = getActive();
if (!canvas || !obj) return;
obj.set('shadow', on ? new Shadow({ color, blur, offsetX: 0, offsetY: 0 }) : null);
canvas.requestRenderAll();
setSelProps((prev) => (prev ? { ...prev, glowOn: on, glowColor: color, glowBlur: blur } : prev));
};
const removeActive = () => {
const canvas = fabricRef.current;
const obj = getActive();
if (!canvas || !obj) return;
if (obj.type === 'activeSelection') {
obj.getObjects().forEach((o) => canvas.remove(o));
} else {
canvas.remove(obj);
}
canvas.discardActiveObject();
canvas.requestRenderAll();
setSelProps(null);
};
const addText = (text, style = {}) => {
const canvas = fabricRef.current;
if (!canvas) return;
const { displayW, displayH } = baseInfoRef.current;
const t = new IText(text, {
left: displayW / 2,
top: displayH / 2,
originX: 'center',
originY: 'center',
fontSize: Math.round(displayH * 0.09),
fill: '#ffffff',
stroke: '#000000',
strokeWidth: 2,
paintFirst: 'stroke',
fontFamily: 'sans-serif',
angle: 0,
...style
});
canvas.add(t);
canvas.setActiveObject(t);
canvas.requestRenderAll();
try {
t.enterEditing();
t.selectAll();
} catch (_) { /* 双击可再次编辑 */ }
setActiveTool('select');
};
const addEmoji = (ch) => {
const canvas = fabricRef.current;
if (!canvas) return;
const { displayW, displayH } = baseInfoRef.current;
const t = new IText(ch, {
left: displayW / 2,
top: displayH / 2,
originX: 'center',
originY: 'center',
fontSize: Math.round(displayH * 0.16),
strokeWidth: 0,
angle: 0
});
canvas.add(t);
canvas.setActiveObject(t);
canvas.requestRenderAll();
setActiveTool('select');
};
const addStickerImage = async (e) => {
const file = e.target.files && e.target.files[0];
e.target.value = '';
const canvas = fabricRef.current;
if (!file || !canvas) return;
const objUrl = URL.createObjectURL(file);
try {
const img = await FabricImage.fromURL(objUrl);
const { displayW, displayH } = baseInfoRef.current;
const scale = (displayW * 0.4) / img.width;
img.set({
left: displayW / 2,
top: displayH / 2,
originX: 'center',
originY: 'center',
scaleX: scale,
scaleY: scale
});
canvas.add(img);
canvas.setActiveObject(img);
canvas.requestRenderAll();
setActiveTool('select');
} catch (err) {
setStatus('贴图加载失败: ' + (err.message || ''));
} finally {
URL.revokeObjectURL(objUrl);
}
};
const addWatermark = (tile) => {
const canvas = fabricRef.current;
if (!canvas) return;
const { displayW, displayH } = baseInfoRef.current;
const base = {
fill: '#ffffff',
strokeWidth: 0,
opacity: wmOpacity / 100,
angle: -25,
fontFamily: 'sans-serif',
isWatermark: true
};
if (!tile) {
const t = new IText(wmText || '水印', {
left: displayW / 2,
top: displayH / 2,
originX: 'center',
originY: 'center',
fontSize: Math.round(displayH * (wmSize / 100)),
...base
});
canvas.add(t);
canvas.setActiveObject(t);
} else {
const fontSize = Math.round(displayH * (wmSize / 100));
const gapX = Math.max(fontSize * (wmText || '水印').length * 0.7, 160);
const gapY = Math.max(fontSize * 2.4, 140);
const objs = [];
for (let y = gapY * 0.4; y < displayH; y += gapY) {
for (let x = gapX * 0.3; x < displayW; x += gapX) {
objs.push(new IText(wmText || '水印', {
left: x,
top: y,
originX: 'left',
originY: 'top',
fontSize,
...base
}));
}
}
objs.forEach((o) => canvas.add(o));
if (objs[0]) canvas.setActiveObject(objs[0]);
}
canvas.requestRenderAll();
setActiveTool('select');
};
const clearWatermarks = () => {
const canvas = fabricRef.current;
if (!canvas) return;
canvas.getObjects().filter((o) => o.isWatermark).forEach((o) => canvas.remove(o));
canvas.discardActiveObject();
canvas.requestRenderAll();
setSelProps(null);
};
// ---------- 去水印涂抹 ----------
const enterMaskMode = () => {
const canvas = fabricRef.current;
if (!canvas) return;
canvas.discardActiveObject();
canvas.selection = false;
canvas.skipTargetFind = true;
canvas.requestRenderAll();
setSelProps(null);
setMaskMode(true);
};
const exitMaskMode = (clear = true) => {
const canvas = fabricRef.current;
if (canvas) {
canvas.selection = true;
canvas.skipTargetFind = false;
canvas.requestRenderAll();
}
if (clear && maskCanvasRef.current) {
const ctx = maskCanvasRef.current.getContext('2d');
ctx.clearRect(0, 0, maskCanvasRef.current.width, maskCanvasRef.current.height);
}
setMaskMode(false);
};
const maskPoint = (e) => {
const c = maskCanvasRef.current;
const rect = c.getBoundingClientRect();
return {
x: (e.clientX - rect.left) * (c.width / rect.width),
y: (e.clientY - rect.top) * (c.height / rect.height)
};
};
const onMaskDown = (e) => {
e.currentTarget.setPointerCapture(e.pointerId);
drawingRef.current = true;
lastPtRef.current = maskPoint(e);
};
const onMaskMove = (e) => {
if (!drawingRef.current) return;
const c = maskCanvasRef.current;
const ctx = c.getContext('2d');
const pt = maskPoint(e);
const rect = c.getBoundingClientRect();
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = brushSize * (c.width / rect.width);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.beginPath();
ctx.moveTo(lastPtRef.current.x, lastPtRef.current.y);
ctx.lineTo(pt.x, pt.y);
ctx.stroke();
lastPtRef.current = pt;
};
const onMaskUp = () => {
drawingRef.current = false;
lastPtRef.current = null;
};
const clearMask = () => {
const c = maskCanvasRef.current;
if (c) c.getContext('2d').clearRect(0, 0, c.width, c.height);
};
const applyInpaint = async () => {
const c = maskCanvasRef.current;
const base = baseBlobRef.current;
if (!c || !base) return;
const { naturalW, naturalH } = baseInfoRef.current;
const off = document.createElement('canvas');
off.width = naturalW;
off.height = naturalH;
const ctx = off.getContext('2d');
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, naturalW, naturalH);
ctx.drawImage(c, 0, 0, naturalW, naturalH);
const maskBlob = await new Promise((resolve) => off.toBlob(resolve, 'image/png'));
if (!maskBlob) {
setStatus('蒙版导出失败');
return;
}
await callAI(
'inpaint',
(fd) => {
fd.append('image', base, 'base.png');
fd.append('mask', maskBlob, 'mask.png');
},
'去水印修复'
);
clearMask();
exitMaskMode(false);
};
// ---------- 其余 AI ----------
const runUpscale = (scale) => {
const base = baseBlobRef.current;
if (!base) return;
callAI('upscale', (fd) => {
fd.append('image', base, 'base.png');
fd.append('scale', String(scale));
}, `AI 高清 ×${scale}`);
};
const runRemoveBg = (mode, color) => {
const base = baseBlobRef.current;
if (!base) return;
callAI('removebg', (fd) => {
fd.append('image', base, 'base.png');
fd.append('mode', mode);
if (mode === 'color' && color) fd.append('bg_color', color);
}, mode === 'transparent' ? '去背景' : '抠图');
};
const runFaceSwap = async (e) => {
const file = e.target.files && e.target.files[0];
e.target.value = '';
const base = baseBlobRef.current;
if (!file || !base) return;
await callAI('faceswap', (fd) => {
fd.append('source', file, file.name || 'face.png');
fd.append('target', base, 'target.png');
}, '换脸');
};
// ================= 裁剪 / 旋转翻转 / 图像大小 / 调色 =================
const blobToImage = (blob) => new Promise((resolve, reject) => {
const u = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => { URL.revokeObjectURL(u); resolve(img); };
img.onerror = (e) => { URL.revokeObjectURL(u); reject(new Error('图片解码失败')); };
img.src = u;
});
const blobFromCanvas = (c, mime) => new Promise((resolve) => {
c.toBlob((b) => resolve(b), mime || 'image/png', (mime || 'image/png') === 'image/jpeg' ? 0.95 : undefined);
});
const pickMime = (blob) => {
const t = blob && blob.type;
if (t === 'image/jpeg' || t === 'image/webp' || t === 'image/png') return t;
return 'image/png';
};
// ---------- 调色 ----------
const buildFilterStr = (a, blurPx) => {
const p = [];
if (a.brightness) p.push(`brightness(${1 + a.brightness / 100})`);
if (a.contrast) p.push(`contrast(${1 + a.contrast / 100})`);
if (a.saturate) p.push(`saturate(${1 + a.saturate / 100})`);
if (a.hue) p.push(`hue-rotate(${a.hue}deg)`);
if (blurPx > 0) p.push(`blur(${blurPx}px)`);
if (a.grayscale) p.push('grayscale(1)');
if (a.invert) p.push('invert(1)');
if (a.sepia) p.push('sepia(1)');
return p.join(' ');
};
const applyAutoLevel = (ctx, w, h) => {
const d = ctx.getImageData(0, 0, w, h);
const px = d.data;
const mn = [255, 255, 255];
const mx = [0, 0, 0];
for (let i = 0; i < px.length; i += 4) {
for (let c = 0; c < 3; c++) {
const v = px[i + c];
if (v < mn[c]) mn[c] = v;
if (v > mx[c]) mx[c] = v;
}
}
const gain = [0, 0, 0];
for (let c = 0; c < 3; c++) gain[c] = mx[c] > mn[c] ? 255 / (mx[c] - mn[c]) : 1;
for (let i = 0; i < px.length; i += 4) {
for (let c = 0; c < 3; c++) px[i + c] = (px[i + c] - mn[c]) * gain[c];
}
ctx.putImageData(d, 0, 0);
};
// 底图变化时同步调色状态(清空预览、恢复默认值)
const syncAdjustSource = (blob) => {
adjSourceRef.current = blob;
adjImgRef.current = null;
adjDirtyRef.current = false;
adjSeqRef.current++;
setAdj(ADJ_DEFAULT);
};
const initAdjustSource = async () => {
if (adjSourceRef.current !== baseBlobRef.current) {
adjSourceRef.current = baseBlobRef.current;
adjImgRef.current = null;
}
if (!adjImgRef.current && baseBlobRef.current) {
try { adjImgRef.current = await blobToImage(baseBlobRef.current); } catch (_) { /* 预览时再试 */ }
}
if (adjDirtyRef.current) renderAdjustPreview(adj);
};
const renderAdjustPreview = async (a) => {
const canvas = fabricRef.current;
if (!canvas || !baseBlobRef.current) return;
if (adjSourceRef.current !== baseBlobRef.current) {
adjSourceRef.current = baseBlobRef.current;
adjImgRef.current = null;
}
if (!adjImgRef.current) {
try { adjImgRef.current = await blobToImage(baseBlobRef.current); } catch (_) { return; }
}
const seq = ++adjSeqRef.current;
const { displayW, displayH, naturalW } = baseInfoRef.current;
const c = document.createElement('canvas');
c.width = displayW;
c.height = displayH;
const ctx = c.getContext('2d');
// 预览在显示分辨率绘制,模糊按比例换算,所见即所得
const blurPx = naturalW ? a.blur * (displayW / naturalW) : a.blur;
const f = buildFilterStr(a, blurPx);
if (f) ctx.filter = f;
ctx.drawImage(adjImgRef.current, 0, 0, displayW, displayH);
ctx.filter = 'none';
if (a.autoLevel) applyAutoLevel(ctx, displayW, displayH);
const blob = await blobFromCanvas(c, 'image/png');
if (!blob || seq !== adjSeqRef.current) return; // 过期请求丢弃
const u = URL.createObjectURL(blob);
try {
const fi = await FabricImage.fromURL(u);
if (seq !== adjSeqRef.current) return;
fi.set({ left: 0, top: 0, scaleX: 1, scaleY: 1 });
canvas.backgroundImage = fi;
adjDirtyRef.current = true;
dirtyRef.current = true;
canvas.requestRenderAll();
} finally {
URL.revokeObjectURL(u);
}
};
const previewTimerRef = useRef(null);
const onAdjChange = (patch) => {
const next = { ...adj, ...patch };
setAdj(next);
clearTimeout(previewTimerRef.current);
previewTimerRef.current = setTimeout(() => renderAdjustPreview(next), 90);
};
// 全分辨率烘焙调色(保存/AI/裁剪/旋转前调用)
const applyAdjustFull = async () => {
const canvas = fabricRef.current;
if (!canvas || !adjDirtyRef.current || !baseBlobRef.current) return;
if (!adjImgRef.current) {
try { adjImgRef.current = await blobToImage(adjSourceRef.current || baseBlobRef.current); } catch (_) { return; }
}
const { naturalW, naturalH } = baseInfoRef.current;
const c = document.createElement('canvas');
c.width = naturalW;
c.height = naturalH;
const ctx = c.getContext('2d');
const f = buildFilterStr(adj, adj.blur);
if (f) ctx.filter = f;
ctx.drawImage(adjImgRef.current, 0, 0, naturalW, naturalH);
ctx.filter = 'none';
if (adj.autoLevel) applyAutoLevel(ctx, naturalW, naturalH);
const blob = await blobFromCanvas(c, pickMime(baseBlobRef.current));
if (!blob) return;
adjDirtyRef.current = false;
await replaceBaseImage(blob); // 内部 syncAdjustSource 清空预览状态
setStatus('调整已应用');
};
const ensureAdjustCommitted = async () => {
if (adjDirtyRef.current) await applyAdjustFull();
};
const cancelAdjust = async () => {
adjSeqRef.current++;
adjDirtyRef.current = false;
setAdj(ADJ_DEFAULT);
const wasDirty = dirtyRef.current;
if (baseBlobRef.current) {
await replaceBaseImage(baseBlobRef.current); // 恢复未预览的原图
dirtyRef.current = wasDirty; // 仅取消调色不算修改
}
};
// ---------- 裁剪 ----------
const onCropPointerDown = (e, mode) => {
e.stopPropagation();
e.preventDefault();
if (!cropRect) return;
cropDragRef.current = { mode, sx: e.clientX, sy: e.clientY, r0: { ...cropRect } };
e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId);
};
const onCropPointerMove = (e) => {
const d = cropDragRef.current;
if (!d || !cropRect) return;
const W = size.w;
const H = size.h;
const MIN = 48;
const dx = e.clientX - d.sx;
const dy = e.clientY - d.sy;
const r0 = d.r0;
const a = ASPECTS.find((x) => x.key === cropAspect);
const ratio = a && a.r ? a.r : 0;
let r;
if (d.mode === 'move') {
r = { x: Math.min(Math.max(0, r0.x + dx), W - r0.w), y: Math.min(Math.max(0, r0.y + dy), H - r0.h), w: r0.w, h: r0.h };
} else {
// 角点缩放:对角为锚点
const ax = d.mode === 'se' || d.mode === 'ne' ? r0.x : r0.x + r0.w;
const ay = d.mode === 'se' || d.mode === 'sw' ? r0.y : r0.y + r0.h;
const anchorLeft = d.mode === 'se' || d.mode === 'ne';
const anchorTop = d.mode === 'se' || d.mode === 'sw';
let w = anchorLeft ? r0.w + dx : r0.w - dx;
let h = anchorTop ? r0.h + dy : r0.h - dy;
w = Math.max(MIN, w);
h = Math.max(MIN, h);
const maxW = anchorLeft ? W - ax : ax;
const maxH = anchorTop ? H - ay : ay;
if (ratio) {
if (Math.abs(dx) >= Math.abs(dy)) h = w / ratio;
else w = h * ratio;
w = Math.min(w, maxW);
h = w / ratio;
if (h > maxH) { h = maxH; w = h * ratio; }
w = Math.min(w, maxW);
} else {
w = Math.min(w, maxW);
h = Math.min(h, maxH);
}
r = {
x: anchorLeft ? ax : ax - w,
y: anchorTop ? ay : ay - h,
w: Math.round(w),
h: Math.round(h)
};
}
setCropRect(r);
};
const onCropPointerUp = () => { cropDragRef.current = null; };
const setAspect = (key) => {
setCropAspect(key);
const a = ASPECTS.find((x) => x.key === key);
if (!a || !a.r || !cropRect) return;
const W = size.w;
const H = size.h;
const cx = cropRect.x + cropRect.w / 2;
const cy = cropRect.y + cropRect.h / 2;
let w = Math.min(cropRect.w, cropRect.h * a.r);
let h = w / a.r;
if (h > H) { h = H; w = h * a.r; }
w = Math.min(w, W);
h = w / a.r;
let x = Math.round(cx - w / 2);
let y = Math.round(cy - h / 2);
x = Math.min(Math.max(0, x), W - Math.round(w));
y = Math.min(Math.max(0, y), H - Math.round(h));
setCropRect({ x, y, w: Math.round(w), h: Math.round(h) });
};
const applyCrop = async () => {
const canvas = fabricRef.current;
if (!canvas || !cropRect || saving) return;
const { naturalW, naturalH, displayW, displayH } = baseInfoRef.current;
if (!naturalW || !displayW) return;
const kx = naturalW / displayW;
const ky = naturalH / displayH;
let sx = Math.round(cropRect.x * kx);
let sy = Math.round(cropRect.y * ky);
let sw = Math.round(cropRect.w * kx);
let sh = Math.round(cropRect.h * ky);
sx = Math.min(Math.max(0, sx), naturalW - 1);
sy = Math.min(Math.max(0, sy), naturalH - 1);
sw = Math.max(1, Math.min(sw, naturalW - sx));
sh = Math.max(1, Math.min(sh, naturalH - sy));
const base = baseBlobRef.current;
if (!base) return;
setAiBusy('裁剪中…');
try {
await ensureAdjustCommitted(); // 调色预览先烘焙
const img = await blobToImage(baseBlobRef.current);
const c = document.createElement('canvas');
c.width = sw;
c.height = sh;
c.getContext('2d').drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
const blob = await blobFromCanvas(c, pickMime(base));
if (!blob) throw new Error('裁剪失败');
// 叠加层:整体平移,删掉完全落在裁剪区外的对象
canvas.discardActiveObject();
setSelProps(null);
const cw = cropRect.w;
const ch = cropRect.h;
canvas.getObjects().forEach((o) => {
o.set({ left: (o.left || 0) - cropRect.x, top: (o.top || 0) - cropRect.y });
o.setCoords();
const b = o.getBoundingRect();
if (b.left + b.width < 0 || b.top + b.height < 0 || b.left > cw || b.top > ch) canvas.remove(o);
});
// 预先把显示基准切到裁剪区域,复用尺寸自适应替换逻辑
baseInfoRef.current = { ...baseInfoRef.current, displayW: cw, displayH: ch };
await replaceBaseImageSized(blob);
setCropRect(null);
setActiveTool('select');
setStatus(`已裁剪 ${sw}×${sh}`);
} catch (err) {
setStatus(err.message || '裁剪失败');
} finally {
setAiBusy('');
}
};
// ---------- 旋转 / 翻转 ----------
const transformBase = async (kind) => {
const canvas = fabricRef.current;
const base = baseBlobRef.current;
if (!canvas || !base || aiBusy) return;
setAiBusy(kind === 'fliph' || kind === 'flipv' ? '翻转中…' : '旋转中…');
try {
await ensureAdjustCommitted();
const srcBlob = baseBlobRef.current;
const { naturalW: nw0, naturalH: nh0, displayW, displayH } = baseInfoRef.current;
const img = await blobToImage(srcBlob);
const swap = kind === 'cw90' || kind === 'ccw90';
const c = document.createElement('canvas');
c.width = swap ? nh0 : nw0;
c.height = swap ? nw0 : nh0;
const ctx = c.getContext('2d');
if (kind === 'cw90') { ctx.translate(c.width, 0); ctx.rotate(Math.PI / 2); }
else if (kind === 'ccw90') { ctx.translate(0, c.height); ctx.rotate(-Math.PI / 2); }
else if (kind === 'r180') { ctx.translate(c.width, c.height); ctx.rotate(Math.PI); }
else if (kind === 'fliph') { ctx.translate(c.width, 0); ctx.scale(-1, 1); }
else { ctx.translate(0, c.height); ctx.scale(1, -1); }
ctx.drawImage(img, 0, 0);
const blob = await blobFromCanvas(c, pickMime(srcBlob));
if (!blob) throw new Error('处理失败');
// 叠加层同步几何变换(以对象中心计算,兼容不同原点)
canvas.discardActiveObject();
setSelProps(null);
canvas.getObjects().forEach((o) => {
const ctr = o.getCenterPoint();
let nx = ctr.x;
let ny = ctr.y;
let na = o.angle || 0;
if (kind === 'cw90') { nx = displayH - ctr.y; ny = ctr.x; na += 90; }
else if (kind === 'ccw90') { nx = ctr.y; ny = displayW - ctr.x; na -= 90; }
else if (kind === 'r180') { nx = displayW - ctr.x; ny = displayH - ctr.y; na += 180; }
else if (kind === 'fliph') { nx = displayW - ctr.x; ny = ctr.y; na = -na; }
else { nx = ctr.x; ny = displayH - ctr.y; na = -na; }
if (kind === 'fliph') o.set('scaleX', -(o.scaleX || 1));
if (kind === 'flipv') o.set('scaleY', -(o.scaleY || 1));
o.set('angle', na);
const ctr2 = o.getCenterPoint();
o.set({ left: (o.left || 0) + (nx - ctr2.x), top: (o.top || 0) + (ny - ctr2.y) });
o.setCoords();
});
const ndW = swap ? displayH : displayW;
const ndH = swap ? displayW : displayH;
canvas.setDimensions({ width: ndW, height: ndH });
setSize({ w: ndW, h: ndH });
const u = URL.createObjectURL(blob);
let bg;
try {
bg = await FabricImage.fromURL(u);
} finally {
URL.revokeObjectURL(u);
}
const scale = ndW / bg.width;
bg.set({ left: 0, top: 0, scaleX: scale, scaleY: scale });
canvas.backgroundImage = bg;
baseInfoRef.current = { naturalW: bg.width, naturalH: bg.height, displayW: ndW, displayH: ndH };
baseBlobRef.current = blob;
dirtyRef.current = true;
canvas.requestRenderAll();
syncAdjustSource(blob);
setStatus(kind === 'cw90' ? '已顺时针旋转 90°'
: kind === 'ccw90' ? '已逆时针旋转 90°'
: kind === 'r180' ? '已旋转 180°'
: kind === 'fliph' ? '已水平翻转' : '已垂直翻转');
} catch (err) {
setStatus(err.message || '处理失败');
} finally {
setAiBusy('');
}
};
// ---------- 图像大小(按宽度等比缩放) ----------
const applyResize = async () => {
const canvas = fabricRef.current;
const base = baseBlobRef.current;
const { naturalW: W, naturalH: H } = baseInfoRef.current;
const target = Math.round(Number(resizeW));
if (!canvas || !base || !W) return;
if (!target || target < 16 || target > 12000) { setStatus('宽度需在 16~12000 之间'); return; }
if (target === W) { setStatus('宽度未变化'); return; }
const targetH = Math.max(1, Math.round(H * target / W));
if (target * targetH > 80000000) { setStatus('目标尺寸过大(超过 8000 万像素)'); return; }
setAiBusy('缩放中…');
try {
await ensureAdjustCommitted();
const img = await blobToImage(baseBlobRef.current);
const c = document.createElement('canvas');
c.width = target;
c.height = targetH;
const ctx = c.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, target, targetH);
const blob = await blobFromCanvas(c, pickMime(base));
if (!blob) throw new Error('缩放失败');
canvas.discardActiveObject();
setSelProps(null);
await replaceBaseImageSized(blob);
setResizeW(String(target));
setStatus(`已缩放为 ${target}×${targetH}`);
} catch (err) {
setStatus(err.message || '缩放失败');
} finally {
setAiBusy('');
}
};
// ---------- 保存 ----------
const doSave = async (mode) => {
const canvas = fabricRef.current;
if (!canvas || saving) return;
const { naturalW, displayW } = baseInfoRef.current;
if (!naturalW) return;
setSaving(true);
setStatus('');
try {
await ensureAdjustCommitted();
const multiplier = naturalW / displayW;
const dataURL = canvas.toDataURL({ format: 'png', multiplier });
const blob = await (await fetch(dataURL)).blob();
const fd = new FormData();
fd.append('image', blob, 'edit.png');
fd.append('libraryId', currentLibraryId);
fd.append('path', editingImage.path);
fd.append('mode', mode);
const resp = await fetch('/api/edit/save', {
method: 'POST',
headers: getToken() ? { Authorization: `Bearer ${getToken()}` } : {},
body: fd
});
const j = await resp.json().catch(() => ({}));
if (!resp.ok) throw new Error(j.error || `保存失败 (${resp.status})`);
if (j.mode === 'overwrite') {
updateImage(editingImage.path, { size: j.size, modifiedAt: j.modifiedAt });
setStatus('已覆盖保存');
} else {
bumpRefresh();
imageAPI.getFolders(currentLibraryId)
.then((r) => useImageStore.getState().setFolders(r.folders))
.catch(() => {});
setStatus(`已另存为 ${j.filename}`);
}
dirtyRef.current = false;
setTimeout(() => setEditingImage(null), 700);
} catch (err) {
setStatus(err.message || '保存失败');
} finally {
setSaving(false);
}
};
const handleClose = () => {
if (dirtyRef.current && !window.confirm('有未保存的修改,确定关闭?')) return;
setEditingImage(null);
};
// ---------- 快捷键 ----------
useEffect(() => {
if (!editingImage) return;
const onKeyDown = (e) => {
const tag = document.activeElement && document.activeElement.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') return;
const obj = fabricRef.current && fabricRef.current.getActiveObject();
if (obj && obj.isEditing) return;
if (e.key === 'Escape') {
if (maskMode) exitMaskMode();
else if (activeTool === 'crop') setActiveTool('select');
else handleClose();
} else if ((e.key === 'Delete' || e.key === 'Backspace') && obj && !maskMode && activeTool !== 'crop') {
e.preventDefault();
removeActive();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [editingImage, maskMode, activeTool]);
if (!editingImage) return null;
const isTextSel = selProps && (selProps.type === 'i-text' || selProps.type === 'textbox' || selProps.type === 'text');
const isImgSel = selProps && selProps.type === 'image';
return (
<div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-2 md:p-6">
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full h-full max-w-[1440px] max-h-[920px] flex flex-col overflow-hidden">
{/* 头部 */}
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex-shrink-0 gap-3">
<div className="flex items-center gap-2 min-w-0">
<Pencil className="w-4 h-4 text-blue-500 flex-shrink-0" />
<span className="font-medium text-gray-800 dark:text-gray-200 truncate">{editingImage.filename}</span>
{status && <span className="text-xs text-green-600 dark:text-green-400 flex-shrink-0">{status}</span>}
{loading && <span className="text-xs text-gray-400 flex-shrink-0">加载中…</span>}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<button
onClick={() => doSave('overwrite')}
disabled={saving || loading}
className="px-3 py-1.5 text-sm rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
{saving ? '保存中…' : '覆盖原图'}
</button>
<button
onClick={() => doSave('new')}
disabled={saving || loading}
className="px-3 py-1.5 text-sm rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 transition-colors"
>
另存为新图
</button>
<button
onClick={handleClose}
className="p-1.5 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
title="关闭"
>
<X className="w-5 h-5" />
</button>
</div>
</div>
<div className="flex flex-1 min-h-0">
{/* 左侧工具栏 */}
<div className="w-16 border-r border-gray-200 dark:border-gray-700 flex flex-col items-center py-2 gap-1 overflow-y-auto flex-shrink-0">
{TOOLS.map((t) => {
const Icon = t.icon;
const active = activeTool === t.id;
return (
<button
key={t.id}
onClick={() => {
setActiveTool(t.id);
if (maskMode && t.id !== 'ai') exitMaskMode();
}}
className={`w-12 py-2 rounded-lg flex flex-col items-center gap-0.5 transition-colors ${
active
? 'bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
title={t.label}
>
<Icon className="w-4 h-4" />
<span className="text-[10px] leading-none">{t.label}</span>
</button>
);
})}
</div>
{/* 画布区 */}
<div className="flex-1 min-w-0 overflow-auto bg-gray-100 dark:bg-gray-900 flex items-center justify-center p-4 relative">
{error ? (
<div className="text-red-500 text-sm">{error}</div>
) : (
<div className="relative" style={{ width: size.w || 1, height: size.h || 1 }}>
<canvas ref={canvasElRef} />
{maskMode && size.w > 0 && (
<canvas
ref={maskCanvasRef}
width={size.w}
height={size.h}
className="absolute top-0 left-0"
style={{ opacity: 0.65, cursor: 'crosshair', touchAction: 'none' }}
onPointerDown={onMaskDown}
onPointerMove={onMaskMove}
onPointerUp={onMaskUp}
onPointerLeave={onMaskUp}
/>
)}
{activeTool === 'crop' && cropRect && size.w > 0 && (
<div
className="absolute inset-0 z-20"
style={{ touchAction: 'none' }}
onPointerMove={onCropPointerMove}
onPointerUp={onCropPointerUp}
onPointerCancel={onCropPointerUp}
>
<div
className="absolute"
style={{
left: cropRect.x,
top: cropRect.y,
width: cropRect.w,
height: cropRect.h,
boxShadow: '0 0 0 9999px rgba(0,0,0,0.55)',
border: '1.5px solid #60a5fa',
cursor: 'move',
boxSizing: 'border-box'
}}
onPointerDown={(e) => onCropPointerDown(e, 'move')}
>
<div className="absolute left-1/3 top-0 bottom-0 w-px bg-white/40 pointer-events-none" />
<div className="absolute left-2/3 top-0 bottom-0 w-px bg-white/40 pointer-events-none" />
<div className="absolute top-1/3 left-0 right-0 h-px bg-white/40 pointer-events-none" />
<div className="absolute top-2/3 left-0 right-0 h-px bg-white/40 pointer-events-none" />
{[['nw', 'left-[-6px] top-[-6px]', 'nwse-resize'],
['ne', 'right-[-6px] top-[-6px]', 'nesw-resize'],
['sw', 'left-[-6px] bottom-[-6px]', 'nesw-resize'],
['se', 'right-[-6px] bottom-[-6px]', 'nwse-resize']].map(([dir, pos, cur]) => (
<div
key={dir}
onPointerDown={(e) => onCropPointerDown(e, dir)}
className={`absolute w-3 h-3 bg-white border-2 border-blue-500 rounded-sm ${pos}`}
style={{ cursor: cur, touchAction: 'none' }}
/>
))}
</div>
</div>
)}
{loading && (
<div className="absolute inset-0 flex items-center justify-center bg-white/60 dark:bg-gray-900/60">
<Loader2 className="w-6 h-6 animate-spin text-blue-500" />
</div>
)}
</div>
)}
{aiBusy && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 z-10">
<div className="flex items-center gap-2 bg-white dark:bg-gray-800 rounded-lg px-4 py-3 shadow-xl">
<Loader2 className="w-5 h-5 animate-spin text-blue-500" />
<span className="text-sm text-gray-700 dark:text-gray-300">{aiBusy}{aiBusy.endsWith('…') ? '' : ',约 5~30 秒…'}</span>
</div>
</div>
)}
{!loading && !error && (
<div className="absolute bottom-2 left-1/2 -translate-x-1/2 text-[11px] text-gray-400 dark:text-gray-500 pointer-events-none whitespace-nowrap">
拖拽移动 · 双击编辑文字 · Delete 删除 · Esc 关闭
</div>
)}
</div>
{/* 右侧属性面板 */}
<div className="w-64 md:w-72 border-l border-gray-200 dark:border-gray-700 overflow-y-auto p-3 space-y-4 flex-shrink-0">
{/* 选中对象属性优先 */}
{selProps && selProps.type !== 'multi' && (isTextSel || isImgSel) && (
<div className="space-y-3 p-3 rounded-lg bg-blue-50/60 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800">
<div className="flex items-center justify-between">
<span className="text-xs font-semibold text-blue-700 dark:text-blue-300">
{isTextSel ? '文字属性' : '图片属性'}
</span>
<button
onClick={removeActive}
className="p-1 rounded text-red-500 hover:bg-red-100 dark:hover:bg-red-900/40"
title="删除对象"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
{isTextSel && (
<>
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">内容</label>
<textarea
value={selProps.text}
onChange={(e) => updateActive({ text: e.target.value })}
rows={2}
className="w-full mt-1 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200 px-2 py-1 outline-none focus:border-blue-400"
/>
</div>
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">字号:{selProps.fontSize}</label>
<input
type="range"
min={8}
max={300}
value={selProps.fontSize}
onChange={(e) => updateActive({ fontSize: Number(e.target.value) })}
className="w-full mt-1"
/>
</div>
<div className="flex items-center gap-2">
<label className="text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">颜色</label>
<input
type="color"
value={selProps.fill}
onChange={(e) => updateActive({ fill: e.target.value })}
className="w-8 h-6 rounded border border-gray-300 dark:border-gray-600 cursor-pointer bg-transparent"
/>
<label className="text-xs text-gray-500 dark:text-gray-400 flex-shrink-0 ml-2">发光</label>
<input
type="checkbox"
checked={selProps.glowOn}
onChange={(e) => setGlow(e.target.checked, selProps.glowColor, selProps.glowBlur)}
/>
<input
type="color"
value={selProps.glowColor}
onChange={(e) => setGlow(true, e.target.value, selProps.glowBlur)}
className="w-8 h-6 rounded border border-gray-300 dark:border-gray-600 cursor-pointer bg-transparent"
disabled={!selProps.glowOn}
/>
</div>
{selProps.glowOn && (
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">发光强度:{selProps.glowBlur}</label>
<input
type="range"
min={2}
max={60}
value={selProps.glowBlur}
onChange={(e) => setGlow(true, selProps.glowColor, Number(e.target.value))}
className="w-full mt-1"
/>
</div>
)}
</>
)}
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">旋转:{selProps.angle}°</label>
<input
type="range"
min={-180}
max={180}
value={selProps.angle}
onChange={(e) => updateActive({ angle: Number(e.target.value) })}
className="w-full mt-1"
/>
</div>
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">透明度:{selProps.opacity}%</label>
<input
type="range"
min={5}
max={100}
value={selProps.opacity}
onChange={(e) => updateActive({ opacity: Number(e.target.value) / 100 })}
className="w-full mt-1"
/>
</div>
</div>
)}
{selProps && selProps.type === 'multi' && (
<div className="p-3 rounded-lg bg-gray-100 dark:bg-gray-700 text-xs text-gray-500 dark:text-gray-400">
已选中多个对象,按 Delete 取消选择或删除
</div>
)}
{/* 工具面板 */}
{activeTool === 'select' && !selProps && (
<div className="text-xs text-gray-400 dark:text-gray-500 leading-relaxed">
点击画布中的对象可编辑属性;左侧切换工具添加内容。
</div>
)}
{activeTool === 'crop' && (
<div className="space-y-3">
<div className="text-xs font-semibold text-gray-700 dark:text-gray-300">裁剪比例</div>
<div className="grid grid-cols-3 gap-1.5">
{ASPECTS.map((a) => (
<button
key={a.key}
onClick={() => setAspect(a.key)}
className={`py-1.5 text-xs rounded-lg border transition-colors ${
cropAspect === a.key
? 'bg-blue-600 border-blue-600 text-white'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
{a.label}
</button>
))}
</div>
<div className="flex gap-2">
<button
onClick={applyCrop}
disabled={!cropRect || !!aiBusy}
className="flex-1 py-1.5 text-xs rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
应用裁剪
</button>
<button
onClick={() => { setCropRect(null); setActiveTool('select'); }}
disabled={!!aiBusy}
className="flex-1 py-1.5 text-xs rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50"
>
取消
</button>
</div>
<p className="text-[11px] text-gray-400">拖动选区移动,拖四角缩放;比例可锁定。Esc 退出。</p>
<div className="space-y-2 pt-2 border-t border-gray-200 dark:border-gray-700">
<div className="text-xs font-semibold text-gray-700 dark:text-gray-300">旋转 / 翻转</div>
<div className="grid grid-cols-3 gap-1.5">
{[
{ k: 'ccw90', label: '⟲ 左转' },
{ k: 'cw90', label: '⟳ 右转' },
{ k: 'r180', label: '180°' },
{ k: 'fliph', label: '⇄ 水平' },
{ k: 'flipv', label: '⇅ 垂直' }
].map((b) => (
<button
key={b.k}
onClick={() => transformBase(b.k)}
disabled={!!aiBusy || saving}
className="py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
>
{b.label}
</button>
))}
</div>
<p className="text-[11px] text-gray-400">底图和文字、贴图一起变换。</p>
</div>
<div className="space-y-2 pt-2 border-t border-gray-200 dark:border-gray-700">
<div className="text-xs font-semibold text-gray-700 dark:text-gray-300">图像大小</div>
<div className="text-[11px] text-gray-400">
当前:{baseInfoRef.current.naturalW || '—'} × {baseInfoRef.current.naturalH || '—'} px
</div>
<div className="flex gap-2">
<input
type="number"
min={16}
max={12000}
value={resizeW}
onChange={(e) => setResizeW(e.target.value)}
placeholder="宽度 px"
className="flex-1 px-2 py-1.5 text-xs border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-100"
/>
<button
onClick={applyResize}
disabled={!!aiBusy || saving}
className="px-3 py-1.5 text-xs rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
缩放
</button>
</div>
<p className="text-[11px] text-gray-400">按宽度等比缩放(16~12000 px)。</p>
</div>
</div>
)}
{activeTool === 'adjust' && (
<div className="space-y-3">
<div className="text-xs font-semibold text-gray-700 dark:text-gray-300">色彩调整</div>
{ADJ_SLIDERS.map((sl) => (
<div key={sl.k}>
<div className="flex justify-between text-[11px] text-gray-500 dark:text-gray-400">
<span>{sl.label}</span>
<span>{adj[sl.k]}{sl.unit || ''}</span>
</div>
<input
type="range"
min={sl.min}
max={sl.max}
value={adj[sl.k]}
onChange={(e) => onAdjChange({ [sl.k]: Number(e.target.value) })}
className="w-full accent-blue-500"
/>
</div>
))}
<div className="grid grid-cols-2 gap-1.5">
{ADJ_TOGGLES.map((t) => (
<button
key={t.k}
onClick={() => onAdjChange({ [t.k]: !adj[t.k] })}
className={`py-1.5 text-xs rounded-lg border transition-colors ${
adj[t.k]
? 'bg-blue-600 border-blue-600 text-white'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
{t.label}
</button>
))}
</div>
<div className="flex gap-2">
<button
onClick={applyAdjustFull}
disabled={!!aiBusy || saving}
className="flex-1 py-1.5 text-xs rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
应用
</button>
<button
onClick={cancelAdjust}
disabled={!!aiBusy || saving}
className="flex-1 py-1.5 text-xs rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50"
>
还原
</button>
</div>
<p className="text-[11px] text-gray-400">拖动即时预览;保存、裁剪、AI 处理时自动按原分辨率应用。</p>
</div>
)}
{activeTool === 'text' && (
<div className="space-y-3">
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">初始字号:{newFontSize}</label>
<input
type="range"
min={12}
max={200}
value={newFontSize}
onChange={(e) => setNewFontSize(Number(e.target.value))}
className="w-full mt-1"
/>
</div>
<button
onClick={() => addText('双击编辑文字', { fontSize: newFontSize })}
className="w-full py-2 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 transition-colors"
>
+ 添加文字
</button>
<p className="text-[11px] text-gray-400">添加后可设置大小、颜色、发光、旋转、透明度</p>
</div>
)}
{activeTool === 'sticker' && (
<div className="grid grid-cols-6 gap-1">
{EMOJIS.map((ch) => (
<button
key={ch}
onClick={() => addEmoji(ch)}
className="text-xl py-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
{ch}
</button>
))}
</div>
)}
{activeTool === 'template' && (
<div className="space-y-2">
{TEMPLATES.map((tpl) => (
<button
key={tpl.label}
onClick={() => addText(tpl.text, tpl.style)}
className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 text-left hover:border-blue-400 hover:bg-blue-50/50 dark:hover:bg-blue-900/20 transition-colors"
>
<span
className="text-sm font-bold"
style={{
color: tpl.style.fill,
backgroundColor: tpl.style.textBackgroundColor || 'transparent',
padding: tpl.style.textBackgroundColor ? '1px 6px' : 0,
WebkitTextStroke: tpl.style.strokeWidth ? `${Math.min(tpl.style.strokeWidth / 2, 2)}px ${tpl.style.stroke}` : undefined
}}
>
{tpl.label}
</span>
</button>
))}
<p className="text-[11px] text-gray-400">点击插入,插入后可继续修改</p>
</div>
)}
{activeTool === 'image' && (
<div className="space-y-3">
<button
onClick={() => stickerInputRef.current && stickerInputRef.current.click()}
className="w-full py-2 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 transition-colors"
>
+ 选择图片作为贴图
</button>
<input ref={stickerInputRef} type="file" accept="image/*" className="hidden" onChange={addStickerImage} />
<p className="text-[11px] text-gray-400">插入后可拖拽、缩放、旋转</p>
</div>
)}
{activeTool === 'watermark' && (
<div className="space-y-3">
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">水印文字</label>
<input
type="text"
value={wmText}
onChange={(e) => setWmText(e.target.value)}
className="w-full mt-1 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200 px-2 py-1.5 outline-none focus:border-blue-400"
placeholder="输入水印文字"
/>
</div>
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">大小:{wmSize}%</label>
<input type="range" min={2} max={15} value={wmSize} onChange={(e) => setWmSize(Number(e.target.value))} className="w-full mt-1" />
</div>
<div>
<label className="text-xs text-gray-500 dark:text-gray-400">不透明度:{wmOpacity}%</label>
<input type="range" min={5} max={100} value={wmOpacity} onChange={(e) => setWmOpacity(Number(e.target.value))} className="w-full mt-1" />
</div>
<div className="flex gap-2">
<button
onClick={() => addWatermark(false)}
className="flex-1 py-2 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 transition-colors"
>
单个水印
</button>
<button
onClick={() => addWatermark(true)}
className="flex-1 py-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
>
平铺水印
</button>
</div>
<button
onClick={clearWatermarks}
className="w-full py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors flex items-center justify-center gap-1"
>
<Eraser className="w-3.5 h-3.5" /> 清除全部水印
</button>
</div>
)}
{activeTool === 'merge' && (
<MergeCollage
image={editingImage}
libraryId={currentLibraryId}
onMerge={replaceBaseImageSized}
setStatus={setStatus}
setBusy={setAiBusy}
/>
)}
{activeTool === 'ai' && (
<div className="space-y-4">
<div>
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">AI 高清</div>
<div className="flex gap-2">
<button
onClick={() => runUpscale(2)}
disabled={!!aiBusy}
className="flex-1 py-2 rounded-lg bg-gradient-to-r from-blue-500 to-cyan-500 text-white text-sm hover:opacity-90 disabled:opacity-50 transition-opacity"
>
×2 放大
</button>
<button
onClick={() => runUpscale(4)}
disabled={!!aiBusy}
className="flex-1 py-2 rounded-lg bg-gradient-to-r from-blue-500 to-cyan-500 text-white text-sm hover:opacity-90 disabled:opacity-50 transition-opacity"
>
×4 放大
</button>
</div>
</div>
<div>
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">去背景 / 抠图</div>
<button
onClick={() => runRemoveBg('transparent')}
disabled={!!aiBusy}
className="w-full py-2 rounded-lg bg-emerald-600 text-white text-sm hover:bg-emerald-700 disabled:opacity-50 transition-colors mb-2"
>
去背景(透明底)
</button>
<div className="flex gap-2 items-center">
<input
type="color"
value={bgColor}
onChange={(e) => setBgColor(e.target.value)}
className="w-9 h-8 rounded border border-gray-300 dark:border-gray-600 cursor-pointer bg-transparent flex-shrink-0"
/>
<button
onClick={() => runRemoveBg('color', bgColor)}
disabled={!!aiBusy}
className="flex-1 py-2 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 transition-colors"
>
抠图(自定义底色)
</button>
</div>
</div>
<div>
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">去水印(涂抹修复)</div>
{maskMode ? (
<div className="space-y-2 p-2 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800">
<p className="text-[11px] text-amber-700 dark:text-amber-300">在图片上涂抹水印区域,然后点击修复</p>
<div>
<label className="text-xs text-amber-700 dark:text-amber-300">笔刷:{brushSize}px</label>
<input
type="range"
min={8}
max={100}
value={brushSize}
onChange={(e) => setBrushSize(Number(e.target.value))}
className="w-full mt-1"
/>
</div>
<div className="flex gap-2">
<button
onClick={applyInpaint}
disabled={!!aiBusy}
className="flex-1 py-1.5 rounded bg-amber-600 text-white text-xs hover:bg-amber-700 disabled:opacity-50 transition-colors"
>
{aiBusy ? '修复中…' : '开始修复'}
</button>
<button
onClick={clearMask}
className="px-3 py-1.5 rounded bg-white dark:bg-gray-700 border border-amber-300 dark:border-amber-700 text-xs text-amber-700 dark:text-amber-300"
>
清除
</button>
<button
onClick={() => exitMaskMode()}
className="px-3 py-1.5 rounded bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 text-xs text-gray-500"
>
取消
</button>
</div>
</div>
) : (
<button
onClick={enterMaskMode}
disabled={!!aiBusy}
className="w-full py-2 rounded-lg bg-amber-500 text-white text-sm hover:bg-amber-600 disabled:opacity-50 transition-colors flex items-center justify-center gap-1.5"
>
<Wand2 className="w-3.5 h-3.5" /> 进入涂抹模式
</button>
)}
</div>
<div>
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">换脸</div>
<button
onClick={() => faceInputRef.current && faceInputRef.current.click()}
disabled={!!aiBusy}
className="w-full py-2 rounded-lg bg-purple-600 text-white text-sm hover:bg-purple-700 disabled:opacity-50 transition-colors"
>
选择人脸照片换脸
</button>
<input ref={faceInputRef} type="file" accept="image/*" className="hidden" onChange={runFaceSwap} />
<p className="text-[11px] text-gray-400 mt-1">源=所选人脸照片,目标=当前图片(替换最大人脸)</p>
</div>
<p className="text-[11px] text-gray-400 leading-relaxed">
AI 操作只作用于底图,已添加的文字/贴图会保留在上层。
</p>
</div>
)}
</div>
</div>
</div>
</div>
);
}
export default ImageEditor;