forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewProjectPanel.tsx
More file actions
2943 lines (2822 loc) · 98 KB
/
NewProjectPanel.tsx
File metadata and controls
2943 lines (2822 loc) · 98 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 { useEffect, useId, useMemo, useRef, useState } from 'react';
import { createTabToTracking } from '@open-design/contracts/analytics';
import {
isOpenDesignHostAvailable,
pickAndImportHostProject,
type OpenDesignHostProjectImportSuccess,
} from '@open-design/host';
import { useAnalytics } from '../analytics/provider';
import {
trackDesignSystemApplyResult,
trackNewProjectModalElementClick,
trackNewProjectModalSurfaceView,
trackNewProjectModalTabClick,
} from '../analytics/events';
import type { ConnectorDetail } from '@open-design/contracts';
import type {
TrackingDesignSystemApplyTargetKind,
TrackingDesignSystemOrigin,
TrackingDesignSystemStatusValue,
} from '@open-design/contracts/analytics';
import { useT } from '../i18n';
import type { Dict } from '../i18n/types';
import { fetchPromptTemplate } from '../providers/registry';
import { isStoredMediaProviderEntryPresent } from '../state/config';
import type {
AudioKind,
DesignSystemSummary,
MediaAspect,
ProjectKind,
ProjectMetadata,
ProjectPlatform,
ProjectTemplate,
MediaProviderCredentials,
PromptTemplateSummary,
SkillSummary,
} from '../types';
import {
AUDIO_DURATIONS_SEC,
AUDIO_MODELS_BY_KIND,
DEFAULT_AUDIO_MODEL,
DEFAULT_IMAGE_MODEL,
DEFAULT_VIDEO_MODEL,
findProvider,
IMAGE_MODELS,
MEDIA_ASPECTS,
type MediaModel,
VIDEO_LENGTHS_SEC,
VIDEO_MODELS,
} from '../media/models';
import { formatPickAndImportFailure } from '../utils/pickAndImportError';
import { Icon } from './Icon';
import { Skeleton } from './Loading';
import { Toast } from './Toast';
// Snapshot of a curated prompt template, captured at New Project time and
// folded into ProjectMetadata.promptTemplate. The user may have edited the
// prompt body before clicking Create — that edited copy lives here.
type PromptTemplatePick = {
summary: PromptTemplateSummary;
prompt: string;
};
const SFX_AUDIO_DURATIONS_SEC = AUDIO_DURATIONS_SEC.filter((sec) => sec <= 30);
type TranslateFn = (key: keyof Dict, vars?: Record<string, string | number>) => string;
type NewProjectPlatform = Exclude<ProjectPlatform, 'auto'>;
const DESIGN_PLATFORMS: Array<{
value: NewProjectPlatform;
labelKey: keyof Dict;
hintKey: keyof Dict;
}> = [
{
value: 'responsive',
labelKey: 'newproj.platform.responsive.label',
hintKey: 'newproj.platform.responsive.hint',
},
{
value: 'web-desktop',
labelKey: 'newproj.platform.webDesktop.label',
hintKey: 'newproj.platform.webDesktop.hint',
},
{
value: 'mobile-ios',
labelKey: 'newproj.platform.mobileIos.label',
hintKey: 'newproj.platform.mobileIos.hint',
},
{
value: 'mobile-android',
labelKey: 'newproj.platform.mobileAndroid.label',
hintKey: 'newproj.platform.mobileAndroid.hint',
},
{
value: 'tablet',
labelKey: 'newproj.platform.tablet.label',
hintKey: 'newproj.platform.tablet.hint',
},
{
value: 'desktop-app',
labelKey: 'newproj.platform.desktopApp.label',
hintKey: 'newproj.platform.desktopApp.hint',
},
];
export type CreateTab = 'prototype' | 'live-artifact' | 'deck' | 'template' | 'media' | 'other';
export type MediaSurface = 'image' | 'video' | 'audio';
export interface CreateInput {
name: string;
skillId: string | null;
designSystemId: string | null;
metadata: ProjectMetadata;
}
interface Props {
skills: SkillSummary[];
designSystems: DesignSystemSummary[];
defaultDesignSystemId: string | null;
templates: ProjectTemplate[];
onDeleteTemplate?: (id: string) => Promise<boolean>;
promptTemplates: PromptTemplateSummary[];
onCreate: (input: CreateInput & { requestId?: string }) => void;
onImportClaudeDesign?: (file: File) => Promise<void> | void;
// Web fallback: the user types an absolute baseDir into the manual
// input and the renderer POSTs `/api/import/folder` itself. Browser
// builds have no `shell.openPath` surface, so the renderer naming a
// path here cannot escalate (PR #974 trust model).
onImportFolder?: (baseDir: string) => Promise<void> | void;
// Host flow: the desktop main process owns the picker dialog and
// the import call atomically (`pickAndImport` IPC). The renderer
// never sees the path or the HMAC token; it only receives the
// host-owned project identifiers and forwards them here so App-level
// state can refresh through the daemon API.
onImportFolderResponse?: (response: OpenDesignHostProjectImportSuccess) => Promise<void> | void;
mediaProviders?: Record<string, MediaProviderCredentials>;
connectors?: ConnectorDetail[];
connectorsLoading?: boolean;
onOpenConnectorsTab?: () => void;
loading?: boolean;
initialTab?: CreateTab;
}
const TAB_LABEL_KEYS: Record<CreateTab, keyof Dict> = {
prototype: 'newproj.tabPrototype',
'live-artifact': 'newproj.tabLiveArtifact',
deck: 'newproj.tabDeck',
template: 'newproj.tabTemplate',
media: 'newproj.tabMedia',
other: 'newproj.tabOther',
};
// Maps the New Project tab + media surface to the apply-result target
// kind enum. `media` collapses to image/video/audio inside callers;
// this helper covers the non-media tabs and the live-artifact special
// case. Media surfaces map case-by-case at the call site.
function newProjectTabToApplyKind(
tab: CreateTab,
): TrackingDesignSystemApplyTargetKind {
switch (tab) {
case 'prototype':
return 'prototype';
case 'deck':
return 'slide_deck';
case 'live-artifact':
return 'live_artifact';
case 'media':
// Media tab has its own surface picker; the apply emission
// happens before the user selects image/video/audio, so we
// mark it `unknown` rather than guessing. The picker is also
// typically hidden under media but the helper stays total.
return 'unknown';
case 'template':
case 'other':
return 'unknown';
}
}
// Maps a `DesignSystemSummary.source` value to the DS origin enum used
// by `design_system_apply_result.design_system_source`. The summary
// shape only carries `'built-in' | 'installed' | 'user'`; we map them
// onto the doc's enum: user → manual_create, built-in → official_preset,
// installed → template.
function deriveDesignSystemOrigin(
system: DesignSystemSummary | undefined,
): TrackingDesignSystemOrigin | undefined {
if (!system) return undefined;
switch (system.source) {
case 'user':
return 'manual_create';
case 'built-in':
return 'official_preset';
case 'installed':
return 'template';
default:
return 'unknown';
}
}
function deriveDesignSystemStatusValue(
system: DesignSystemSummary | undefined,
): TrackingDesignSystemStatusValue | undefined {
if (!system) return undefined;
switch (system.status) {
case 'draft':
case 'published':
return system.status;
default:
return 'unknown';
}
}
const MEDIA_SURFACE_LABEL_KEYS: Record<MediaSurface, keyof Dict> = {
image: 'newproj.surfaceImage',
video: 'newproj.surfaceVideo',
audio: 'newproj.surfaceAudio',
};
export function defaultDesignSystemSelection(
defaultDesignSystemId: string | null,
designSystems: DesignSystemSummary[],
): string[] {
if (!defaultDesignSystemId) return [];
return designSystems.some((d) => d.id === defaultDesignSystemId)
? [defaultDesignSystemId]
: [];
}
export function buildDesignSystemCreateSelection(
showDesignSystemPicker: boolean,
selectedIds: string[],
): { primary: string | null; inspirations: string[] } {
return showDesignSystemPicker
? {
primary: selectedIds[0] ?? null,
inspirations: selectedIds.slice(1),
}
: { primary: null, inspirations: [] };
}
export function NewProjectPanel({
skills,
designSystems,
defaultDesignSystemId,
templates,
onDeleteTemplate,
promptTemplates,
onCreate,
onImportClaudeDesign,
onImportFolder,
onImportFolderResponse,
mediaProviders,
connectors,
connectorsLoading = false,
onOpenConnectorsTab,
loading = false,
initialTab = 'prototype',
}: Props) {
const t = useT();
const analytics = useAnalytics();
const importInputRef = useRef<HTMLInputElement | null>(null);
const [importing, setImporting] = useState(false);
const [baseDir, setBaseDir] = useState('');
const [importingFolder, setImportingFolder] = useState(false);
// PR #974 round-4 (mrcfps): pickAndImport now returns structured
// failure shapes (`desktop auth secret not registered`, `web sidecar
// URL not available`, `daemon returned HTTP X`) — surfacing them
// gives the user a recovery hint instead of a silent no-op.
// Shape: `{ message, details? }`. `null` means no toast.
const [importFolderError, setImportFolderError] = useState<
{ message: string; details?: string } | null
>(null);
const [tab, setTab] = useState<CreateTab>(initialTab);
// P0 analytics — fire surface_view once per (panel mount, tab) pair so the
// funnel sees both initial open and tab switches without double-counting on
// unrelated re-renders. Ref keys on a tab string because the panel is a
// long-lived component the modal mounts/unmounts as the user opens/closes it.
const newProjectViewedTabRef = useRef<string | null>(null);
useEffect(() => {
if (newProjectViewedTabRef.current === tab) return;
newProjectViewedTabRef.current = tab;
trackNewProjectModalSurfaceView(analytics.track, {
page_name: 'home',
area: 'new_project_modal',
tab_name: createTabToTracking(tab),
});
}, [tab, analytics.track]);
// Media tab consolidates image / video / audio. The active surface picks
// which set of options + skill resolution applies; submission still maps
// back to the existing image/video/audio ProjectKind branches so the
// backend contract is unchanged.
const [mediaSurface, setMediaSurface] = useState<MediaSurface>('image');
const tabsRef = useRef<HTMLDivElement | null>(null);
const [tabScroll, setTabScroll] = useState({ left: false, right: false });
const [name, setName] = useState('');
// Design-system selection is now an *array* internally so the same
// component can drive both single-select and multi-select modes without
// duplicating state. Single-select coerces to length 0/1.
const initialDefaultDsSelection = useMemo(
() => defaultDesignSystemSelection(defaultDesignSystemId, designSystems),
[defaultDesignSystemId, designSystems],
);
const [selectedDsIds, setSelectedDsIds] = useState<string[]>(
() => initialDefaultDsSelection,
);
const [dsSelectionTouched, setDsSelectionTouched] = useState(false);
const [dsMulti, setDsMulti] = useState(false);
// Per-tab metadata. Tracked independently so switching tabs preserves
// each tab's pick rather than resetting to defaults.
const [fidelity, setFidelity] = useState<'wireframe' | 'high-fidelity'>(
'high-fidelity',
);
const [platformTargets, setPlatformTargets] = useState<NewProjectPlatform[]>(['responsive']);
const [includeLandingPage, setIncludeLandingPage] = useState(false);
const [includeOsWidgets, setIncludeOsWidgets] = useState(false);
const [speakerNotes, setSpeakerNotes] = useState(false);
const [animations, setAnimations] = useState(false);
const [templateId, setTemplateId] = useState<string | null>(null);
const [imageModel, setImageModel] = useState(DEFAULT_IMAGE_MODEL);
const [imageAspect, setImageAspect] = useState<MediaAspect>('1:1');
const [videoModel, setVideoModel] = useState(DEFAULT_VIDEO_MODEL);
const [videoModelTouched, setVideoModelTouched] = useState(false);
const [videoAspect, setVideoAspect] = useState<MediaAspect>('16:9');
const [videoLength, setVideoLength] = useState(5);
const [audioKind, setAudioKind] = useState<AudioKind>('speech');
const [audioModel, setAudioModel] = useState(DEFAULT_AUDIO_MODEL.speech);
const [audioDuration, setAudioDuration] = useState(10);
const [voice, setVoice] = useState('');
// Per-surface curated prompt template the user picked. Tracked
// independently for image vs video so flipping tabs doesn't clobber the
// other one's pick. The body is editable in-line and the edited copy is
// what gets carried to the agent — that's the "optimize the template"
// affordance the design brief asks for.
const [imagePromptTemplate, setImagePromptTemplate] =
useState<PromptTemplatePick | null>(null);
const [videoPromptTemplate, setVideoPromptTemplate] =
useState<PromptTemplatePick | null>(null);
// Design system is meaningful only for the structured/visual surfaces
// (prototype, deck, template, and the freeform "other" canvas). The
// media surfaces use prompt templates instead — design tokens don't map
// onto image/video/audio generations, and the picker just adds noise
// there. Keep this list explicit so future tabs declare their intent.
const tabSupportsDesignSystem =
tab === 'prototype' ||
tab === 'deck' ||
tab === 'template' ||
tab === 'other';
// Orbit briefings ship their own complete visual language baked into
// example.html and explicitly opt out of DESIGN.md injection via
// `od.design_system.requires: false`. Hide the picker only for those
// Orbit scenario skills; the general prototype creation surface should
// still honor the user's configured default design system even when a
// non-Orbit default skill does not require one.
const tabDefaultSkillForcesNoDs = useMemo(() => {
const tabSkillId = ((): string | null => {
if (tab === 'prototype' || tab === 'live-artifact') {
const list = skills.filter((s) => s.mode === 'prototype');
return list.find((s) => s.defaultFor.includes('prototype'))?.id
?? list[0]?.id ?? null;
}
if (tab === 'deck') {
const list = skills.filter((s) => s.mode === 'deck');
return list.find((s) => s.defaultFor.includes('deck'))?.id
?? list[0]?.id ?? null;
}
return null;
})();
if (!tabSkillId) return false;
const s = skills.find((x) => x.id === tabSkillId);
return s
? s.scenario === 'orbit' && s.designSystemRequired === false
: false;
}, [tab, skills]);
const showDesignSystemPicker =
tabSupportsDesignSystem && !tabDefaultSkillForcesNoDs;
useEffect(() => {
if (dsSelectionTouched) return;
setSelectedDsIds(initialDefaultDsSelection);
}, [dsSelectionTouched, initialDefaultDsSelection]);
// Fires `design_system_apply_result` with `auto_select` when the
// picker mounts/refreshes and pre-selects the user's default DS
// without an explicit click. Only emits once per default-id while
// the picker is showing, and only while the user hasn't manually
// changed the selection (so the dashboard separates auto vs manual
// attribution). The picker visibility guard skips media tabs where
// the DS picker isn't rendered.
const autoSelectFiredForRef = useRef<string | null>(null);
useEffect(() => {
if (!showDesignSystemPicker) return;
if (dsSelectionTouched) return;
const primary = initialDefaultDsSelection[0];
if (!primary) return;
if (autoSelectFiredForRef.current === primary) return;
autoSelectFiredForRef.current = primary;
const picked = designSystems.find((d) => d.id === primary);
trackDesignSystemApplyResult(analytics.track, {
page_name: 'home',
area: 'design_system_picker',
action: 'auto_select',
result: 'success',
target_project_kind: newProjectTabToApplyKind(tab),
design_system_id: primary,
design_system_source: deriveDesignSystemOrigin(picked),
design_system_status: deriveDesignSystemStatusValue(picked),
design_system_applied: true,
design_system_selection_mode: 'default',
is_default: true,
is_auto_selected: true,
available_design_system_count: designSystems.length,
duration_ms: 0,
});
}, [
analytics.track,
designSystems,
dsSelectionTouched,
initialDefaultDsSelection,
showDesignSystemPicker,
tab,
]);
// When entering the template tab, snap to the first user-saved template
// if there is one (and we don't already have a valid pick). The template
// tab no longer offers a built-in fallback — the entire point is to
// start from a template *the user* created via Share.
useEffect(() => {
if (tab !== 'template') return;
if (templates.length === 0) {
setTemplateId(null);
return;
}
if (templateId == null || !templates.some((t) => t.id === templateId)) {
setTemplateId(templates[0]!.id);
}
}, [tab, templates, templateId]);
// The skill the request still routes through — kept so prototype/deck
// pick a default-rendered skill (so the agent gets the right SKILL.md
// body) without requiring the user to choose one explicitly.
const skillIdForTab = useMemo(() => {
if (tab === 'other') return null;
if (tab === 'prototype') {
const list = skills.filter((s) => s.mode === 'prototype');
return list.find((s) => s.defaultFor.includes('prototype'))?.id
?? list[0]?.id
?? null;
}
if (tab === 'live-artifact') {
const exact = skills.find((s) => s.id === 'live-artifact' || s.name === 'live-artifact');
if (exact) return exact.id;
const hinted = skills.find((s) => {
const haystack = `${s.id} ${s.name} ${s.description} ${s.triggers.join(' ')}`.toLowerCase();
return haystack.includes('live artifact') || haystack.includes('live-artifact');
});
if (hinted) return hinted.id;
const prototypes = skills.filter((s) => s.mode === 'prototype');
return prototypes.find((s) => s.defaultFor.includes('prototype'))?.id
?? prototypes[0]?.id
?? null;
}
if (tab === 'deck') {
const list = skills.filter((s) => s.mode === 'deck');
return list.find((s) => s.defaultFor.includes('deck'))?.id
?? list[0]?.id
?? null;
}
if (tab === 'media') {
const list = skills.filter(
(s) => s.mode === mediaSurface || s.surface === mediaSurface,
);
// The HyperFrames-HTML render path lives in the `hyperframes` skill.
// When the user has chosen `hyperframes-html` (via dropdown or template),
// pin the project to that skill explicitly.
if (mediaSurface === 'video' && videoModel === 'hyperframes-html') {
const hyper = list.find((s) => s.id === 'hyperframes');
if (hyper) return hyper.id;
}
return list.find((s) => s.defaultFor.includes(mediaSurface))?.id
?? list[0]?.id
?? null;
}
return null;
}, [tab, mediaSurface, skills, videoModel]);
// When the user picks a curated prompt template, propagate the template's
// declared `model` and `aspect` onto the actual project state. Without
// this the user picks (e.g.) a HyperFrames template but `videoModel`
// stays on the default seedance — the agent then dispatches the wrong
// model and the render path mismatches the prompt.
function handleImagePromptTemplate(pick: PromptTemplatePick | null) {
setImagePromptTemplate(pick);
const m = pick?.summary.model;
if (m && IMAGE_MODELS.some((x) => x.id === m)) setImageModel(m);
const a = pick?.summary.aspect;
if (a && (MEDIA_ASPECTS as readonly string[]).includes(a)) {
setImageAspect(a as MediaAspect);
}
}
function handleVideoPromptTemplate(pick: PromptTemplatePick | null) {
setVideoPromptTemplate(pick);
const m = pick?.summary.model;
if (m && VIDEO_MODELS.some((x) => x.id === m)) {
setVideoModel(m);
setVideoModelTouched(true);
}
const a = pick?.summary.aspect;
if (a && (MEDIA_ASPECTS as readonly string[]).includes(a)) {
setVideoAspect(a as MediaAspect);
}
}
function handleVideoModel(id: string) {
setVideoModel(id);
setVideoModelTouched(true);
}
// The HyperFrames skill renders HTML compositions through a local
// `npx hyperframes render` path, which dispatches under the
// `hyperframes-html` model — not seedance/veo/sora. When the resolved
// skill for the video tab is hyperframes, default `videoModel` so the
// model dropdown matches the actual render path. Once the user has
// explicitly chosen a model (via the dropdown or by picking a template
// that declares a model), `videoModelTouched` latches and this effect
// becomes a no-op for the rest of the panel session — re-entering the
// Media tab's Video surface no longer silently rewrites their override back to
// hyperframes-html.
useEffect(() => {
if (tab !== 'media' || mediaSurface !== 'video') return;
if (skillIdForTab !== 'hyperframes') return;
if (videoModelTouched) return;
if (videoPromptTemplate) return;
if (!VIDEO_MODELS.some((m) => m.id === 'hyperframes-html')) return;
setVideoModel('hyperframes-html');
// Intentionally leaving videoPromptTemplate / videoModel out of deps
// so this only fires when the user toggles the tab or the skill
// resolution shifts — not whenever the user changes the dropdown.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tab, mediaSurface, skillIdForTab, videoModelTouched]);
const canCreate =
!loading && (tab !== 'template' || templateId != null);
function updateTabScrollState() {
const el = tabsRef.current;
if (!el) return;
const maxLeft = el.scrollWidth - el.clientWidth;
setTabScroll({
left: el.scrollLeft > 2,
right: el.scrollLeft < maxLeft - 2,
});
}
function scrollTabs(direction: -1 | 1) {
const el = tabsRef.current;
if (!el) return;
el.scrollBy({
left: direction * Math.max(120, el.clientWidth * 0.65),
behavior: 'smooth',
});
}
function handleDesignSystemChange(ids: string[]) {
setDsSelectionTouched(true);
setSelectedDsIds(ids);
const previousPrimary = selectedDsIds[0] ?? null;
const nextPrimary = ids[0] ?? null;
// Only emit when the primary actually changed; secondary reorders
// inside multi-select don't count as a fresh apply.
if (previousPrimary === nextPrimary) return;
const targetKind = newProjectTabToApplyKind(tab);
if (ids.length === 0) {
trackDesignSystemApplyResult(analytics.track, {
page_name: 'home',
area: 'design_system_picker',
action: 'clear_selection',
result: 'success',
target_project_kind: targetKind,
design_system_applied: false,
design_system_selection_mode: 'none',
is_default: false,
is_auto_selected: false,
available_design_system_count: designSystems.length,
duration_ms: 0,
});
return;
}
if (!nextPrimary) return;
const picked = designSystems.find((d) => d.id === nextPrimary);
const isDefault = nextPrimary === defaultDesignSystemId;
trackDesignSystemApplyResult(analytics.track, {
page_name: 'home',
area: 'design_system_picker',
action: 'select_design_system',
result: 'success',
target_project_kind: targetKind,
design_system_id: nextPrimary,
design_system_source: deriveDesignSystemOrigin(picked),
design_system_status: deriveDesignSystemStatusValue(picked),
design_system_applied: true,
design_system_selection_mode: isDefault ? 'default' : 'manual',
is_default: isDefault,
// `is_auto_selected` reports whether this row was picked by the
// app (initial default selection from `initialDefaultDsSelection`)
// rather than by the user. Once `dsSelectionTouched` is set we
// know any subsequent change came from a click.
is_auto_selected: false,
available_design_system_count: designSystems.length,
duration_ms: 0,
});
}
useEffect(() => {
const el = tabsRef.current;
if (!el) return;
updateTabScrollState();
const onScroll = () => updateTabScrollState();
el.addEventListener('scroll', onScroll, { passive: true });
const ro = new ResizeObserver(updateTabScrollState);
ro.observe(el);
return () => {
el.removeEventListener('scroll', onScroll);
ro.disconnect();
};
}, []);
useEffect(() => {
const el = tabsRef.current;
const active = el?.querySelector<HTMLButtonElement>('.newproj-tab.active');
active?.scrollIntoView({ behavior: 'smooth', inline: 'nearest', block: 'nearest' });
window.setTimeout(updateTabScrollState, 180);
}, [tab]);
function handleCreate() {
if (!canCreate) return;
// Media surfaces don't carry a design system pick. Force the primary
// and inspiration ids to empty there so the New Project panel can't
// accidentally bind a stale DS that the user can no longer see in the
// form (the picker is hidden for image/video/audio).
const { primary: primaryDs, inspirations } =
buildDesignSystemCreateSelection(showDesignSystemPicker, selectedDsIds);
const promptTemplatePick =
tab === 'media'
? mediaSurface === 'image'
? imagePromptTemplate
: mediaSurface === 'video'
? videoPromptTemplate
: null
: null;
const trimmedName = name.trim();
const metadata = buildMetadata({
tab,
mediaSurface,
fidelity,
platformTargets,
includeLandingPage,
includeOsWidgets,
speakerNotes,
animations,
templateId,
templates,
imageModel,
imageAspect,
videoModel,
videoAspect,
videoLength,
audioKind,
audioModel,
audioDuration,
voice,
inspirationIds: inspirations,
promptTemplate: promptTemplatePick,
});
// Generate the click→result correlation id here so the home_click and
// the eventual project_create_result share request_id.
const requestId = analytics.newRequestId();
// v2 emits ui_click element=create on the New project modal; the
// project_create_result correlated through `requestId` carries the
// project_kind / fidelity payload, so we no longer duplicate them
// on the click event.
trackNewProjectModalElementClick(
analytics.track,
{
page_name: 'home',
area: 'new_project_modal',
element: 'create',
tab_name: createTabToTracking(tab),
},
{ requestId },
);
onCreate({
name: trimmedName || autoName(tab, mediaSurface, t),
skillId: skillIdForTab,
designSystemId: primaryDs,
metadata: {
...metadata,
nameSource: trimmedName ? 'user' : 'generated',
},
requestId,
});
}
async function handleImportPicked(ev: React.ChangeEvent<HTMLInputElement>) {
const file = ev.target.files?.[0];
ev.target.value = '';
if (!file || !onImportClaudeDesign) return;
setImporting(true);
try {
await onImportClaudeDesign(file);
} finally {
setImporting(false);
}
}
// PR #974: the host bridge does not expose raw folder paths to the
// renderer. The desktop flow uses `pickAndImport`, which performs the
// picker + the HMAC-gated import atomically in the main process and
// returns host-owned project identifiers.
// The web fallback continues to use the manual baseDir input —
// browser builds have no `shell.openPath` surface so a renderer-named
// path cannot escalate.
const hasHostPickAndImport = isOpenDesignHostAvailable();
async function handleOpenFolder() {
if (hasHostPickAndImport) {
if (!onImportFolderResponse) return;
setImportFolderError(null);
setImportingFolder(true);
try {
const result = await pickAndImportHostProject({
skillId: skillIdForTab,
});
if (!result) return;
if (result.ok === true) {
await onImportFolderResponse(result);
return;
}
// Round-4 (mrcfps #2): every non-OK shape used to fall through
// a silent `return`. Reserve silent for the explicit cancel
// case; surface the structured reason for everything else
// (auth-not-registered, web-sidecar-down, daemon HTTP errors,
// network errors). The pickAndImport handler already pre-shapes
// these into a `{ ok: false, reason, details? }` envelope.
if ('canceled' in result && result.canceled === true) return;
setImportFolderError(formatPickAndImportFailure(result));
} finally {
setImportingFolder(false);
}
return;
}
if (!onImportFolder) return;
const trimmed = baseDir.trim();
if (!trimmed) {
setImportFolderError({ message: 'Path cannot be empty' });
return;
}
setImportFolderError(null);
setImportingFolder(true);
try {
await onImportFolder(trimmed);
} catch (err) {
setImportFolderError({
message: err instanceof Error ? err.message : 'Failed to import folder',
});
} finally {
setImportingFolder(false);
}
}
return (
<div className="newproj" data-testid="new-project-panel">
<div className={`newproj-tabs-shell${tabScroll.left ? ' can-left' : ''}${tabScroll.right ? ' can-right' : ''}`}>
<button
type="button"
className={`newproj-tabs-arrow left${tabScroll.left ? '' : ' hidden'}`}
onClick={() => scrollTabs(-1)}
aria-label="Scroll project types left"
tabIndex={tabScroll.left ? 0 : -1}
>
<Icon name="chevron-left" size={16} strokeWidth={2} />
</button>
<div className="newproj-tabs" role="tablist" ref={tabsRef}>
{(Object.keys(TAB_LABEL_KEYS) as CreateTab[]).map((entry) => (
<button
key={entry}
role="tab"
data-testid={`new-project-tab-${entry}`}
aria-selected={tab === entry}
className={`newproj-tab ${tab === entry ? 'active' : ''}`}
onClick={() => {
if (entry !== tab) {
trackNewProjectModalTabClick(analytics.track, {
page_name: 'home',
area: 'new_project_modal',
element: 'tab',
tab_name: createTabToTracking(entry),
});
}
setTab(entry);
}}
>
{t(TAB_LABEL_KEYS[entry])}
</button>
))}
</div>
<button
type="button"
className={`newproj-tabs-arrow right${tabScroll.right ? '' : ' hidden'}`}
onClick={() => scrollTabs(1)}
aria-label="Scroll project types right"
tabIndex={tabScroll.right ? 0 : -1}
>
<Icon name="chevron-right" size={16} strokeWidth={2} />
</button>
</div>
<div className="newproj-body">
<h3 className="newproj-title">
<span className="newproj-title-text">{titleForTab(tab, mediaSurface, t)}</span>
{tab === 'live-artifact' ? (
// "Beta" is an internationally adopted brand-style status marker;
// intentionally not run through t() (consistent with short product
// status pills that read the same across our supported locales).
<span className="newproj-title-badge" aria-label="Beta feature">Beta</span>
) : null}
</h3>
<input
className="newproj-name"
data-testid="new-project-name"
placeholder={t('newproj.namePlaceholder')}
value={name}
onChange={(e) => setName(e.target.value)}
/>
{showDesignSystemPicker ? (
<DesignSystemPicker
designSystems={designSystems}
defaultDesignSystemId={defaultDesignSystemId}
selectedIds={selectedDsIds}
multi={dsMulti}
onChangeMulti={setDsMulti}
onChange={handleDesignSystemChange}
loading={loading}
/>
) : null}
{tab === 'media' ? (
<div
className="newproj-media-segmented"
role="tablist"
aria-label={t('newproj.tabMedia')}
>
{(Object.keys(MEDIA_SURFACE_LABEL_KEYS) as MediaSurface[]).map((surface) => (
<button
key={surface}
type="button"
role="tab"
data-testid={`new-project-media-surface-${surface}`}
aria-selected={mediaSurface === surface}
className={`newproj-media-surface ${mediaSurface === surface ? 'active' : ''}`}
onClick={() => setMediaSurface(surface)}
>
{t(MEDIA_SURFACE_LABEL_KEYS[surface])}
</button>
))}
</div>
) : null}
{tab === 'media' && mediaSurface === 'image' ? (
<PromptTemplatePicker
surface="image"
templates={promptTemplates}
value={imagePromptTemplate}
onChange={handleImagePromptTemplate}
/>
) : null}
{tab === 'media' && mediaSurface === 'video' ? (
<PromptTemplatePicker
surface="video"
templates={promptTemplates}
value={videoPromptTemplate}
onChange={handleVideoPromptTemplate}
/>
) : null}
{tab === 'prototype' || tab === 'live-artifact' || tab === 'template' || tab === 'other' ? (
<PlatformPicker value={platformTargets} onChange={setPlatformTargets} />
) : null}
{tab === 'prototype' || tab === 'live-artifact' || tab === 'template' || tab === 'other' ? (
<SurfaceOptions
includeLandingPage={includeLandingPage}
includeOsWidgets={includeOsWidgets}
onIncludeLandingPage={setIncludeLandingPage}
onIncludeOsWidgets={setIncludeOsWidgets}
/>
) : null}
{/* Live artifact always renders at high fidelity — its whole point
is data-bound polished UI, so the wireframe option is hidden. */}
{tab === 'prototype' ? (
<FidelityPicker value={fidelity} onChange={setFidelity} />
) : null}
{tab === 'live-artifact' ? (
<ConnectorsSection
connectors={connectors}
loading={connectorsLoading}
onOpenConnectorsTab={onOpenConnectorsTab}
/>
) : null}
{tab === 'deck' ? (
<ToggleRow
label={t('newproj.toggleSpeakerNotes')}
hint={t('newproj.toggleSpeakerNotesHint')}
checked={speakerNotes}
onChange={setSpeakerNotes}
/>
) : null}
{tab === 'template' ? (
<>
<TemplatePicker
templates={templates}
value={templateId}
onChange={setTemplateId}
onDelete={onDeleteTemplate}
/>
<ToggleRow
label={t('newproj.toggleAnimations')}
hint={t('newproj.toggleAnimationsHint')}
checked={animations}
onChange={setAnimations}
/>
</>
) : null}
{tab === 'media' && mediaSurface === 'image' ? (
<MediaProjectOptions
surface="image"
imageModel={imageModel}
imageAspect={imageAspect}
mediaProviders={mediaProviders}
onImageModel={setImageModel}
onImageAspect={setImageAspect}
/>
) : null}
{tab === 'media' && mediaSurface === 'video' ? (
<MediaProjectOptions
surface="video"
videoModel={videoModel}
videoAspect={videoAspect}
videoLength={videoLength}
mediaProviders={mediaProviders}
onVideoModel={handleVideoModel}
onVideoAspect={setVideoAspect}
onVideoLength={setVideoLength}
/>
) : null}
{tab === 'media' && mediaSurface === 'audio' ? (
<MediaProjectOptions
surface="audio"
audioKind={audioKind}
audioModel={audioModel}
audioDuration={audioDuration}
voice={voice}
mediaProviders={mediaProviders}
onAudioKind={(kind) => {
setAudioKind(kind);
setAudioModel(DEFAULT_AUDIO_MODEL[kind]);
if (kind === 'sfx') {
setAudioDuration((duration) => Math.min(duration, SFX_AUDIO_DURATIONS_SEC.at(-1) ?? 30));
}
}}
onAudioModel={setAudioModel}
onAudioDuration={setAudioDuration}
onVoice={setVoice}
/>
) : null}
<button
className="primary newproj-create"
data-testid="create-project"
onClick={handleCreate}
disabled={!canCreate}
title={
tab === 'template' && templateId == null
? t('newproj.createDisabledTitle')
: undefined
}
>
<Icon name="plus" size={13} />
<span>
{tab === 'template'