forked from lightningpixel/modly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneratePage.tsx
More file actions
1133 lines (1065 loc) · 46.9 KB
/
Copy pathGeneratePage.tsx
File metadata and controls
1133 lines (1065 loc) · 46.9 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 { useState, useRef, useCallback, useEffect, useMemo } from 'react'
import type { ReactNode } from 'react'
import { useAppStore, DEFAULT_LIGHT_SETTINGS } from '@shared/stores/appStore'
import type { GenerationJob, LightSettings } from '@shared/stores/appStore'
import { useApi } from '@shared/hooks/useApi'
import { ColorPicker } from '@shared/components/ui'
import GenerationHUD from './components/GenerationHUD'
import Viewer3D from './components/Viewer3D'
import WorkflowPanel from './components/WorkflowPanel'
import { getDefaultAssetLibraryService } from './assetLibraryService'
import { resolveAssetLibraryOpenTarget, type ProjectedAssetLibraryEntry } from './assetLibraryProjection'
import {
ASSET_LIBRARY_SORT_OPTIONS,
buildAssetLibraryOpenRequest,
createAssetLibraryOpenJob,
describeAssetLibraryOpenability,
filterAssetLibraryScopeGroups,
getDefaultAssetLibraryCollapsedSectionKeys,
isAssetLibraryEntryOpenable,
resolveOpenPanelAfterLibrarySelection,
toggleAssetLibrarySectionKey,
type AssetLibrarySortMode,
type GenerateOpenPanel,
} from './assetLibraryUi'
const MIN_WIDTH = 220
const MAX_WIDTH = 520
const DEFAULT_WIDTH = 320
// ---------------------------------------------------------------------------
// Export dropdown
// ---------------------------------------------------------------------------
const EXPORT_FORMATS = [
{ fmt: 'glb' as const, desc: 'Binary glTF' },
{ fmt: 'obj' as const, desc: 'Wavefront' },
{ fmt: 'stl' as const, desc: '3D Print' },
{ fmt: 'ply' as const, desc: 'Polygon File' },
]
function ExportDropdown({
onExport,
onClose,
}: {
onExport: (f: 'glb' | 'obj' | 'stl' | 'ply') => void
onClose: () => void
}) {
return (
<div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-1 flex flex-col gap-0.5 min-w-[150px] shadow-xl">
{EXPORT_FORMATS.map(({ fmt, desc }) => (
<button
key={fmt}
onClick={() => { onExport(fmt); onClose() }}
className="px-3 py-2 text-left hover:bg-zinc-800 rounded-lg transition-colors flex items-center gap-2.5"
>
<span className="text-xs font-mono font-semibold text-zinc-200">.{fmt}</span>
<span className="text-[10px] text-zinc-500">{desc}</span>
</button>
))}
</div>
)
}
// ---------------------------------------------------------------------------
// ToolButton — icon-only toolbar button with tooltip + active state
// ---------------------------------------------------------------------------
function ToolButton({
label,
active,
onClick,
children,
}: {
label: string
active: boolean
onClick: () => void
children: ReactNode
}) {
return (
<button
onClick={onClick}
title={label}
aria-label={label}
aria-pressed={active}
className={`flex items-center justify-center w-7 h-7 rounded-lg border transition-colors
${active
? 'bg-zinc-700 border-zinc-600 text-zinc-200'
: 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'
}`}
>
{children}
</button>
)
}
// ---------------------------------------------------------------------------
// Decimate popover
// ---------------------------------------------------------------------------
function DecimatePopover({
currentTriangles,
decimating,
onDecimate,
onClose,
}: {
currentTriangles: number | null
decimating: boolean
onDecimate: (targetFaces: number) => void
onClose: () => void
}) {
const defaultTarget = currentTriangles ? Math.round(currentTriangles * 0.5) : 5000
const [inputValue, setInputValue] = useState(String(defaultTarget))
const parsed = parseInt(inputValue, 10)
const validTarget = !isNaN(parsed) && parsed >= 100 ? parsed : null
const reduction =
currentTriangles && validTarget
? Math.round((1 - Math.min(validTarget, currentTriangles) / currentTriangles) * 100)
: null
return (
<div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 min-w-[200px] shadow-xl">
<p className="text-[10px] text-zinc-500 uppercase tracking-wider">Decimate mesh</p>
{currentTriangles && (
<p className="text-[10px] text-zinc-500">
Current: <span className="text-zinc-300">{currentTriangles.toLocaleString()} tri</span>
</p>
)}
<div className="flex flex-col gap-1.5">
<label className="text-[10px] text-zinc-500">Target faces</label>
<input
type="number"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
min={100}
step={500}
className="bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-1.5 text-xs text-zinc-200 w-full focus:outline-none focus:border-violet-500 transition-colors"
/>
{reduction !== null && (
<p className="text-[10px] text-zinc-500">
Reduction: <span className="text-violet-400">{reduction}%</span>
</p>
)}
</div>
<div className="flex gap-2">
<button
onClick={onClose}
className="flex-1 px-3 py-1.5 text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"
>
Cancel
</button>
<button
onClick={() => validTarget && onDecimate(validTarget)}
disabled={decimating || !validTarget}
className="flex-1 px-3 py-1.5 bg-violet-600 hover:bg-violet-500 disabled:bg-zinc-700 disabled:text-zinc-500 text-white text-xs rounded-lg transition-colors flex items-center justify-center gap-1.5 font-medium"
>
{decimating ? (
<>
<svg className="animate-spin" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Processing…
</>
) : 'Apply'}
</button>
</div>
</div>
)
}
// ---------------------------------------------------------------------------
// Light popover
// ---------------------------------------------------------------------------
function LightPopover({
settings,
onChange,
onClose,
}: {
settings: LightSettings
onChange: (s: LightSettings) => void
onClose: () => void
}) {
function lightRow(
label: string,
colorKey: keyof LightSettings,
intensityKey: keyof LightSettings,
max: number,
) {
const intensity = settings[intensityKey] as number
const color = settings[colorKey] as string
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center gap-2">
<ColorPicker
value={color}
onChange={(c) => onChange({ ...settings, [colorKey]: c })}
/>
<span className="text-[10px] text-zinc-400 flex-1">{label}</span>
<span className="text-[10px] text-zinc-500 font-mono">{intensity.toFixed(1)}</span>
</div>
<input
type="range"
min={0}
max={max}
step={0.1}
value={intensity}
onChange={(e) => onChange({ ...settings, [intensityKey]: parseFloat(e.target.value) })}
className="w-full h-1.5 accent-violet-500 cursor-pointer"
/>
</div>
)
}
function plainRow(label: string, intensityKey: keyof LightSettings, max: number) {
const value = (settings[intensityKey] as number) ?? (DEFAULT_LIGHT_SETTINGS[intensityKey] as number)
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center gap-2">
<span className="text-[10px] text-zinc-400 flex-1">{label}</span>
<span className="text-[10px] text-zinc-500 font-mono">{value.toFixed(2)}</span>
</div>
<input
type="range"
min={0}
max={max}
step={0.05}
value={value}
onChange={(e) => onChange({ ...settings, [intensityKey]: parseFloat(e.target.value) })}
className="w-full h-1.5 accent-violet-500 cursor-pointer"
/>
</div>
)
}
return (
<div className="absolute top-full right-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 min-w-[220px] shadow-xl">
<div className="flex items-center justify-between">
<p className="text-[10px] text-zinc-500 uppercase tracking-wider">Lighting</p>
<button
onClick={() => onChange(DEFAULT_LIGHT_SETTINGS)}
className="text-[10px] text-zinc-600 hover:text-zinc-400 transition-colors"
>
Reset
</button>
</div>
{lightRow('Sun', 'mainColor', 'mainIntensity', 4)}
{lightRow('Fill', 'fillColor', 'fillIntensity', 2)}
{plainRow('Ambient', 'ambientIntensity', 1.5)}
{plainRow('Environment', 'envIntensity', 2)}
<button
onClick={onClose}
className="mt-1 px-3 py-1.5 text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"
>
Close
</button>
</div>
)
}
// ---------------------------------------------------------------------------
// Smooth popover
// ---------------------------------------------------------------------------
function SmoothPopover({
smoothing,
onSmooth,
onClose,
}: {
smoothing: boolean
onSmooth: (iterations: number) => void
onClose: () => void
}) {
const [inputValue, setInputValue] = useState('3')
const parsed = parseInt(inputValue, 10)
const valid = !isNaN(parsed) && parsed >= 1 && parsed <= 20
return (
<div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 min-w-[190px] shadow-xl">
<p className="text-[10px] text-zinc-500 uppercase tracking-wider">Smooth mesh</p>
<div className="flex flex-col gap-1.5">
<label className="text-[10px] text-zinc-500">Iterations <span className="text-zinc-600">(1–20)</span></label>
<input
type="number"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
min={1}
max={20}
step={1}
className="bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-1.5 text-xs text-zinc-200 w-full focus:outline-none focus:border-violet-500 transition-colors"
/>
<p className="text-[10px] text-zinc-600">More iterations = smoother, but loses detail</p>
</div>
<div className="flex gap-2">
<button
onClick={onClose}
className="flex-1 px-3 py-1.5 text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"
>
Cancel
</button>
<button
onClick={() => valid && onSmooth(parsed)}
disabled={smoothing || !valid}
className="flex-1 px-3 py-1.5 bg-violet-600 hover:bg-violet-500 disabled:bg-zinc-700 disabled:text-zinc-500 text-white text-xs rounded-lg transition-colors flex items-center justify-center gap-1.5 font-medium"
>
{smoothing ? (
<>
<svg className="animate-spin" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Processing…
</>
) : 'Apply'}
</button>
</div>
</div>
)
}
// ---------------------------------------------------------------------------
// Workspace library popover
// ---------------------------------------------------------------------------
function AssetLibraryToggleButton({
open,
disabled,
onToggle,
}: {
open: boolean
disabled: boolean
onToggle: () => void
}) {
return (
<button
type="button"
onClick={onToggle}
disabled={disabled}
aria-haspopup="dialog"
aria-expanded={open}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none
${open
? 'bg-zinc-700 border-zinc-600 text-zinc-200'
: 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'
}`}
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden="true">
<path d="M4 6h16" />
<path d="M4 12h16" />
<path d="M4 18h10" />
</svg>
Library
</button>
)
}
function AssetLibraryPopover({
entries,
selectedEntryId,
loading,
opening,
error,
searchQuery,
sortMode,
collapsedSectionKeys,
onSelectEntry,
onSearchQueryChange,
onSortModeChange,
onToggleSection,
onOpenSelected,
onRefresh,
onClose,
}: {
entries: ProjectedAssetLibraryEntry[]
selectedEntryId: string | null
loading: boolean
opening: boolean
error: string | null
searchQuery: string
sortMode: AssetLibrarySortMode
collapsedSectionKeys: string[]
onSelectEntry: (entryId: string) => void
onSearchQueryChange: (value: string) => void
onSortModeChange: (value: AssetLibrarySortMode) => void
onToggleSection: (sectionKey: string) => void
onOpenSelected: () => void
onRefresh: () => void
onClose: () => void
}) {
const scopeGroups = filterAssetLibraryScopeGroups(entries, searchQuery, sortMode)
const visibleEntryIds = new Set(scopeGroups.flatMap((scopeGroup) => scopeGroup.entryGroups.flatMap((group) => group.entries.map((entry) => entry.id))))
const selectedEntry = selectedEntryId && visibleEntryIds.has(selectedEntryId)
? entries.find((entry) => entry.id === selectedEntryId) ?? null
: null
const normalizedSearchQuery = searchQuery.trim()
const openDisabled = !selectedEntry || !isAssetLibraryEntryOpenable(selectedEntry) || loading || opening
const selectedMessage = selectedEntry
? describeAssetLibraryOpenability(selectedEntry)
: scopeGroups.length === 0 && normalizedSearchQuery
? `No workspace assets match “${normalizedSearchQuery}”.`
: 'Select an asset to open it in Generate.'
return (
<div
role="dialog"
aria-label="Workspace library"
className="absolute top-full left-0 mt-1 z-50 w-[320px] max-w-[calc(100vw-2rem)] bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 shadow-xl"
>
<div className="flex items-center justify-between gap-2">
<div>
<p className="text-[10px] text-zinc-500 uppercase tracking-wider">Workspace library</p>
<p className="text-xs text-zinc-300">Select a workspace asset and open the supported source in Generate.</p>
</div>
<button
type="button"
onClick={onClose}
className="px-2 py-1 text-[11px] text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"
>
Close library
</button>
</div>
<button
type="button"
onClick={onRefresh}
disabled={loading || opening}
className="self-start px-2.5 py-1.5 text-[11px] text-zinc-300 bg-zinc-800 hover:bg-zinc-700 disabled:opacity-50 disabled:pointer-events-none rounded-lg transition-colors"
>
Refresh assets
</button>
<div className="flex items-end gap-2">
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
<label htmlFor="asset-library-search" className="text-[11px] text-zinc-300">Search workspace assets</label>
<input
id="asset-library-search"
type="search"
value={searchQuery}
onChange={(event) => onSearchQueryChange(event.target.value)}
placeholder="Search by name, path, scope, or capability"
className="bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-1.5 text-xs text-zinc-200 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
/>
</div>
<div className="flex w-24 shrink-0 flex-col gap-1.5">
<label htmlFor="asset-library-sort" className="text-[11px] text-zinc-300">Sort</label>
<select
id="asset-library-sort"
value={sortMode}
onChange={(event) => onSortModeChange(event.target.value as AssetLibrarySortMode)}
className="bg-zinc-800 border border-zinc-700 rounded-lg px-2 py-1.5 text-xs text-zinc-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
>
{ASSET_LIBRARY_SORT_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
</div>
{loading ? (
<p role="status" className="text-xs text-zinc-400">Loading workspace assets…</p>
) : scopeGroups.length === 0 && !normalizedSearchQuery ? (
<p role="status" className="text-xs text-zinc-500">No workspace assets are indexed yet.</p>
) : scopeGroups.length === 0 ? (
<p role="status" className="text-xs text-zinc-500">{`No workspace assets match “${normalizedSearchQuery}”.`}</p>
) : (
<div role="list" aria-label="Workspace library assets" className="max-h-64 overflow-y-auto rounded-lg border border-zinc-800 bg-zinc-950/40">
{scopeGroups.map((scopeGroup) => {
const scopeExpanded = !collapsedSectionKeys.includes(scopeGroup.sectionKey)
const scopeRegionId = `asset-library-${scopeGroup.sectionKey.replace(/[^a-z0-9-]+/gi, '-')}`
return (
<section key={scopeGroup.sectionKey} role="group" aria-label={`Source scope ${scopeGroup.sourceScopeLabel}`} className="border-b border-zinc-800 last:border-b-0">
<button
type="button"
aria-expanded={scopeExpanded}
aria-controls={scopeRegionId}
onClick={() => onToggleSection(scopeGroup.sectionKey)}
className="flex w-full items-center justify-between gap-2 px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
>
<span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-zinc-300">{scopeGroup.sourceScopeLabel}</span>
<span className="text-[10px] text-zinc-500">{scopeExpanded ? 'Hide' : 'Show'}</span>
</button>
{scopeExpanded && (
<div id={scopeRegionId}>
{scopeGroup.entryGroups.map((group) => {
const capabilityExpanded = !collapsedSectionKeys.includes(group.sectionKey)
const capabilityRegionId = `asset-library-${group.sectionKey.replace(/[^a-z0-9-]+/gi, '-')}`
return (
<section key={group.sectionKey} role="group" aria-label={`Capability category ${group.capabilityLabel}`} className="border-t border-zinc-800 first:border-t-0">
<button
type="button"
aria-expanded={capabilityExpanded}
aria-controls={capabilityRegionId}
onClick={() => onToggleSection(group.sectionKey)}
className="flex w-full items-center justify-between gap-2 px-4 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
>
<span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-zinc-400">{group.capabilityLabel}</span>
<span className="text-[10px] text-zinc-500">{capabilityExpanded ? 'Hide' : 'Show'}</span>
</button>
{capabilityExpanded && (
<div id={capabilityRegionId}>
{group.entries.map((entry) => {
const selected = entry.id === selectedEntryId
return (
<button
key={entry.id}
type="button"
role="listitem"
aria-pressed={selected}
aria-label={`Select library asset ${entry.displayName}`}
onClick={() => onSelectEntry(entry.id)}
className={`w-full text-left px-4 py-2 border-t border-zinc-800 first:border-t-0 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400
${selected ? 'bg-violet-500/10 text-zinc-100' : 'text-zinc-300 hover:bg-zinc-800/80'}`}
>
<div className="flex items-center justify-between gap-2">
<span className="text-xs font-medium">{entry.displayName}</span>
<span className="text-[10px] uppercase tracking-wider text-zinc-500">{entry.capability ?? entry.state.replace(/-/g, ' ')}</span>
</div>
<p className="mt-1 truncate text-[10px] text-zinc-500">{entry.workspacePath}</p>
</button>
)
})}
</div>
)}
</section>
)
})}
</div>
)}
</section>
)
})}
</div>
)}
<div className="rounded-lg border border-zinc-800 bg-zinc-950/40 px-3 py-2">
<p className="text-[11px] text-zinc-400">{selectedMessage}</p>
{error && <p role="alert" className="mt-2 text-[11px] text-amber-300">{error}</p>}
</div>
<button
type="button"
onClick={onOpenSelected}
disabled={openDisabled}
aria-label="Open selected asset"
className="px-3 py-2 bg-violet-600 hover:bg-violet-500 disabled:bg-zinc-700 disabled:text-zinc-500 text-white text-xs rounded-lg transition-colors font-medium"
>
{opening ? 'Opening…' : 'Open selected asset'}
</button>
</div>
)
}
// ---------------------------------------------------------------------------
// GeneratePage
// ---------------------------------------------------------------------------
export default function GeneratePage(): JSX.Element {
const [unloadStatus, setUnloadStatus] = useState<'idle' | 'done'>('idle')
const [panelWidth, setPanelWidth] = useState(DEFAULT_WIDTH)
const [openPanel, setOpenPanel] = useState<GenerateOpenPanel>(null)
const [decimating, setDecimating] = useState(false)
const [smoothing, setSmoothing] = useState(false)
const [importing, setImporting] = useState(false)
const [libraryEntries, setLibraryEntries] = useState<ProjectedAssetLibraryEntry[]>([])
const [librarySelectedEntryId, setLibrarySelectedEntryId] = useState<string | null>(null)
const [libraryLoaded, setLibraryLoaded] = useState(false)
const [libraryLoading, setLibraryLoading] = useState(false)
const [libraryOpening, setLibraryOpening] = useState(false)
const [libraryError, setLibraryError] = useState<string | null>(null)
const [librarySearchQuery, setLibrarySearchQuery] = useState('')
const [librarySortMode, setLibrarySortMode] = useState<AssetLibrarySortMode>('type')
const [libraryCollapsedSectionKeys, setLibraryCollapsedSectionKeys] = useState<string[]>(() => getDefaultAssetLibraryCollapsedSectionKeys())
const [gizmoMode, setGizmoMode] = useState<'translate' | 'rotate' | 'scale' | null>(null)
const dragging = useRef(false)
// Populated by Viewer3D — undoes the latest live gizmo transform, if any.
const gizmoUndoRef = useRef<(() => boolean) | null>(null)
const lightSettings = useAppStore((s) => s.lightSettings)
const setLightSettings = useAppStore((s) => s.setLightSettings)
const isGenerating = useAppStore((s) =>
s.currentJob?.status === 'uploading' || s.currentJob?.status === 'generating'
)
const currentJob = useAppStore((s) => s.currentJob)
const apiUrl = useAppStore((s) => s.apiUrl)
const showError = useAppStore((s) => s.showError)
const updateCurrentJob = useAppStore((s) => s.updateCurrentJob)
const setCurrentJob = useAppStore((s) => s.setCurrentJob)
const meshStats = useAppStore((s) => s.meshStats)
const meshSelected = useAppStore((s) => s.meshSelected)
const pushMeshUrl = useAppStore((s) => s.pushMeshUrl)
const undoMesh = useAppStore((s) => s.undoMesh)
const redoMesh = useAppStore((s) => s.redoMesh)
const canUndo = useAppStore((s) => s.historyIndex > 0)
const canRedo = useAppStore((s) => s.historyIndex < s.meshHistory.length - 1)
const { optimizeMesh, smoothMesh, importMesh } = useApi()
const assetLibraryService = useMemo(() => getDefaultAssetLibraryService(), [])
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (!e.ctrlKey && !e.metaKey) return
if (e.key === 'z') { e.preventDefault(); if (gizmoUndoRef.current?.()) return; undoMesh() }
if (e.key === 'y') { e.preventDefault(); redoMesh() }
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [undoMesh, redoMesh])
const hasModel = currentJob?.status === 'done' && !!currentJob.outputUrl
// Drop the active transform tool when the mesh is deselected, so it doesn't
// silently re-activate on the next selection.
useEffect(() => {
if (!meshSelected) setGizmoMode(null)
}, [meshSelected])
// Gizmo hotkeys: W move, R rotate, S scale, Esc exits. Ignored while typing.
useEffect(() => {
const handler = (e: KeyboardEvent) => {
const el = document.activeElement as HTMLElement | null
if (el && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el.isContentEditable)) return
if (e.key === 'Escape') { setGizmoMode((m) => (m ? null : m)); return }
if (!hasModel || !meshSelected) return
const k = e.key.toLowerCase()
if (k === 'w') setGizmoMode('translate')
else if (k === 'r') setGizmoMode('rotate')
else if (k === 's') setGizmoMode('scale')
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [hasModel, meshSelected])
useEffect(() => {
if (openPanel !== 'library' || libraryLoaded || libraryLoading) return
void loadLibraryEntries()
// eslint-disable-next-line react-hooks/exhaustive-deps -- lazy-load guarded by loaded/loading flags
}, [openPanel, libraryLoaded, libraryLoading])
async function handleUnloadAll() {
await window.electron.model.unloadAll()
setUnloadStatus('done')
setTimeout(() => setUnloadStatus('idle'), 2000)
}
function handleExport(format: 'glb' | 'obj' | 'stl' | 'ply') {
if (!currentJob?.outputUrl) return
const stem = `modly-${Date.now()}`
const link = document.createElement('a')
if (format === 'glb') {
link.href = `${apiUrl}${currentJob.outputUrl}`
} else {
const path = encodeURIComponent(currentJob.outputUrl.replace('/workspace/', ''))
link.href = `${apiUrl}/optimize/export?path=${path}&format=${format}`
}
link.download = `${stem}.${format}`
link.click()
}
function getOptimizePath(url: string): string {
if (url.startsWith('/workspace/')) {
return url.slice('/workspace/'.length)
}
if (url.startsWith('/optimize/serve-file?path=')) {
return decodeURIComponent(url.split('path=')[1] ?? '')
}
return url
}
async function handleImportMesh() {
const filePath = await window.electron.fs.selectMeshFile()
if (!filePath) return
setOpenPanel(null)
setImporting(true)
try {
const { url } = await importMesh(filePath)
const job: GenerationJob = {
id: `import-${Date.now()}`,
imageFile: '',
status: 'done',
progress: 100,
outputUrl: url,
originalOutputUrl: url,
createdAt: Date.now(),
}
setCurrentJob(job)
pushMeshUrl(url)
} finally {
setImporting(false)
}
}
async function loadLibraryEntries() {
setLibraryLoading(true)
setLibraryError(null)
try {
const result = await assetLibraryService.list()
if (!result.success) {
setLibraryLoaded(false)
setLibraryEntries([])
setLibrarySelectedEntryId(null)
setLibraryError(result.error.message)
return
}
setLibraryEntries(result.entries)
setLibrarySelectedEntryId((current) => current && result.entries.some((entry) => entry.id === current)
? current
: result.entries.find(isAssetLibraryEntryOpenable)?.id ?? result.entries[0]?.id ?? null)
setLibraryLoaded(true)
} catch (err) {
setLibraryLoaded(false)
setLibraryEntries([])
setLibrarySelectedEntryId(null)
setLibraryError(err instanceof Error ? err.message : String(err))
} finally {
setLibraryLoading(false)
}
}
async function handleOpenSelectedLibraryEntry() {
const selectedEntry = libraryEntries.find((entry) => entry.id === librarySelectedEntryId) ?? null
if (!selectedEntry) {
setLibraryError('Select an asset before opening it in Generate.')
return
}
if (!isAssetLibraryEntryOpenable(selectedEntry)) {
setLibraryError(describeAssetLibraryOpenability(selectedEntry))
return
}
setLibraryOpening(true)
setLibraryError(null)
try {
const result = await assetLibraryService.open(buildAssetLibraryOpenRequest(selectedEntry))
if (!result.success) {
setLibraryError(result.error.message)
return
}
const target = resolveAssetLibraryOpenTarget(result.entry)
const selection = createAssetLibraryOpenJob(result.entry, target)
if (!selection) {
setLibraryError(describeAssetLibraryOpenability(result.entry))
return
}
setLibraryEntries((currentEntries) => currentEntries.map((entry) => entry.id === result.entry.id ? result.entry : entry))
setLibrarySelectedEntryId(result.entry.id)
setCurrentJob(selection.job)
pushMeshUrl(selection.historyUrl)
setOpenPanel((currentPanel) => resolveOpenPanelAfterLibrarySelection(currentPanel))
} catch (err) {
setLibraryError(err instanceof Error ? err.message : String(err))
} finally {
setLibraryOpening(false)
}
}
async function handleSmooth(iterations: number) {
if (!currentJob?.outputUrl) return
setSmoothing(true)
try {
const path = getOptimizePath(currentJob.outputUrl)
const { url } = await smoothMesh(path, iterations)
updateCurrentJob({ outputUrl: url })
pushMeshUrl(url)
setOpenPanel(null)
} catch (err) {
showError(err instanceof Error ? err.message : String(err))
} finally {
setSmoothing(false)
}
}
async function handleDecimate(targetFaces: number) {
if (!currentJob?.outputUrl) return
setDecimating(true)
try {
const path = getOptimizePath(currentJob.outputUrl)
const { url } = await optimizeMesh(path, targetFaces)
updateCurrentJob({ outputUrl: url })
pushMeshUrl(url)
setOpenPanel(null)
} catch (err) {
showError(err instanceof Error ? err.message : String(err))
} finally {
setDecimating(false)
}
}
const onMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault()
dragging.current = true
const onMouseMove = (ev: MouseEvent) => {
if (!dragging.current) return
setPanelWidth((w) => Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, w + ev.movementX)))
}
const onMouseUp = () => {
dragging.current = false
window.removeEventListener('mousemove', onMouseMove)
window.removeEventListener('mouseup', onMouseUp)
}
window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', onMouseUp)
}, [])
return (
<>
<div className="flex flex-col border-r border-zinc-800 bg-surface-400 overflow-hidden shrink-0" style={{ width: panelWidth }}>
<WorkflowPanel />
</div>
{/* Resize handle */}
<div
onMouseDown={onMouseDown}
className="w-1 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"
/>
<div className="flex-1 flex flex-col overflow-hidden">
{/* Header bar */}
<div className="flex items-center gap-2 px-3 py-2 border-b border-zinc-800 bg-surface-400 shrink-0">
{/* Free memory */}
<button
onClick={handleUnloadAll}
disabled={isGenerating}
title="Free model from memory"
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600 transition-colors disabled:opacity-30 disabled:pointer-events-none"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
</svg>
{unloadStatus === 'done' ? 'Freed' : 'Free memory'}
</button>
<div className="w-px h-4 bg-zinc-700/60" />
{/* Undo / Redo */}
<button
onClick={undoMesh}
disabled={!canUndo}
title="Undo (Ctrl+Z)"
className="flex items-center justify-center w-7 h-7 rounded-lg text-[11px] font-medium bg-zinc-800 border border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600 transition-colors disabled:opacity-30 disabled:pointer-events-none"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
<path d="M3 7v6h6" />
<path d="M3 13a9 9 0 1 0 2.28-5.93" />
</svg>
</button>
<button
onClick={redoMesh}
disabled={!canRedo}
title="Redo (Ctrl+Y)"
className="flex items-center justify-center w-7 h-7 rounded-lg text-[11px] font-medium bg-zinc-800 border border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600 transition-colors disabled:opacity-30 disabled:pointer-events-none"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
<path d="M21 7v6h-6" />
<path d="M21 13a9 9 0 1 1-2.28-5.93" />
</svg>
</button>
<div className="w-px h-4 bg-zinc-700/60" />
{/* Import */}
<div className="relative">
<button
onClick={() => setOpenPanel((p) => (p === 'import' ? null : 'import'))}
disabled={importing}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none
${openPanel === 'import'
? 'bg-zinc-700 border-zinc-600 text-zinc-200'
: 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'
}`}
>
{importing ? (
<svg className="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
) : (
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="7 10 12 15 17 10" />
<line x1="12" y1="15" x2="12" y2="3" />
</svg>
)}
{importing ? 'Importing…' : 'Import'}
{!importing && (
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<polyline points="6 9 12 15 18 9" />
</svg>
)}
</button>
{openPanel === 'import' && (
<div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-1 flex flex-col gap-0.5 min-w-[140px] shadow-xl">
<button
onClick={handleImportMesh}
className="px-3 py-2 text-left hover:bg-zinc-800 rounded-lg transition-colors flex items-center gap-2.5"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" className="text-zinc-400">
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
</svg>
<div>
<p className="text-xs text-zinc-200">Mesh</p>
<p className="text-[10px] text-zinc-500">.glb .obj .stl .ply .splat</p>
</div>
</button>
</div>
)}
</div>
<div className="relative">
<AssetLibraryToggleButton
open={openPanel === 'library'}
disabled={importing || libraryOpening}
onToggle={() => {
setLibraryError(null)
setOpenPanel((panel) => (panel === 'library' ? null : 'library'))
}}
/>
{openPanel === 'library' && (
<AssetLibraryPopover
entries={libraryEntries}
selectedEntryId={librarySelectedEntryId}
loading={libraryLoading}
opening={libraryOpening}
error={libraryError}
searchQuery={librarySearchQuery}
sortMode={librarySortMode}
collapsedSectionKeys={libraryCollapsedSectionKeys}
onSelectEntry={(entryId) => {
setLibraryError(null)
setLibrarySelectedEntryId(entryId)
}}
onSearchQueryChange={setLibrarySearchQuery}
onSortModeChange={setLibrarySortMode}
onToggleSection={(sectionKey) => setLibraryCollapsedSectionKeys((current) => toggleAssetLibrarySectionKey(current, sectionKey))}
onOpenSelected={() => { void handleOpenSelectedLibraryEntry() }}
onRefresh={() => { void loadLibraryEntries() }}
onClose={() => setOpenPanel(null)}
/>
)}
</div>
{hasModel && (
<>
<div className="w-px h-4 bg-zinc-700/60" />
{/* Export */}
<div className="relative">
<button
onClick={() => setOpenPanel((p) => (p === 'export' ? null : 'export'))}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors
${openPanel === 'export'
? 'bg-zinc-700 border-zinc-600 text-zinc-200'
: 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'
}`}
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="7 10 12 5 17 10" />
<line x1="12" y1="5" x2="12" y2="15" />
</svg>
Export
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
{openPanel === 'export' && (
<ExportDropdown
onExport={handleExport as (f: 'glb' | 'obj' | 'stl' | 'ply') => void}
onClose={() => setOpenPanel(null)}
/>
)}
</div>
{/* Smooth */}
<div className="relative">
<button
onClick={() => setOpenPanel((p) => (p === 'smooth' ? null : 'smooth'))}
disabled={smoothing}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none
${openPanel === 'smooth' || smoothing
? 'bg-zinc-700 border-zinc-600 text-zinc-200'
: 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'
}`}
>
{smoothing ? (
<svg className="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
) : (
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z" />
<circle cx="12" cy="12" r="3" />
</svg>
)}
{smoothing ? 'Processing…' : 'Smooth'}
</button>