-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathApp.tsx
More file actions
1566 lines (1413 loc) · 75.7 KB
/
App.tsx
File metadata and controls
1566 lines (1413 loc) · 75.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useRef, useState, useEffect, useCallback, useMemo } from 'react';
import Sidebar from './components/Sidebar';
import { NodeData, Connection, CanvasTransform, Point, DragMode, NodeType } from './types';
import BaseNode from './components/Nodes/BaseNode';
import { NodeContent } from './components/Nodes/NodeContent';
import { Icons } from './components/Icons';
import { generateCreativeDescription, generateImage, generateVideo } from './services/geminiService';
import { storageService } from './services/storageService';
import { ThemeSwitcher } from './components/ThemeSwitcher';
import { SettingsModal } from './components/Settings/SettingsModal';
import { StorageModal } from './components/Settings/StorageModal';
import { ExportImportModal } from './components/Settings/ExportImportModal';
import { WelcomeModal, hasShownWelcome } from './components/Settings/WelcomeModal';
const DEFAULT_NODE_WIDTH = 320;
const DEFAULT_NODE_HEIGHT = 240;
const EMPTY_ARRAY: string[] = [];
// Helper for resizing imported media constraints
const calculateImportDimensions = (naturalWidth: number, naturalHeight: number) => {
const ratio = naturalWidth / naturalHeight;
const maxSide = 750;
let width = naturalWidth;
let height = naturalHeight;
if (width > height) {
if (width > maxSide) {
width = maxSide;
height = width / ratio;
}
} else {
if (height > maxSide) {
height = maxSide;
width = height * ratio;
}
}
return { width, height, ratio };
};
const App: React.FC = () => {
return (
<CanvasWithSidebar />
);
};
const CanvasWithSidebar: React.FC = () => {
const [nodes, setNodes] = useState<NodeData[]>([]);
const [connections, setConnections] = useState<Connection[]>([]);
const [transform, setTransform] = useState<CanvasTransform>({ x: 0, y: 0, k: 1 });
const [selectedNodeIds, setSelectedNodeIds] = useState<Set<string>>(new Set());
const [dragMode, setDragMode] = useState<DragMode | 'RESIZE_NODE' | 'SELECT'>('NONE');
const dragModeRef = useRef(dragMode);
// New Workflow Dialog State
const [showNewWorkflowDialog, setShowNewWorkflowDialog] = useState(false);
// Project Name State
const [projectName, setProjectName] = useState('未命名项目');
const [isEditingProjectName, setIsEditingProjectName] = useState(false);
// Settings Modal State
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [isStorageOpen, setIsStorageOpen] = useState(false);
const [isExportImportOpen, setIsExportImportOpen] = useState(false);
const [isWelcomeOpen, setIsWelcomeOpen] = useState(() => !hasShownWelcome());
const [storageDirName, setStorageDirName] = useState<string | null>(null);
// History State (Persist deleted nodes that have content)
const [deletedNodes, setDeletedNodes] = useState<NodeData[]>([]);
useEffect(() => {
dragModeRef.current = dragMode;
}, [dragMode]);
// 清除 Sora 2 的旧配置(修复 endpoint 问题)
useEffect(() => {
if (typeof window !== 'undefined') {
try {
const sora2Key = `API_CONFIG_MODEL_Sora 2`;
const stored = localStorage.getItem(sora2Key);
if (stored) {
const parsed = JSON.parse(stored);
// 如果 endpoint 是旧的 chat completions,清除配置
if (parsed.endpoint === '/v1/chat/completions') {
localStorage.removeItem(sora2Key);
console.log('[App] Cleared old Sora 2 config with old endpoint');
}
}
} catch(e) {
// 忽略错误
}
}
}, []);
// Default to light theme (white)
const [canvasBg, setCanvasBg] = useState('#F5F7FA');
const isDark = canvasBg === '#0B0C0E';
// Sync body class for CSS variables
useEffect(() => {
if (isDark) {
document.body.classList.add('dark');
} else {
document.body.classList.remove('dark');
}
}, [isDark]);
const [selectionBox, setSelectionBox] = useState<{ x: number, y: number, w: number, h: number } | null>(null);
const [selectedConnectionId, setSelectedConnectionId] = useState<string | null>(null);
const [suggestedNodes, setSuggestedNodes] = useState<NodeData[]>([]);
const [previewMedia, setPreviewMedia] = useState<{ url: string, type: 'image' | 'video' } | null>(null);
// Quick Add Menu State
const [quickAddMenu, setQuickAddMenu] = useState<{ sourceId: string, x: number, y: number, worldX: number, worldY: number } | null>(null);
const [contextMenu, setContextMenu] = useState<{
type: 'CANVAS' | 'NODE',
nodeId?: string,
nodeType?: NodeType,
x: number,
y: number,
worldX: number,
worldY: number
} | null>(null);
const [internalClipboard, setInternalClipboard] = useState<{ nodes: NodeData[], connections: Connection[] } | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const dragStartRef = useRef<{ x: number, y: number, w?: number, h?: number, nodeId?: string }>({ x: 0, y: 0 });
const initialTransformRef = useRef<CanvasTransform>({ x: 0, y: 0, k: 1 });
const initialNodePositionsRef = useRef<{id: string, x: number, y: number}[]>([]);
const connectionStartRef = useRef<{ nodeId: string, type: 'source' | 'target' } | null>(null);
const [tempConnection, setTempConnection] = useState<Point | null>(null);
const lastMousePosRef = useRef<Point>({ x: 0, y: 0 });
const workflowInputRef = useRef<HTMLInputElement>(null);
const assetInputRef = useRef<HTMLInputElement>(null);
const replaceImageRef = useRef<HTMLInputElement>(null);
const nodeToReplaceRef = useRef<string | null>(null);
const spacePressed = useRef(false);
const screenToWorld = (x: number, y: number) => ({
x: (x - transform.x) / transform.k,
y: (y - transform.y) / transform.k,
});
const generateId = () => Math.random().toString(36).substr(2, 9);
// Memoize inputs map to prevent array recreation on every render
const inputsMap = useMemo(() => {
const map: Record<string, string[]> = {};
nodes.forEach(node => {
map[node.id] = connections
.filter(c => c.targetId === node.id)
.map(c => nodes.find(n => n.id === c.sourceId))
.filter(n => n && (n.imageSrc || n.videoSrc))
.map(n => n!.imageSrc || n!.videoSrc || '');
});
return map;
}, [nodes, connections]);
const getInputImages = useCallback((nodeId: string) => {
return inputsMap[nodeId] || EMPTY_ARRAY;
}, [inputsMap]);
const performCopy = () => {
if (selectedNodeIds.size === 0) return;
const selectedNodes = nodes.filter(n => selectedNodeIds.has(n.id));
const selectedConnections = connections.filter(c =>
selectedNodeIds.has(c.sourceId) && selectedNodeIds.has(c.targetId)
);
setInternalClipboard({ nodes: selectedNodes, connections: selectedConnections });
};
const performPaste = (targetPos: Point) => {
if (!internalClipboard || internalClipboard.nodes.length === 0) return;
const { nodes: clipboardNodes, connections: clipboardConnections } = internalClipboard;
let minX = Infinity, minY = Infinity;
clipboardNodes.forEach(n => {
if (n.x < minX) minX = n.x;
if (n.y < minY) minY = n.y;
});
const idMap = new Map<string, string>();
const newNodes: NodeData[] = [];
clipboardNodes.forEach(node => {
const newId = generateId();
idMap.set(node.id, newId);
const offsetX = node.x - minX;
const offsetY = node.y - minY;
newNodes.push({
...node,
id: newId,
x: targetPos.x + offsetX,
y: targetPos.y + offsetY,
title: node.title.endsWith('(Copy)') ? node.title : `${node.title} (Copy)`,
isLoading: false,
});
});
const newConnections: Connection[] = clipboardConnections.map(c => ({
id: generateId(),
sourceId: idMap.get(c.sourceId)!,
targetId: idMap.get(c.targetId)!
}));
setNodes(prev => [...prev, ...newNodes]);
setConnections(prev => [...prev, ...newConnections]);
setSelectedNodeIds(new Set(newNodes.map(n => n.id)));
};
const handleAlign = useCallback((direction: 'UP' | 'DOWN' | 'LEFT' | 'RIGHT') => {
if (selectedNodeIds.size < 2) return;
setNodes(prevNodes => {
const selected = prevNodes.filter(n => selectedNodeIds.has(n.id));
const unselected = prevNodes.filter(n => !selectedNodeIds.has(n.id));
const updatedNodes = selected.map(n => ({ ...n })); // Shallow clone to mutate
const isVerticalAlign = direction === 'UP' || direction === 'DOWN';
// Check overlap logic with Threshold to avoid accidental grouping
const OVERLAP_THRESHOLD = 10;
const isOverlap = (a: NodeData, b: NodeData) => {
if (isVerticalAlign) {
const overlap = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
return overlap > OVERLAP_THRESHOLD;
} else {
const overlap = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
return overlap > OVERLAP_THRESHOLD;
}
};
const clusters: NodeData[][] = [];
const visited = new Set<string>();
for (const node of updatedNodes) {
if (visited.has(node.id)) continue;
const cluster = [node];
visited.add(node.id);
const queue = [node];
while (queue.length > 0) {
const current = queue.shift()!;
for (const other of updatedNodes) {
if (!visited.has(other.id) && isOverlap(current, other)) {
visited.add(other.id);
cluster.push(other);
queue.push(other);
}
}
}
clusters.push(cluster);
}
const minTop = Math.min(...updatedNodes.map(n => n.y));
const maxBottom = Math.max(...updatedNodes.map(n => n.y + n.height));
const minLeft = Math.min(...updatedNodes.map(n => n.x));
const maxRight = Math.max(...updatedNodes.map(n => n.x + n.width));
const HORIZONTAL_GAP = 20;
const VERTICAL_GAP = 60;
clusters.forEach(cluster => {
if (direction === 'UP') {
cluster.sort((a, b) => (a.y - b.y) || a.id.localeCompare(b.id));
let currentY = minTop;
cluster.forEach((node) => {
node.y = currentY;
currentY += node.height + VERTICAL_GAP;
});
} else if (direction === 'DOWN') {
cluster.sort((a, b) => (b.y - a.y) || a.id.localeCompare(b.id));
let currentBottom = maxBottom;
cluster.forEach((node) => {
node.y = currentBottom - node.height;
currentBottom -= (node.height + VERTICAL_GAP);
});
} else if (direction === 'LEFT') {
cluster.sort((a, b) => (a.x - b.x) || a.id.localeCompare(b.id));
let currentX = minLeft;
cluster.forEach((node) => {
node.x = currentX;
currentX += node.width + HORIZONTAL_GAP;
});
} else if (direction === 'RIGHT') {
cluster.sort((a, b) => (b.x - a.x) || a.id.localeCompare(b.id));
let currentRight = maxRight;
cluster.forEach((node) => {
node.x = currentRight - node.width;
currentRight -= (node.width + HORIZONTAL_GAP);
});
}
});
return [...unselected, ...updatedNodes];
});
}, [selectedNodeIds]);
const addNode = (type: NodeType, x?: number, y?: number, dataOverride?: Partial<NodeData>) => {
if (x === undefined || y === undefined) {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect();
const center = screenToWorld(rect.width / 2, rect.height / 2);
x = center.x - DEFAULT_NODE_WIDTH / 2;
y = center.y - DEFAULT_NODE_HEIGHT / 2;
} else {
x = 0; y = 0;
}
}
let w = dataOverride?.width || DEFAULT_NODE_WIDTH;
let h = dataOverride?.height || DEFAULT_NODE_HEIGHT;
if (type === NodeType.ORIGINAL_IMAGE) {
h = dataOverride?.height || 240;
} else if (type === NodeType.TEXT_TO_VIDEO || type === NodeType.IMAGE_TO_VIDEO || type === NodeType.START_END_TO_VIDEO) {
if (!dataOverride?.width) w = 400 * (16/9);
if (!dataOverride?.height) h = 400;
} else if (type === NodeType.TEXT_TO_IMAGE || type === NodeType.IMAGE_TO_IMAGE) {
if (!dataOverride?.width) w = 400;
if (!dataOverride?.height) h = 400;
}
const getDefaultTitle = (t: NodeType) => {
switch (t) {
case NodeType.TEXT_TO_IMAGE: return '生图';
case NodeType.TEXT_TO_VIDEO: return '生视频';
case NodeType.CREATIVE_DESC: return '创意描述';
default: return `原始图片_${Date.now()}`;
}
};
const getDefaultModel = (t: NodeType) => {
switch (t) {
case NodeType.TEXT_TO_IMAGE:
return 'BananaPro';
case NodeType.TEXT_TO_VIDEO:
return 'Sora 2';
default:
return '';
}
};
const isVideoType = type === NodeType.TEXT_TO_VIDEO;
const newNode: NodeData = {
id: generateId(),
type,
x,
y,
width: w,
height: h,
title: dataOverride?.title || getDefaultTitle(type),
aspectRatio: dataOverride?.aspectRatio || (isVideoType ? '16:9' : '1:1'),
model: dataOverride?.model || getDefaultModel(type),
resolution: dataOverride?.resolution || (isVideoType ? '720p' : '1k'),
duration: dataOverride?.duration || (isVideoType ? '5s' : undefined),
count: 1,
prompt: dataOverride?.prompt || '',
imageSrc: dataOverride?.imageSrc,
videoSrc: dataOverride?.videoSrc,
outputArtifacts: dataOverride?.outputArtifacts || (dataOverride?.imageSrc || dataOverride?.videoSrc ? [dataOverride.imageSrc || dataOverride.videoSrc!] : [])
};
setNodes(prev => [...prev, newNode]);
setSelectedNodeIds(new Set([newNode.id]));
};
const handleQuickAddNode = (type: NodeType) => {
if (!quickAddMenu) return;
const newId = generateId();
let w = DEFAULT_NODE_WIDTH;
let h = DEFAULT_NODE_HEIGHT;
const isVideoType = type === NodeType.TEXT_TO_VIDEO;
const isImageGenType = type === NodeType.TEXT_TO_IMAGE;
if (type === NodeType.ORIGINAL_IMAGE) {
h = 240;
} else if (isVideoType) {
w = 400 * (16/9); h = 400;
} else if (isImageGenType) {
w = 400; h = 400;
}
const getDefaultTitle = (t: NodeType) => {
switch (t) {
case NodeType.TEXT_TO_IMAGE: return '生图';
case NodeType.TEXT_TO_VIDEO: return '生视频';
case NodeType.CREATIVE_DESC: return '创意描述';
default: return `原始图片_${Date.now()}`;
}
};
const getDefaultModel = (t: NodeType) => {
switch (t) {
case NodeType.TEXT_TO_IMAGE:
return 'BananaPro';
case NodeType.TEXT_TO_VIDEO:
return 'Sora 2';
default:
return '';
}
};
const newNode: NodeData = {
id: newId,
type,
x: quickAddMenu.worldX,
y: quickAddMenu.worldY - h / 2,
width: w,
height: h,
title: getDefaultTitle(type),
aspectRatio: isVideoType ? '16:9' : '1:1',
model: getDefaultModel(type),
resolution: isVideoType ? '720p' : '1k',
duration: isVideoType ? '5s' : undefined,
count: 1,
prompt: '',
outputArtifacts: []
};
setNodes(prev => [...prev, newNode]);
setConnections(prev => [...prev, { id: generateId(), sourceId: quickAddMenu.sourceId, targetId: newId }]);
setQuickAddMenu(null);
};
const handlePaste = useCallback(async (e: ClipboardEvent) => {
const activeElement = document.activeElement;
const isInputFocused = activeElement instanceof HTMLInputElement || activeElement instanceof HTMLTextAreaElement;
if (isInputFocused) return;
const items = e.clipboardData?.items;
let hasSystemMedia = false;
const mousePos = lastMousePosRef.current;
const worldPos = screenToWorld(mousePos.x, mousePos.y);
if (items) {
for (let i = 0; i < items.length; i++) {
const item = items[i] as DataTransferItem;
if (item.type.indexOf('image') !== -1) {
hasSystemMedia = true;
const file = item.getAsFile();
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const { width, height, ratio } = calculateImportDimensions(img.width, img.height);
const src = event.target?.result as string;
addNode(NodeType.ORIGINAL_IMAGE, worldPos.x, worldPos.y, {
width, height, imageSrc: src, aspectRatio: `${ratio}:1`, outputArtifacts: [src]
});
};
img.src = event.target?.result as string;
};
reader.readAsDataURL(file);
}
} else if (item.type.indexOf('video') !== -1) {
hasSystemMedia = true;
const file = item.getAsFile();
if (file) {
const url = URL.createObjectURL(file);
const video = document.createElement('video');
video.preload = 'metadata';
video.onloadedmetadata = () => {
const { width, height, ratio } = calculateImportDimensions(video.videoWidth, video.videoHeight);
addNode(NodeType.ORIGINAL_IMAGE, worldPos.x, worldPos.y, {
width, height, videoSrc: url, title: file.name, aspectRatio: `${ratio}:1`, outputArtifacts: [url]
});
};
video.src = url;
}
}
}
}
if (!hasSystemMedia && internalClipboard) performPaste(worldPos);
}, [transform, internalClipboard]);
useEffect(() => {
document.addEventListener('paste', handlePaste);
return () => document.removeEventListener('paste', handlePaste);
}, [handlePaste]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
const isInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA';
if (!isInput) {
if (e.key === 'Delete' || e.key === 'Backspace') {
if (selectedNodeIds.size > 0) {
const nodesToDelete = nodes.filter(n => selectedNodeIds.has(n.id));
const withContent = nodesToDelete.filter(n => n.imageSrc || n.videoSrc);
if (withContent.length > 0) {
setDeletedNodes(prev => [...prev, ...withContent]);
}
setNodes(prev => prev.filter(n => !selectedNodeIds.has(n.id)));
setConnections(prev => prev.filter(c => !selectedNodeIds.has(c.sourceId) && !selectedNodeIds.has(c.targetId)));
setSelectedNodeIds(new Set());
}
if (selectedConnectionId) {
setConnections(prev => prev.filter(c => c.id !== selectedConnectionId));
setSelectedConnectionId(null);
}
}
if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
e.preventDefault();
performCopy();
}
if ((e.ctrlKey || e.metaKey) && !e.shiftKey) {
if (e.key === 'ArrowUp') { e.preventDefault(); handleAlign('UP'); }
if (e.key === 'ArrowDown') { e.preventDefault(); handleAlign('DOWN'); }
if (e.key === 'ArrowLeft') { e.preventDefault(); handleAlign('LEFT'); }
if (e.key === 'ArrowRight') { e.preventDefault(); handleAlign('RIGHT'); }
}
}
if (e.key === 'Escape') {
if (previewMedia) setPreviewMedia(null);
if (contextMenu) setContextMenu(null);
if (quickAddMenu) setQuickAddMenu(null);
if (showNewWorkflowDialog) setShowNewWorkflowDialog(false);
if (isSettingsOpen) setIsSettingsOpen(false);
if (isStorageOpen) setIsStorageOpen(false);
if (isExportImportOpen) setIsExportImportOpen(false);
}
if (e.code === 'Space') spacePressed.current = true;
};
const handleKeyUp = (e: KeyboardEvent) => { if (e.code === 'Space') spacePressed.current = false; };
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('keyup', handleKeyUp);
};
}, [selectedNodeIds, selectedConnectionId, previewMedia, contextMenu, nodes, connections, quickAddMenu, showNewWorkflowDialog, isSettingsOpen, isStorageOpen, isExportImportOpen, handleAlign]);
useEffect(() => {
// Load storage directory name for the top-right indicator
const loadStorageInfo = async () => {
const name = await storageService.getDownloadDirectoryName();
setStorageDirName(name);
};
if (isStorageOpen === false) {
// Refresh when modal closes
loadStorageInfo();
}
loadStorageInfo();
const handleGlobalMouseUp = () => {
if (dragModeRef.current !== 'NONE') {
setDragMode('NONE');
setTempConnection(null);
connectionStartRef.current = null;
dragStartRef.current = { x: 0, y: 0 };
setSuggestedNodes([]);
setSelectionBox(null);
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
return () => window.removeEventListener('mouseup', handleGlobalMouseUp);
}, [isStorageOpen]);
const handleOpenStorageSettings = () => {
setIsStorageOpen(true);
};
const handleImportWorkflow = (data: { nodes: NodeData[], connections: Connection[], transform?: CanvasTransform, projectName?: string }) => {
// 保存当前有内容的节点到历史
const withContent = nodes.filter(n => n.imageSrc || n.videoSrc);
if (withContent.length > 0) setDeletedNodes(prev => [...prev, ...withContent]);
setNodes(data.nodes);
setConnections(data.connections);
if (data.transform) setTransform(data.transform);
if (data.projectName) setProjectName(data.projectName);
setSelectedNodeIds(new Set());
};
const updateNodeData = useCallback((id: string, updates: Partial<NodeData>) => {
setNodes(prev => prev.map(n => n.id === id ? { ...n, ...updates } : n));
}, []);
const handleGenerate = async (nodeId: string) => {
const node = nodes.find(n => n.id === nodeId);
if (!node) return;
updateNodeData(nodeId, { isLoading: true });
const inputs = getInputImages(node.id);
// Debug: Log input images for troubleshooting
console.log(`[Generation] Node: ${node.title} (${node.type}), Input Images:`, inputs.length > 0 ? inputs.map(i => i.substring(0, 50) + '...') : 'None');
try {
if (node.type === NodeType.CREATIVE_DESC) {
const res = await generateCreativeDescription(node.prompt || '', node.model === 'TEXT_TO_VIDEO' ? 'VIDEO' : 'IMAGE');
updateNodeData(nodeId, { optimizedPrompt: res, isLoading: false });
} else {
let results: string[] = [];
// Image generation
if (node.type === NodeType.TEXT_TO_IMAGE) {
results = await generateImage(
node.prompt || '', node.aspectRatio, node.model, node.resolution, node.count || 1, inputs, node.promptOptimize
);
}
// Video generation
else if (node.type === NodeType.TEXT_TO_VIDEO) {
results = await generateVideo(
node.prompt || '', inputs, node.aspectRatio, node.model, node.resolution, node.duration, node.count || 1, node.promptOptimize
);
}
// Start-End Frame to Video generation (首尾帧模式)
else if (node.type === NodeType.START_END_TO_VIDEO) {
// 添加 _FL 后缀来标识首尾帧模式
const modelWithFL = (node.model || 'Sora 2') + '_FL';
// 如果设置了 swapFrames,交换首尾帧顺序
const orderedInputs = node.swapFrames && inputs.length >= 2 ? [inputs[1], inputs[0]] : inputs;
results = await generateVideo(
node.prompt || '', orderedInputs, node.aspectRatio, modelWithFL, node.resolution, node.duration, node.count || 1, node.promptOptimize
);
}
if (results.length > 0) {
const currentArtifacts = node.outputArtifacts || [];
if (node.imageSrc && !currentArtifacts.includes(node.imageSrc)) currentArtifacts.push(node.imageSrc);
if (node.videoSrc && !currentArtifacts.includes(node.videoSrc)) currentArtifacts.push(node.videoSrc);
const newArtifacts = [...results, ...currentArtifacts];
const updates: Partial<NodeData> = { isLoading: false, outputArtifacts: newArtifacts };
// Set output based on node type
if (node.type === NodeType.TEXT_TO_IMAGE) {
updates.imageSrc = results[0];
} else if (node.type === NodeType.TEXT_TO_VIDEO || node.type === NodeType.START_END_TO_VIDEO) {
updates.videoSrc = results[0];
}
updateNodeData(nodeId, updates);
} else {
throw new Error("未返回结果");
}
}
} catch (e) {
console.error(e);
alert(`生成失败: ${(e as Error).message}`);
updateNodeData(nodeId, { isLoading: false });
}
};
const handleMaximize = (nodeId: string) => {
const node = nodes.find(n => n.id === nodeId);
if (!node) return;
if (node.videoSrc) setPreviewMedia({ url: node.videoSrc, type: 'video' });
else if (node.imageSrc) setPreviewMedia({ url: node.imageSrc, type: 'image' });
else alert("没有可预览的内容");
};
const handleHistoryPreview = (url: string, type: 'image' | 'video') => setPreviewMedia({ url, type });
const copyImageToClipboard = async (nodeId: string) => {
const node = nodes.find(n => n.id === nodeId);
if (node && node.imageSrc) {
try {
const res = await fetch(node.imageSrc);
const blob = await res.blob();
await navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob as Blob })]);
alert("图片已复制到剪贴板");
} catch (e) { console.error(e); alert("复制图片失败"); }
}
};
const triggerReplaceImage = (nodeId: string) => {
nodeToReplaceRef.current = nodeId;
replaceImageRef.current?.click();
};
const handleReplaceImage = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
const nodeId = nodeToReplaceRef.current;
if (file && nodeId) {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const node = nodes.find(n => n.id === nodeId);
if (node) {
const { width, height, ratio } = calculateImportDimensions(img.width, img.height);
const src = event.target?.result as string;
const currentArtifacts = node.outputArtifacts || [];
const newArtifacts = [src, ...currentArtifacts];
updateNodeData(nodeId, {
imageSrc: src,
width, height,
aspectRatio: `${ratio}:1`,
outputArtifacts: newArtifacts
});
}
};
img.src = event.target?.result as string;
};
reader.readAsDataURL(file);
}
if (replaceImageRef.current) replaceImageRef.current.value = '';
nodeToReplaceRef.current = null;
};
const handleSaveWorkflow = () => {
const workflowData = { nodes, connections, transform, projectName, version: "1.0" };
const blob = new Blob([JSON.stringify(workflowData, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
const safeName = projectName.replace(/[<>:"/\\|?*]/g, '_').trim() || '未命名项目';
link.download = `${safeName}.aistudio-flow`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const handleNewWorkflow = () => setShowNewWorkflowDialog(true);
const handleConfirmNew = (shouldSave: boolean) => {
if (shouldSave) handleSaveWorkflow();
const withContent = nodes.filter(n => n.imageSrc || n.videoSrc);
if (withContent.length > 0) setDeletedNodes(prev => [...prev, ...withContent]);
setNodes([]);
setConnections([]);
setTransform({ x: 0, y: 0, k: 1 });
setProjectName('未命名项目');
setShowNewWorkflowDialog(false);
setSelectedNodeIds(new Set());
setSelectionBox(null);
};
const handleLoadWorkflow = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const data = JSON.parse(event.target?.result as string);
if (data.nodes && data.connections) {
setNodes(data.nodes);
setConnections(data.connections);
if (data.transform) setTransform(data.transform);
if (data.projectName) setProjectName(data.projectName);
}
} catch (err) { console.error(err); alert("Invalid workflow file"); }
};
reader.readAsText(file);
e.target.value = '';
};
const handleDownload = async (nodeId: string) => {
const node = nodes.find(n => n.id === nodeId);
if (!node) return;
const url = node.videoSrc || node.imageSrc;
if (!url) { alert("No content to download."); return; }
const ext = node.videoSrc ? 'mp4' : 'png';
const filename = `${node.title.replace(/\s+/g, '_')}_${Date.now()}.${ext}`;
try {
const response = await fetch(url);
const blob = await response.blob();
// Try storage service first
const saved = await storageService.saveFile(blob, filename);
if (saved) return;
const blobUrl = URL.createObjectURL(blob as Blob);
const link = document.createElement('a');
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl);
} catch (e) {
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.target = "_blank";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
const handleImportAsset = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const rect = containerRef.current?.getBoundingClientRect();
const center = rect ? screenToWorld(rect.width / 2, rect.height / 2) : { x: 0, y: 0 };
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const { width, height, ratio } = calculateImportDimensions(img.width, img.height);
const src = event.target?.result as string;
addNode(NodeType.ORIGINAL_IMAGE, center.x - width/2, center.y - height/2, {
width, height, imageSrc: src, aspectRatio: `${ratio}:1`, outputArtifacts: [src]
});
};
img.src = event.target?.result as string;
};
reader.readAsDataURL(file);
} else if (file.type.startsWith('video/')) {
const url = URL.createObjectURL(file);
const video = document.createElement('video');
video.preload = 'metadata';
video.onloadedmetadata = () => {
const { width, height, ratio } = calculateImportDimensions(video.videoWidth, video.videoHeight);
addNode(NodeType.ORIGINAL_IMAGE, center.x - width/2, center.y - height/2, {
width, height, videoSrc: url, title: file.name, aspectRatio: `${ratio}:1`, outputArtifacts: [url]
});
};
video.src = url;
}
e.target.value = '';
};
const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); };
const handleDrop = (e: React.DragEvent) => {
e.preventDefault(); e.stopPropagation();
const files: File[] = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
const worldPos = screenToWorld(e.clientX, e.clientY);
files.forEach((file, index) => {
const offsetX = index * 20; const offsetY = index * 20;
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (event) => {
const src = event.target?.result as string;
const img = new Image();
img.onload = () => {
const { width, height, ratio } = calculateImportDimensions(img.width, img.height);
addNode(NodeType.ORIGINAL_IMAGE, worldPos.x - width/2 + offsetX, worldPos.y - height/2 + offsetY, {
width, height, imageSrc: src, aspectRatio: `${ratio}:1`, outputArtifacts: [src]
});
};
img.src = src;
};
reader.readAsDataURL(file);
} else if (file.type.startsWith('video/')) {
const url = URL.createObjectURL(file);
const video = document.createElement('video');
video.preload = 'metadata';
video.onloadedmetadata = () => {
const { width, height, ratio } = calculateImportDimensions(video.videoWidth, video.videoHeight);
addNode(NodeType.ORIGINAL_IMAGE, worldPos.x - width/2 + offsetX, worldPos.y - height/2 + offsetY, {
width, height, videoSrc: url, title: file.name, aspectRatio: `${ratio}:1`, outputArtifacts: [url]
});
};
video.src = url;
}
});
};
const handleWheel = (e: React.WheelEvent) => {
if (e.ctrlKey || e.metaKey) e.preventDefault();
const zoomIntensity = 0.1;
const direction = e.deltaY > 0 ? -1 : 1;
let newK = transform.k + direction * zoomIntensity;
newK = Math.min(Math.max(0.4, newK), 2);
const rect = containerRef.current!.getBoundingClientRect();
const worldX = (e.clientX - rect.left - transform.x) / transform.k;
const worldY = (e.clientY - rect.top - transform.y) / transform.k;
setTransform({ x: (e.clientX - rect.left) - worldX * newK, y: (e.clientY - rect.top) - worldY * newK, k: newK });
};
const handleMouseDown = (e: React.MouseEvent) => {
if (contextMenu) setContextMenu(null);
if (quickAddMenu) setQuickAddMenu(null);
if (selectedConnectionId) setSelectedConnectionId(null);
if (e.button === 1 || (e.button === 0 && spacePressed.current)) {
setDragMode('PAN');
dragStartRef.current = { x: e.clientX, y: e.clientY };
initialTransformRef.current = { ...transform };
e.preventDefault(); return;
}
if (e.target === containerRef.current && e.button === 0) {
setDragMode('SELECT');
dragStartRef.current = { x: e.clientX, y: e.clientY };
setSelectionBox({ x: 0, y: 0, w: 0, h: 0 });
if (!e.shiftKey) setSelectedNodeIds(new Set());
}
};
const handleNodeMouseDown = (e: React.MouseEvent, id: string) => {
e.stopPropagation();
if (contextMenu) setContextMenu(null);
if (quickAddMenu) setQuickAddMenu(null);
if (selectedConnectionId) setSelectedConnectionId(null);
if (e.button === 0) {
setDragMode('DRAG_NODE');
dragStartRef.current = { x: e.clientX, y: e.clientY };
const isAlreadySelected = selectedNodeIds.has(id);
let newSelection = new Set(selectedNodeIds);
if (e.shiftKey) { isAlreadySelected ? newSelection.delete(id) : newSelection.add(id); } else { if (!isAlreadySelected) { newSelection.clear(); newSelection.add(id); } }
setSelectedNodeIds(newSelection);
initialNodePositionsRef.current = nodes.map(n => ({ id: n.id, x: n.x, y: n.y }));
}
};
const handleNodeContextMenu = (e: React.MouseEvent, id: string, type: NodeType) => {
e.stopPropagation(); e.preventDefault();
const worldPos = screenToWorld(e.clientX, e.clientY);
setContextMenu({ type: 'NODE', nodeId: id, nodeType: type, x: e.clientX, y: e.clientY, worldX: worldPos.x, worldY: worldPos.y });
if (!selectedNodeIds.has(id)) setSelectedNodeIds(new Set([id]));
};
const handleCanvasContextMenu = (e: React.MouseEvent) => {
e.preventDefault();
const worldPos = screenToWorld(e.clientX, e.clientY);
setContextMenu({ type: 'CANVAS', x: e.clientX, y: e.clientY, worldX: worldPos.x, worldY: worldPos.y });
};
const handleResizeStart = (e: React.MouseEvent, nodeId: string) => {
e.stopPropagation(); e.preventDefault();
const node = nodes.find(n => n.id === nodeId);
if (!node) return;
setDragMode('RESIZE_NODE');
dragStartRef.current = { x: e.clientX, y: e.clientY, w: node.width, h: node.height, nodeId: nodeId };
setSelectedNodeIds(new Set([nodeId]));
};
const handleConnectStart = (e: React.MouseEvent, nodeId: string, type: 'source' | 'target') => {
e.stopPropagation(); e.preventDefault();
connectionStartRef.current = { nodeId, type };
setDragMode('CONNECT');
setTempConnection(screenToWorld(e.clientX, e.clientY));
};
const handleMouseMove = (e: React.MouseEvent) => {
lastMousePosRef.current = { x: e.clientX, y: e.clientY };
const worldPos = screenToWorld(e.clientX, e.clientY);
if (dragMode !== 'NONE' && e.buttons === 0) { setDragMode('NONE'); dragStartRef.current = { x: 0, y: 0 }; return; }
if (dragMode === 'PAN') {
setTransform({ ...initialTransformRef.current, x: initialTransformRef.current.x + (e.clientX - dragStartRef.current.x), y: initialTransformRef.current.y + (e.clientY - dragStartRef.current.y) });
} else if (dragMode === 'DRAG_NODE') {
const dx = (e.clientX - dragStartRef.current.x) / transform.k;
const dy = (e.clientY - dragStartRef.current.y) / transform.k;
setNodes(prev => prev.map(n => { if (selectedNodeIds.has(n.id)) { const initial = initialNodePositionsRef.current.find(init => init.id === n.id); if (initial) return { ...n, x: initial.x + dx, y: initial.y + dy }; } return n; }));
} else if (dragMode === 'SELECT') {
const x = Math.min(dragStartRef.current.x, e.clientX);
const y = Math.min(dragStartRef.current.y, e.clientY);
const w = Math.abs(e.clientX - dragStartRef.current.x);
const h = Math.abs(e.clientY - dragStartRef.current.y);
setSelectionBox({ x: x - containerRef.current!.getBoundingClientRect().left, y: y - containerRef.current!.getBoundingClientRect().top, w, h });
const worldStartX = (x - containerRef.current!.getBoundingClientRect().left - transform.x) / transform.k;
const worldStartY = (y - containerRef.current!.getBoundingClientRect().top - transform.y) / transform.k;
const worldWidth = w / transform.k; const worldHeight = h / transform.k;
const newSelection = new Set<string>();
nodes.forEach(n => { if (n.x < worldStartX + worldWidth && n.x + n.width > worldStartX && n.y < worldStartY + worldHeight && n.y + n.height > worldStartY) newSelection.add(n.id); });
setSelectedNodeIds(newSelection);
} else if (dragMode === 'CONNECT') {
setTempConnection(worldPos);
if (connectionStartRef.current?.type === 'source') {
const candidates = nodes.filter(n => n.id !== connectionStartRef.current?.nodeId).filter(n => n.type !== NodeType.ORIGINAL_IMAGE)
.map(n => ({ node: n, dist: Math.sqrt(Math.pow(worldPos.x - (n.x + n.width/2), 2) + Math.pow(worldPos.y - (n.y + n.height/2), 2)) }))
.filter(item => item.dist < 500).sort((a, b) => a.dist - b.dist).slice(0, 3).map(item => item.node);
setSuggestedNodes(candidates);
}
} else if (dragMode === 'RESIZE_NODE') {
const nodeId = dragStartRef.current.nodeId;
const node = nodes.find(n => n.id === nodeId);
if (node) {
const dx = (e.clientX - dragStartRef.current.x) / transform.k;
let ratio = 1.33;
if (node.aspectRatio) { const [w, h] = node.aspectRatio.split(':').map(Number); if (!isNaN(w) && !isNaN(h) && h !== 0) ratio = w / h; }
else if (node.type === NodeType.ORIGINAL_IMAGE) { ratio = (dragStartRef.current.w || 1) / (dragStartRef.current.h || 1); }
let minWidth = 150;
if (node.type !== NodeType.CREATIVE_DESC) {
const limit1 = ratio >= 1 ? 400 * ratio : 400;
minWidth = Math.max(limit1, 400);
} else minWidth = 280;
let newWidth = Math.max(minWidth, (dragStartRef.current.w || 0) + dx);
setNodes(prev => prev.map(n => n.id === nodeId ? { ...n, width: newWidth, height: newWidth / ratio } : n));
}
}
};
const handleMouseUp = (e: React.MouseEvent) => {
if (dragMode === 'CONNECT' && connectionStartRef.current?.type === 'source') {