forked from lightningpixel/modly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkflowsPage.tsx
More file actions
2200 lines (2016 loc) · 107 KB
/
Copy pathWorkflowsPage.tsx
File metadata and controls
2200 lines (2016 loc) · 107 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import {
ReactFlow,
ReactFlowProvider,
Background,
addEdge,
useNodesState,
useEdgesState,
useReactFlow,
type Connection,
type Node,
type Edge,
type OnConnectStartParams,
} from '@xyflow/react'
import { useWorkflowsStore, NODE_TYPES_WITHOUT_TARGET, NODE_TYPES_WITHOUT_SOURCE, FOLDER_COLORS } from '@shared/stores/workflowsStore'
import { useExtensionsStore } from '@shared/stores/extensionsStore'
import { useAppStore } from '@shared/stores/appStore'
import type { Workflow, WFNode, WFEdge, WFNodeData } from '@shared/types/electron.d'
import { buildAllWorkflowExtensions } from './mockExtensions'
import type { WorkflowExtension } from './mockExtensions'
import { useWorkflowRunStore } from './workflowRunStore'
import { validateWorkflowPreflight } from './preflight'
import ExtensionNode from './nodes/ExtensionNode'
import ImageNode from './nodes/ImageNode'
import TextNode from './nodes/TextNode'
import AddToSceneNode from './nodes/AddToSceneNode'
import Load3DMeshNode from './nodes/Load3DMeshNode'
import PreviewImageNode from './nodes/PreviewImageNode'
import WaitNode from './nodes/WaitNode'
import WhileNode from './nodes/WhileNode'
import ForEachNode from './nodes/ForEachNode'
import WorkflowEdge from './nodes/WorkflowEdge'
// ─── Constants ────────────────────────────────────────────────────────────────
const DRAG_KEY = 'modly/extension-id'
const DRAG_NODE_KEY = 'modly/node-type'
const NODE_TYPES = { extensionNode: ExtensionNode, imageNode: ImageNode, textNode: TextNode, outputNode: AddToSceneNode, meshNode: Load3DMeshNode, previewNode: PreviewImageNode, waitNode: WaitNode, whileNode: WhileNode, forEachNode: ForEachNode }
// Loop-container node types: resizable frames whose children form a loop body.
// (For Each iterators are plain source nodes, not containers.)
const CONTAINER_TYPES = new Set(['whileNode'])
const isContainerType = (type: string | undefined): boolean => !!type && CONTAINER_TYPES.has(type)
const EDGE_TYPES = { workflowEdge: WorkflowEdge }
const DEFAULT_EDGE_OPTS = { type: 'workflowEdge' }
// The While container whose bounds contain a flow-space point, if any. Used to
// auto-parent nodes dropped (or created) inside a While so they join its loop body.
function findWhileContainerAt(nodes: Node[], pos: { x: number; y: number }): Node | undefined {
return nodes.find((n) => {
if (!isContainerType(n.type)) return false
const gw = (n.measured?.width ?? n.width ?? (n.style?.width as number)) || 0
const gh = (n.measured?.height ?? n.height ?? (n.style?.height as number)) || 0
return pos.x >= n.position.x && pos.x <= n.position.x + gw
&& pos.y >= n.position.y && pos.y <= n.position.y + gh
})
}
// ─── IO badge ─────────────────────────────────────────────────────────────────
const IO_STYLES: Record<'image' | 'text' | 'mesh' | 'audio', string> = {
audio: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/25',
image: 'bg-sky-500/15 text-sky-400 border-sky-500/25',
mesh: 'bg-violet-500/15 text-violet-400 border-violet-500/25',
text: 'bg-amber-500/15 text-amber-400 border-amber-500/25',
}
function IoBadge({ type }: { type: 'image' | 'text' | 'mesh' | 'audio' }) {
return (
<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border ${IO_STYLES[type]}`}>
{type}
</span>
)
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function newId(): string { return crypto.randomUUID() }
// Node clipboard (module-level so Ctrl+C in one workflow tab can be pasted in
// another — the canvas remounts per tab but the module survives).
const _nodeClipboard: { current: { nodes: Node[]; edges: Edge[]; pastes: number } | null } = { current: null }
function newWorkflow(): Workflow {
const now = new Date().toISOString()
return { id: newId(), name: 'New Workflow', description: '', nodes: [], edges: [], createdAt: now, updatedAt: now }
}
// ─── Extensions panel ────────────────────────────────────────────────────────
const PANEL_MIN = 240
const PANEL_MAX = 860
const PANEL_BUILTIN_NODES = [
{ type: 'imageNode', label: 'Image', color: '#38bdf8', icon: <><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></> },
{ type: 'textNode', label: 'Text', color: '#fbbf24', icon: <><path d="M17 6.1H3M21 12.1H3M15.1 18H3"/></> },
{ type: 'meshNode', label: 'Load 3D Mesh', color: '#a78bfa', icon: <><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></> },
{ type: 'outputNode', label: 'Add to Scene', color: '#a78bfa', icon: <><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></> },
{ type: 'previewNode', label: 'Preview Views', color: '#38bdf8', icon: <><rect x="3" y="3" width="8" height="8" rx="1"/><rect x="13" y="3" width="8" height="8" rx="1"/><rect x="3" y="13" width="8" height="8" rx="1"/><rect x="13" y="13" width="8" height="8" rx="1"/></> },
{ type: 'waitNode', label: 'Wait', color: '#71717a', icon: <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></> },
{ type: 'whileNode', label: 'While', color: '#f59e0b', icon: <><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></> },
{ type: 'forEachNode', label: 'For Each', color: '#38bdf8', icon: <><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></> },
]
function ExtGroupHeader({ title, author, expanded, onToggle, count }: { title: string; author?: string; expanded: boolean; onToggle: () => void; count: number }) {
return (
<button
onClick={onToggle}
className="flex items-center gap-2 w-full px-1 py-1.5 group"
>
<svg
width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
className="text-zinc-600 group-hover:text-zinc-400 transition-colors shrink-0"
style={{ transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 0.15s ease' }}
>
<polyline points="9 18 15 12 9 6"/>
</svg>
<div className="flex flex-col items-start min-w-0">
<span className="text-[11px] font-semibold text-zinc-400 group-hover:text-zinc-200 transition-colors truncate leading-tight">{title}</span>
{author && <span className="text-[9px] text-zinc-600 truncate leading-tight">{author}</span>}
</div>
<span className="ml-auto text-[9px] text-zinc-700 shrink-0">{count}</span>
</button>
)
}
function ExtensionsPanel({ allExtensions, open }: { allExtensions: WorkflowExtension[]; open: boolean }) {
const [search, setSearch] = useState('')
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
const [width, setWidth] = useState(288)
const dragging = useRef(false)
const startX = useRef(0)
const startW = useRef(0)
useEffect(() => {
const onMove = (e: MouseEvent) => {
if (!dragging.current) return
const delta = startX.current - e.clientX
setWidth(() => Math.min(PANEL_MAX, Math.max(PANEL_MIN, startW.current + delta)))
}
const onUp = () => { dragging.current = false; document.body.style.cursor = '' }
document.addEventListener('mousemove', onMove)
document.addEventListener('mouseup', onUp)
return () => {
document.removeEventListener('mousemove', onMove)
document.removeEventListener('mouseup', onUp)
}
}, [])
const cols = width >= 580 ? 3 : width >= 370 ? 2 : 1
const gridClass = cols === 3 ? 'grid-cols-3' : cols === 2 ? 'grid-cols-2' : 'grid-cols-1'
const query = search.trim().toLowerCase()
const toggleGroup = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }))
const isExpanded = (id: string, hasMatches: boolean) => (query && hasMatches) || !collapsed[id]
// Base group
const filteredBuiltinNodes = PANEL_BUILTIN_NODES.filter((n) => !query || n.label.toLowerCase().includes(query))
const filteredBuiltinExts = allExtensions.filter((e) => e.builtin && (!query || e.name.toLowerCase().includes(query)))
const baseCount = filteredBuiltinNodes.length + filteredBuiltinExts.length
const baseVisible = !query || baseCount > 0
// Non-builtin groups: grouped by extensionId
const nonBuiltinMap = useMemo(() => {
const map = new Map<string, { extensionName: string; nodes: WorkflowExtension[] }>()
for (const ext of allExtensions) {
if (ext.builtin) continue
if (!map.has(ext.extensionId)) map.set(ext.extensionId, { extensionName: ext.extensionName, nodes: [] })
map.get(ext.extensionId)!.nodes.push(ext)
}
return map
}, [allExtensions])
return (
<div
style={{ width: open ? width : 0 }}
className="flex overflow-hidden border-l border-zinc-800 transition-[width] duration-300 ease-in-out shrink-0"
>
<div className="flex shrink-0" style={{ width }}>
{/* Resize handle */}
<div
onMouseDown={(e) => {
dragging.current = true; startX.current = e.clientX; startW.current = width
document.body.style.cursor = 'col-resize'; e.preventDefault()
}}
className="w-1 shrink-0 hover:bg-zinc-600 active:bg-accent/60 cursor-col-resize transition-colors self-stretch"
/>
<div className="flex flex-col flex-1 min-w-0 bg-zinc-950/30">
{/* Header */}
<div className="px-4 py-3 border-b border-zinc-800">
<h2 className="text-xs font-semibold text-zinc-300">Extensions</h2>
<p className="text-[10px] text-zinc-600 mt-0.5">Drag onto canvas</p>
</div>
{/* Search */}
<div className="px-3 pt-2.5 pb-2 border-b border-zinc-800">
<div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-zinc-800/60 border border-zinc-700/60 focus-within:border-zinc-600">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500 shrink-0">
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
</svg>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search…"
className="flex-1 bg-transparent text-[11px] text-zinc-200 placeholder-zinc-600 focus:outline-none min-w-0"
/>
{search && (
<button onClick={() => setSearch('')} className="text-zinc-600 hover:text-zinc-400 transition-colors">
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
)}
</div>
</div>
{/* Groups */}
<div className="flex-1 overflow-y-auto px-3 py-2 flex flex-col gap-0.5">
{/* ── Base group ── */}
{baseVisible && (
<div>
<ExtGroupHeader
title="Base"
expanded={isExpanded('base', baseCount > 0)}
onToggle={() => toggleGroup('base')}
count={baseCount}
/>
{isExpanded('base', baseCount > 0) && (
<div className={`grid ${gridClass} gap-2 mt-1.5 mb-3`}>
{filteredBuiltinNodes.map(({ type, label, color, icon }) => (
<div
key={type}
draggable
onDragStart={(e) => { e.dataTransfer.setData(DRAG_NODE_KEY, type); e.dataTransfer.effectAllowed = 'copy' }}
className="flex flex-col gap-2 px-3 py-3 rounded-lg border border-zinc-800 bg-zinc-900 transition-colors cursor-grab hover:bg-zinc-800/60 hover:border-zinc-700 active:cursor-grabbing"
>
<div className="flex items-center gap-2">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" className="shrink-0">{icon}</svg>
<p className="text-xs font-semibold text-zinc-200 truncate">{label}</p>
</div>
</div>
))}
{filteredBuiltinExts.map((ext) => (
<div
key={ext.id}
draggable
onDragStart={(e) => { e.dataTransfer.setData(DRAG_KEY, ext.id); e.dataTransfer.effectAllowed = 'copy' }}
className="flex flex-col gap-2 px-3 py-3 rounded-lg border border-zinc-800 bg-zinc-900 transition-colors cursor-grab hover:bg-zinc-800/60 hover:border-zinc-700 active:cursor-grabbing"
>
<p className="text-xs font-semibold text-zinc-200 truncate">{ext.name}</p>
<div className="flex items-center gap-1 mt-auto">
<IoBadge type={ext.input} />
<svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 shrink-0">
<path d="M5 12h14M13 6l6 6-6 6"/>
</svg>
<IoBadge type={ext.output} />
</div>
</div>
))}
</div>
)}
</div>
)}
{/* ── Non-builtin extension groups ── */}
{[...nonBuiltinMap.entries()].map(([extId, { extensionName, nodes }]) => {
const filtered = nodes.filter((e) => !query || e.name.toLowerCase().includes(query))
if (query && filtered.length === 0) return null
const displayNodes = query ? filtered : nodes
const expanded = isExpanded(extId, filtered.length > 0)
return (
<div key={extId}>
<ExtGroupHeader
title={extensionName}
author={displayNodes[0]?.extensionAuthor}
expanded={expanded}
onToggle={() => toggleGroup(extId)}
count={displayNodes.length}
/>
{expanded && (
<div className={`grid ${gridClass} gap-2 mt-1.5 mb-3`}>
{displayNodes.map((ext) => (
<div
key={ext.id}
draggable
onDragStart={(e) => { e.dataTransfer.setData(DRAG_KEY, ext.id); e.dataTransfer.effectAllowed = 'copy' }}
className="flex flex-col gap-2 px-3 py-3 rounded-lg border border-zinc-800 bg-zinc-900 transition-colors cursor-grab hover:bg-zinc-800/60 hover:border-zinc-700 active:cursor-grabbing"
>
<p className="text-xs font-semibold text-zinc-200 truncate">{ext.name}</p>
{ext.description && cols === 1 && (
<p className="text-[10px] text-zinc-500 leading-relaxed line-clamp-2">{ext.description}</p>
)}
<div className="flex items-center gap-1 mt-auto">
<IoBadge type={ext.input} />
<svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 shrink-0">
<path d="M5 12h14M13 6l6 6-6 6"/>
</svg>
<IoBadge type={ext.output} />
</div>
</div>
))}
</div>
)}
</div>
)
})}
{/* Empty state */}
{query && baseCount === 0 && [...nonBuiltinMap.values()].every((g) => !g.nodes.some((e) => e.name.toLowerCase().includes(query))) && (
<p className="text-[11px] text-zinc-600 text-center pt-4">No results for "{query}"</p>
)}
</div>
</div>
</div>
</div>
)
}
// ─── Page ─── toggle button icon ─────────────────────────────────────────────
function PanelToggleIcon({ open }: { open: boolean }) {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
style={{ transition: 'transform 0.3s ease', transform: open ? 'rotate(0deg)' : 'rotate(180deg)' }}>
<rect x="3" y="3" width="18" height="18" rx="2"/>
<line x1="15" y1="3" x2="15" y2="21"/>
</svg>
)
}
// ─── Node palette (Space to open) ────────────────────────────────────────────
const BUILTIN_NODES = [
{ type: 'imageNode', label: 'Image', color: '#38bdf8', description: 'Image input' },
{ type: 'textNode', label: 'Text', color: '#fbbf24', description: 'Text input' },
{ type: 'meshNode', label: 'Load 3D Mesh', color: '#a78bfa', description: 'Load a 3D mesh file or use current model' },
{ type: 'outputNode', label: 'Add to Scene', color: '#a78bfa', description: 'Output node — adds the mesh to the 3D scene' },
{ type: 'previewNode', label: 'Preview Views', color: '#38bdf8', description: 'Displays multi-view image outputs in a 2×3 grid' },
{ type: 'waitNode', label: 'Wait', color: '#71717a', description: 'Pauses the workflow until you click Continue' },
{ type: 'whileNode', label: 'While', color: '#f59e0b', description: 'Container: wrap nodes to loop them N times or with Continue/Retry' },
{ type: 'forEachNode', label: 'For Each', color: '#38bdf8', description: 'Iterates a folder (image / text / mesh) alphabetically, one item per run of the downstream nodes' },
]
type PaletteItem =
| { kind: 'node'; data: typeof BUILTIN_NODES[0] }
| { kind: 'ext'; data: WorkflowExtension }
type PaletteGroup = {
id: string
title: string
author?: string
expanded: boolean
items: Array<PaletteItem & { flatIdx: number }>
}
function NodePalette({
allExtensions,
onSelect,
onClose,
}: {
allExtensions: WorkflowExtension[]
onSelect: (type: string, extensionId?: string) => void
onClose: () => void
}) {
const [query, setQuery] = useState('')
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
const [activeIndex, setActiveIndex] = useState(0)
const inputRef = useRef<HTMLInputElement>(null)
const q = query.trim().toLowerCase()
const nonBuiltinMap = useMemo(() => {
const map = new Map<string, { extensionName: string; extensionAuthor: string; nodes: WorkflowExtension[] }>()
for (const ext of allExtensions) {
if (ext.builtin) continue
if (!map.has(ext.extensionId)) map.set(ext.extensionId, { extensionName: ext.extensionName, extensionAuthor: ext.extensionAuthor, nodes: [] })
map.get(ext.extensionId)!.nodes.push(ext)
}
return map
}, [allExtensions])
const toggleGroup = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }))
const isExpanded = (id: string, hasMatches: boolean) => (!!q && hasMatches) || !collapsed[id]
// Build groups with pre-assigned flat indices (drives keyboard nav)
const { groups, totalItems } = useMemo(() => {
const groups: PaletteGroup[] = []
let flatIdx = 0
// Base group
const filteredBuiltinNodes = BUILTIN_NODES.filter((n) => !q || n.label.toLowerCase().includes(q) || n.description.toLowerCase().includes(q))
const filteredBuiltinExts = allExtensions.filter((e) => e.builtin && (!q || e.name.toLowerCase().includes(q) || (e.description ?? '').toLowerCase().includes(q)))
const baseCount = filteredBuiltinNodes.length + filteredBuiltinExts.length
const baseVisible = !q || baseCount > 0
const baseExp = isExpanded('base', baseCount > 0)
if (baseVisible) {
const items: PaletteGroup['items'] = []
if (baseExp) {
filteredBuiltinNodes.forEach((n) => items.push({ kind: 'node', data: n, flatIdx: flatIdx++ }))
filteredBuiltinExts.forEach((e) => items.push({ kind: 'ext', data: e, flatIdx: flatIdx++ }))
}
groups.push({ id: 'base', title: 'Base', expanded: baseExp, items })
}
// Non-builtin groups
for (const [extId, { extensionName, extensionAuthor, nodes }] of nonBuiltinMap) {
const filtered = nodes.filter((e) => !q || e.name.toLowerCase().includes(q) || (e.description ?? '').toLowerCase().includes(q))
if (q && filtered.length === 0) continue
const displayNodes = q ? filtered : nodes
const expanded = isExpanded(extId, filtered.length > 0)
const items: PaletteGroup['items'] = []
if (expanded) displayNodes.forEach((e) => items.push({ kind: 'ext', data: e, flatIdx: flatIdx++ }))
groups.push({ id: extId, title: extensionName, author: extensionAuthor || undefined, expanded, items })
}
return { groups, totalItems: flatIdx }
// eslint-disable-next-line react-hooks/exhaustive-deps -- isExpanded only reads `collapsed`, already a dep
}, [q, allExtensions, nonBuiltinMap, collapsed])
useEffect(() => { setActiveIndex(0) }, [query])
useEffect(() => { inputRef.current?.focus() }, [])
// Flat list for Enter key (derived from groups)
const flatItems = useMemo(() => groups.flatMap((g) => g.items), [groups])
const handleKey = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Escape') { onClose(); return }
if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIndex((i) => Math.min(i + 1, totalItems - 1)); return }
if (e.key === 'ArrowUp') { e.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); return }
if (e.key === 'Enter') {
e.preventDefault()
const item = flatItems[activeIndex]
if (!item) return
if (item.kind === 'node') onSelect(item.data.type)
else onSelect('extensionNode', item.data.id)
}
}, [activeIndex, flatItems, totalItems, onSelect, onClose])
return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh] bg-black/40 backdrop-blur-[2px]" onMouseDown={onClose}>
<div
className="w-full max-w-md bg-zinc-900 border border-zinc-700 rounded-xl shadow-2xl overflow-hidden"
onMouseDown={(e) => e.stopPropagation()}
>
{/* Search input */}
<div className="flex items-center gap-3 px-4 py-3 border-b border-zinc-800">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500 shrink-0">
<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
</svg>
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={handleKey}
placeholder="Search nodes and extensions…"
className="flex-1 bg-transparent text-sm text-zinc-100 placeholder-zinc-600 focus:outline-none"
/>
<kbd className="text-[10px] text-zinc-600 bg-zinc-800 px-1.5 py-0.5 rounded border border-zinc-700">Esc</kbd>
</div>
{/* Groups */}
<div className="max-h-96 overflow-y-auto py-1.5">
{groups.map((group) => (
<div key={group.id}>
{/* Group header */}
<button
onClick={() => toggleGroup(group.id)}
className="flex items-center gap-2 w-full px-4 py-2 group hover:bg-zinc-800/30 transition-colors"
>
<svg
width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
className="text-zinc-600 group-hover:text-zinc-400 transition-colors shrink-0"
style={{ transform: group.expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 0.15s ease' }}
>
<polyline points="9 18 15 12 9 6"/>
</svg>
<div className="flex items-baseline gap-2 min-w-0">
<span className="text-[11px] font-semibold text-zinc-400 group-hover:text-zinc-200 transition-colors">{group.title}</span>
{group.author && <span className="text-[10px] text-zinc-600 truncate">{group.author}</span>}
</div>
<span className="ml-auto text-[10px] text-zinc-700 shrink-0">{group.items.length}</span>
</button>
{/* Group items */}
{group.expanded && group.items.map((item) => {
const isActive = activeIndex === item.flatIdx
if (item.kind === 'node') {
const n = item.data
return (
<button
key={n.type}
onMouseEnter={() => setActiveIndex(item.flatIdx)}
onClick={() => onSelect(n.type)}
className={`w-full flex items-center gap-3 px-4 pl-9 py-2.5 transition-colors ${isActive ? 'bg-zinc-800' : 'hover:bg-zinc-800/50'}`}
>
<span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ background: n.color }} />
<span className="text-sm text-zinc-200">{n.label}</span>
<span className="text-xs text-zinc-600 ml-auto">{n.description}</span>
</button>
)
}
const e = item.data
return (
<button
key={e.id}
onMouseEnter={() => setActiveIndex(item.flatIdx)}
onClick={() => onSelect('extensionNode', e.id)}
className={`w-full flex items-center gap-3 px-4 pl-9 py-2.5 transition-colors ${isActive ? 'bg-zinc-800' : 'hover:bg-zinc-800/50'}`}
>
<span className="w-1.5 h-1.5 rounded-full shrink-0 bg-violet-400" />
<span className="text-sm text-zinc-200">{e.name}</span>
<div className="flex items-center gap-1 ml-auto shrink-0">
<span className="text-[10px] text-zinc-500">{e.input}</span>
<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-700">
<path d="M5 12h14M13 6l6 6-6 6"/>
</svg>
<span className="text-[10px] text-zinc-500">{e.output}</span>
</div>
</button>
)
})}
</div>
))}
{totalItems === 0 && groups.length === 0 && (
<p className="px-4 py-6 text-sm text-zinc-600 text-center">No results for "{query}"</p>
)}
</div>
</div>
</div>
)
}
// ─── Help modal ───────────────────────────────────────────────────────────────
function HelpModal({ onClose }: { onClose: () => void }) {
const [helperImg, setHelperImg] = useState<string | null>(null)
useEffect(() => {
window.electron.fs.readScreenshotDataUrl('workflow-helper.png').then(setHelperImg).catch(() => {})
}, [])
useEffect(() => {
const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape') onClose() }
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
return createPortal(
<div
className="fixed inset-0 z-[9999] flex items-center justify-center bg-zinc-950/70 backdrop-blur-sm"
onMouseDown={onClose}
>
<div
className="w-[520px] max-h-[80vh] rounded-2xl bg-zinc-900 border border-zinc-700/60 shadow-2xl overflow-hidden flex flex-col"
onMouseDown={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="sticky top-0 flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-zinc-900 z-10">
<div className="flex items-center gap-2.5">
<div className="w-7 h-7 rounded-lg bg-accent/10 border border-accent/20 flex items-center justify-center shrink-0">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-accent-light">
<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>
</svg>
</div>
<h2 className="text-sm font-semibold text-zinc-100">How the workflow system works</h2>
</div>
<button onClick={onClose} className="p-1 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
<div className="px-5 py-5 flex flex-col gap-5 overflow-y-auto">
{/* Concept */}
<section className="flex flex-col gap-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Concept</h3>
<p className="text-[12px] text-zinc-300 leading-relaxed">
A workflow is a <span className="text-zinc-100 font-medium">directed graph of nodes</span>. Each node receives data from its inputs (left handle) and produces a result on its output (right handle). Data flows from left to right — you connect nodes by dragging from one handle to another.
</p>
</section>
{/* Example screenshot */}
{helperImg && (
<div className="rounded-xl overflow-hidden border border-zinc-800">
<img src={helperImg} alt="Basic workflow example" className="w-full object-cover" />
<p className="px-3 py-2 text-[10px] text-zinc-500 bg-zinc-800/50 border-t border-zinc-800">
Example — Image → AI model → Add to Scene
</p>
</div>
)}
{/* Node types */}
<section className="flex flex-col gap-2.5">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Node types</h3>
<div className="flex flex-col gap-2">
<div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400 shrink-0 mt-0.5">image</span>
<div>
<p className="text-[11px] font-medium text-zinc-200">Image</p>
<p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Source node. Pick a local image file — it becomes the input of the first processing node.</p>
</div>
</div>
<div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-amber-500/30 bg-amber-500/10 text-amber-400 shrink-0 mt-0.5">text</span>
<div>
<p className="text-[11px] font-medium text-zinc-200">Text</p>
<p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Source node. Pass a text prompt to extensions that accept text input.</p>
</div>
</div>
<div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400 shrink-0 mt-0.5">mesh</span>
<div>
<p className="text-[11px] font-medium text-zinc-200">Load 3D Mesh</p>
<p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Source node. Load a .glb, .obj, .stl, .ply or .splat file from disk, or use the model currently loaded in the 3D viewer.</p>
</div>
</div>
<div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">
<div className="flex gap-1 shrink-0 mt-0.5">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400">image</span>
<span className="text-zinc-600 text-[9px] flex items-center">→</span>
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>
</div>
<div>
<p className="text-[11px] font-medium text-zinc-200">Model extension <span className="text-[10px] font-normal text-zinc-500">(AI generator)</span></p>
<p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Runs a locally installed AI model to convert an image into a 3D mesh. Requires the model weights to be downloaded first from the <span className="text-zinc-300 font-medium">Extensions</span> page.</p>
</div>
</div>
<div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">
<div className="flex gap-1 shrink-0 mt-0.5">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>
<span className="text-zinc-600 text-[9px] flex items-center">→</span>
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>
</div>
<div>
<p className="text-[11px] font-medium text-zinc-200">Process extension <span className="text-[10px] font-normal text-zinc-500">(mesh processor)</span></p>
<p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Transforms a mesh — examples: Optimize Mesh (polygon reduction), Export Mesh (save to file). No GPU required.</p>
</div>
</div>
<div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400 shrink-0 mt-0.5">scene</span>
<div>
<p className="text-[11px] font-medium text-zinc-200">Add to Scene</p>
<p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Terminal node. Receives the final mesh and loads it directly into the 3D viewer when the workflow completes.</p>
</div>
</div>
</div>
</section>
{/* Tips */}
<section className="flex flex-col gap-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Tips</h3>
<ul className="flex flex-col gap-1.5">
{[
['Space', 'Open the node palette on the canvas'],
['Eye icon', 'Pin a node to the Generate page side panel'],
['Drag handle → canvas', 'Auto-opens the palette to connect a new node'],
['Right-click a link', 'Delete the connection between two nodes'],
['Run', 'Saves & executes the workflow, result goes to the 3D scene'],
].map(([key, desc]) => (
<li key={key} className="flex items-start gap-2 text-[11px] text-zinc-400">
<span className="px-1.5 py-px rounded bg-zinc-800 border border-zinc-700 text-zinc-300 font-medium text-[10px] shrink-0 mt-px">{key}</span>
<span>{desc}</span>
</li>
))}
</ul>
</section>
</div>
</div>
</div>,
document.body
)
}
// ─── Connection type helpers ──────────────────────────────────────────────────
function getNodeOutputType(node: Node | undefined, allExts: WorkflowExtension[]): string | undefined {
if (!node) return undefined
if (node.type === 'imageNode') return 'image'
if (node.type === 'meshNode') return 'mesh'
if (node.type === 'textNode') return 'text'
return allExts.find((e) => e.id === (node.data as WFNodeData)?.extensionId)?.output
}
function getNodeInputType(
node: Node | undefined,
targetHandle: string | null | undefined,
allExts: WorkflowExtension[],
): string | undefined {
if (!node) return undefined
if (node.type === 'outputNode') return 'mesh'
if (node.type === 'previewNode') return 'image'
const ext = allExts.find((e) => e.id === (node.data as WFNodeData)?.extensionId)
if (ext?.inputs && ext.inputs.length > 1 && targetHandle) {
const idx = parseInt(targetHandle.replace('input-', ''), 10)
return ext.inputs[isNaN(idx) ? 0 : idx] ?? ext.input
}
return ext?.input
}
// ─── Workflow canvas (inner, requires ReactFlowProvider) ──────────────────────
function WorkflowCanvasInner({
workflow, allExtensions, onSave, panelOpen, onTogglePanel, onOpen, onImport,
}: {
workflow: Workflow
allExtensions: WorkflowExtension[]
onSave: (w: Workflow) => Promise<{ success: boolean; error?: string }>
panelOpen: boolean
onTogglePanel: () => void
onOpen: () => void
onImport: () => void
}) {
const { screenToFlowPosition, getNode } = useReactFlow()
const { runState, run: runWorkflow, cancel } = useWorkflowRunStore()
const currentMeshUrl = useAppStore((s) => s.currentJob?.outputUrl)
const showToast = useAppStore((s) => s.showToast)
const isRunning = runState.status === 'running' || runState.status === 'paused'
const [nodes, setNodes, onNodesChange] = useNodesState(workflow.nodes as Node[])
const [edges, setEdges, onEdgesChange] = useEdgesState(workflow.edges as Edge[])
const [paletteOpen, setPaletteOpen] = useState(false)
const [helpOpen, setHelpOpen] = useState(false)
// Pending connection: set when user drags a handle and releases on empty canvas
const pendingConnectionRef = useRef<OnConnectStartParams | null>(null)
const connectionCompletedRef = useRef(false)
const [pendingDropPos, setPendingDropPos] = useState<{ x: number; y: number } | null>(null)
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
const flushSaveRef = useRef<(() => void) | null>(null)
const autosaveMountedRef = useRef(false)
const preflightToastTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
const didMountRef = useRef(false)
// ─── Undo / Redo ──────────────────────────────────────────────────────────
type Snapshot = { nodes: Node[]; edges: Edge[] }
const historyRef = useRef<Snapshot[]>([{ nodes: workflow.nodes as Node[], edges: workflow.edges as Edge[] }])
const histIdxRef = useRef(0)
const [histIdx, setHistIdx] = useState(0)
const skipPushRef = useRef(true) // skip the initial autosave-triggered push
const lastSavedAtRef = useRef<string>(workflow.updatedAt)
// Re-sync when workflow switches
useEffect(() => {
setNodes(workflow.nodes as Node[])
setEdges(workflow.edges as Edge[])
historyRef.current = [{ nodes: workflow.nodes as Node[], edges: workflow.edges as Edge[] }]
histIdxRef.current = 0
setHistIdx(0)
skipPushRef.current = true
// eslint-disable-next-line react-hooks/exhaustive-deps -- re-sync only when the workflow switches; adding nodes/edges would reset the editor on every change
}, [workflow.id])
// Re-sync when Generate tab (or another external source) saves param changes
useEffect(() => {
if (workflow.updatedAt === lastSavedAtRef.current) return
setNodes(workflow.nodes as Node[])
setEdges(workflow.edges as Edge[])
skipPushRef.current = true
lastSavedAtRef.current = workflow.updatedAt
// eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on updatedAt only; adding nodes/edges would resync on every local edit
}, [workflow.updatedAt])
// Persist and claim the echo so the sync effect above does not treat our own
// write as an external change. The claim is optimistic — the store is updated
// before save() resolves — and is rolled back when the write fails, so a failed
// save never silently replaces the canvas with the last persisted version.
const saveAndClaim = useCallback((updated: Workflow) => {
const prevSavedAt = lastSavedAtRef.current
lastSavedAtRef.current = updated.updatedAt
void onSave(updated).then((res) => {
if (!res.success) lastSavedAtRef.current = prevSavedAt
})
}, [onSave])
// Auto-save + history push debounced.
useEffect(() => {
if (saveTimer.current) clearTimeout(saveTimer.current)
const flush = (pushHistory: boolean) => {
saveTimer.current = null
flushSaveRef.current = null
saveAndClaim({
...workflow,
nodes: nodes as WFNode[],
edges: edges as WFEdge[],
updatedAt: new Date().toISOString(),
})
if (pushHistory && !skipPushRef.current) {
const next = historyRef.current.slice(0, histIdxRef.current + 1)
next.push({ nodes, edges })
if (next.length > 50) next.shift()
historyRef.current = next
const newIdx = next.length - 1
histIdxRef.current = newIdx
setHistIdx(newIdx)
}
skipPushRef.current = false
}
// Only arm the unmount flush once the user has actually edited something,
// so merely opening and leaving the tab does not trigger a pointless write.
if (autosaveMountedRef.current) flushSaveRef.current = () => flush(false)
else autosaveMountedRef.current = true
saveTimer.current = setTimeout(() => flush(true), 500)
// No cleanup: the next edit clears the timer above, and the unmount effect
// below flushes a pending save so switching tabs never drops an edit.
// eslint-disable-next-line react-hooks/exhaustive-deps -- debounce on editable state; latest workflow/onSave read in the timeout
}, [nodes, edges])
// Switching tabs unmounts this page — flush the pending autosave instead of
// dropping it, otherwise an edit made within the debounce window is lost.
useEffect(() => () => {
if (saveTimer.current) clearTimeout(saveTimer.current)
flushSaveRef.current?.()
}, [])
const preflightIssues = useMemo(() => {
const draft: Workflow = {
...workflow,
nodes: nodes as WFNode[],
edges: edges as WFEdge[],
updatedAt: workflow.updatedAt,
}
return validateWorkflowPreflight(draft, allExtensions, { currentMeshUrl })
}, [workflow, nodes, edges, allExtensions, currentMeshUrl])
useEffect(() => {
if (!didMountRef.current) {
didMountRef.current = true
return
}
if (preflightToastTimer.current) clearTimeout(preflightToastTimer.current)
if (preflightIssues.length === 0) return
preflightToastTimer.current = setTimeout(() => {
showToast(preflightIssues[0].message)
}, 250)
return () => {
if (preflightToastTimer.current) clearTimeout(preflightToastTimer.current)
}
}, [preflightIssues, showToast])
const undo = useCallback(() => {
const idx = histIdxRef.current
if (idx <= 0) return
const newIdx = idx - 1
const snap = historyRef.current[newIdx]
skipPushRef.current = true
setNodes(snap.nodes)
setEdges(snap.edges)
histIdxRef.current = newIdx
setHistIdx(newIdx)
}, [setNodes, setEdges])
const redo = useCallback(() => {
const idx = histIdxRef.current
if (idx >= historyRef.current.length - 1) return
const newIdx = idx + 1
const snap = historyRef.current[newIdx]
skipPushRef.current = true
setNodes(snap.nodes)
setEdges(snap.edges)
histIdxRef.current = newIdx
setHistIdx(newIdx)
}, [setNodes, setEdges])
const canUndo = histIdx > 0
const canRedo = histIdx < historyRef.current.length - 1
const isValidConnection = useCallback((connection: Edge | Connection) => {
const srcType = getNodeOutputType(getNode(connection.source) as Node, allExtensions)
const tgtType = getNodeInputType(getNode(connection.target) as Node, connection.targetHandle, allExtensions)
if (srcType && tgtType && srcType !== tgtType) return false // type mismatch (unknown types allowed)
// Reject connections that would create a cycle: if the target can already
// reach the source, adding source→target closes a loop.
if (connection.source && connection.target) {
const stack = [connection.target]
const seen = new Set<string>()
while (stack.length > 0) {
const id = stack.pop()!
if (id === connection.source) return false
if (seen.has(id)) continue
seen.add(id)
for (const e of edges) if (e.source === id) stack.push(e.target)
}
}
return true
}, [getNode, allExtensions, edges])
const onConnectStart = useCallback((_: MouseEvent | TouchEvent, params: OnConnectStartParams) => {
pendingConnectionRef.current = params
connectionCompletedRef.current = false
}, [])
const onConnect = useCallback((params: Connection) => {
connectionCompletedRef.current = true
setEdges((eds) => addEdge({ ...params, ...DEFAULT_EDGE_OPTS }, eds))
}, [setEdges])
const onConnectEnd = useCallback((event: MouseEvent | TouchEvent) => {
if (connectionCompletedRef.current || !pendingConnectionRef.current?.nodeId) {
pendingConnectionRef.current = null
return
}
// Dropped on empty canvas — or inside a While body — opens the palette. The
// While is a giant node, so don't treat its empty body as "dropped on a node";
// bail only on a real node or a handle.
const target = event.target as Element
const nodeEl = target.closest('.react-flow__node')
const onContainer = !!nodeEl && [...CONTAINER_TYPES].some((t) => nodeEl.classList.contains(`react-flow__node-${t}`))
if (target.closest('.react-flow__handle') || (nodeEl && !onContainer)) {
pendingConnectionRef.current = null
return
}
const clientX = 'clientX' in event ? event.clientX : (event as TouchEvent).changedTouches[0].clientX
const clientY = 'clientY' in event ? event.clientY : (event as TouchEvent).changedTouches[0].clientY
setPendingDropPos({ x: clientX, y: clientY })
setPaletteOpen(true)
}, [])
const onDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault(); e.dataTransfer.dropEffect = 'copy'
}, [])
const onDrop = useCallback((e: React.DragEvent) => {
e.preventDefault()
const position = screenToFlowPosition({ x: e.clientX, y: e.clientY })
const nodeType = e.dataTransfer.getData(DRAG_NODE_KEY)
if (nodeType) {
const isContainer = isContainerType(nodeType)
setNodes((nds) => {
const parent = isContainer ? undefined : findWhileContainerAt(nds, position)
const node: Node = {
id: newId(), type: nodeType,
position: parent ? { x: position.x - parent.position.x, y: position.y - parent.position.y } : position,
data: { enabled: true, params: {} } as WFNodeData,
...(isContainer ? { style: { width: 420, height: 240 }, width: 420, height: 240 } : {}),
...(parent ? { parentId: parent.id } : {}),
}
// Containers must sit before their future children in the array → prepend.
return isContainer ? [node, ...nds] : [...nds, node]
})
return
}
const extensionId = e.dataTransfer.getData(DRAG_KEY)
if (!extensionId) return
setNodes((nds) => {
const parent = findWhileContainerAt(nds, position)
const node: Node = {
id: newId(), type: 'extensionNode',
position: parent ? { x: position.x - parent.position.x, y: position.y - parent.position.y } : position,
data: { extensionId, enabled: true, params: {} } as WFNodeData,
...(parent ? { parentId: parent.id } : {}),
}
return [...nds, node]
})
}, [screenToFlowPosition, setNodes])
// Keyboard shortcuts (Space, Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z)
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement).tagName
if (tag === 'INPUT' || tag === 'TEXTAREA') return
if (e.code === 'Space') {
e.preventDefault()
setPaletteOpen(true)
return
}
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key === 'z') {
e.preventDefault()
undo()
return
}
if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.shiftKey && e.key === 'z'))) {