-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathroute.tsx
More file actions
503 lines (455 loc) · 17.6 KB
/
route.tsx
File metadata and controls
503 lines (455 loc) · 17.6 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
import { conform, useForm } from "@conform-to/react";
import { parse } from "@conform-to/zod";
import { CommandLineIcon, FolderIcon } from "@heroicons/react/20/solid";
import { json, type ActionFunction, type LoaderFunctionArgs } from "@remix-run/node";
import { Form, useActionData, useNavigation } from "@remix-run/react";
import type { Prisma } from "@trigger.dev/database";
import React, { useEffect, useState } from "react";
import { redirect, typedjson, useTypedLoaderData } from "remix-typedjson";
import invariant from "tiny-invariant";
import { z } from "zod";
import { BackgroundWrapper } from "~/components/BackgroundWrapper";
import { Feedback } from "~/components/Feedback";
import { AppContainer, MainCenteredContainer } from "~/components/layout/AppLayout";
import { TechnologyPicker } from "~/components/onboarding/TechnologyPicker";
import { Button, LinkButton } from "~/components/primitives/Buttons";
import { Callout } from "~/components/primitives/Callout";
import { Fieldset } from "~/components/primitives/Fieldset";
import { FormButtons } from "~/components/primitives/FormButtons";
import { FormError } from "~/components/primitives/FormError";
import { FormTitle } from "~/components/primitives/FormTitle";
import { Input } from "~/components/primitives/Input";
import { InputGroup } from "~/components/primitives/InputGroup";
import { Label } from "~/components/primitives/Label";
import { Select, SelectItem } from "~/components/primitives/Select";
import { prisma } from "~/db.server";
import { featuresForRequest } from "~/features.server";
import { redirectWithErrorMessage, redirectWithSuccessMessage } from "~/models/message.server";
import { createProject, ExceededProjectLimitError } from "~/models/project.server";
import { requireUserId } from "~/services/session.server";
import {
newProjectPath,
OrganizationParamsSchema,
organizationPath,
selectPlanPath,
v3ProjectPath,
} from "~/utils/pathBuilder";
import { generateVercelOAuthState } from "~/v3/vercel/vercelOAuthState.server";
const WORKING_ON_OTHER = "Other/not sure yet";
const GOALS_OTHER = "Other/not sure yet";
const workingOnOptions = [
"AI agent",
"Media processing pipeline",
"Media generation with AI",
"Event-driven workflow",
"Realtime streaming",
"Internal tool or background job",
WORKING_ON_OTHER,
] as const;
const goalOptions = [
"Ship a production workflow",
"Prototype or explore",
"Migrate an existing system",
"Learn how Trigger works",
"Evaluate against alternatives",
GOALS_OTHER,
] as const;
function shuffleArray<T>(arr: T[]): T[] {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
function MultiSelectField({
value,
setValue,
items,
icon,
}: {
value: string[];
setValue: (value: string[]) => void;
items: string[];
icon: React.ReactNode;
}) {
return (
<Select<string[], string>
value={value}
setValue={setValue}
placeholder="Select some options"
variant="secondary/small"
dropdownIcon
icon={icon}
items={items}
className="h-8 min-w-0 border-0 bg-charcoal-750 pl-2 text-sm text-text-dimmed ring-charcoal-600 transition hover:bg-charcoal-650 hover:text-text-dimmed hover:ring-1"
text={(v) =>
v.length === 0 ? undefined : (
<span className="flex min-w-0 items-center text-text-bright">
<span className="truncate">{v.slice(0, 2).join(", ")}</span>
{v.length > 2 && <span className="ml-1 flex-none">+{v.length - 2} more</span>}
</span>
)
}
>
{(items) =>
items.map((item) => (
<SelectItem key={item} value={item} checkPosition="left">
<span className="text-text-bright">{item}</span>
</SelectItem>
))
}
</Select>
);
}
export async function loader({ params, request }: LoaderFunctionArgs) {
const userId = await requireUserId(request);
const { organizationSlug } = OrganizationParamsSchema.parse(params);
const organization = await prisma.organization.findFirst({
where: { slug: organizationSlug, members: { some: { userId } } },
select: {
id: true,
title: true,
v3Enabled: true,
v2Enabled: true,
hasRequestedV3: true,
_count: {
select: {
projects: {
where: {
deletedAt: null,
},
},
},
},
},
});
if (!organization) {
throw new Response(null, { status: 404, statusText: "Organization not found" });
}
const { isManagedCloud } = featuresForRequest(request);
if (isManagedCloud && !organization.v3Enabled) {
return redirect(selectPlanPath({ slug: organizationSlug }));
}
const url = new URL(request.url);
const message = url.searchParams.get("message");
return typedjson({
organization: {
id: organization.id,
title: organization.title,
slug: organizationSlug,
projectsCount: organization._count.projects,
v3Enabled: organization.v3Enabled,
v2Enabled: organization.v2Enabled,
hasRequestedV3: organization.hasRequestedV3,
},
defaultVersion: url.searchParams.get("version") ?? "v2",
message: message ? decodeURIComponent(message) : undefined,
});
}
const schema = z.object({
projectName: z.string().min(3, "Project name must have at least 3 characters").max(50),
projectVersion: z.enum(["v2", "v3"]),
workingOn: z.string().optional(),
workingOnOther: z.string().optional(),
technologies: z.string().optional(),
technologiesOther: z.string().optional(),
goals: z.string().optional(),
goalsOther: z.string().optional(),
workingOnPositions: z.string().optional(),
goalsPositions: z.string().optional(),
});
export const action: ActionFunction = async ({ request, params }) => {
const userId = await requireUserId(request);
const { organizationSlug } = params;
invariant(organizationSlug, "organizationSlug is required");
const formData = await request.formData();
const submission = parse(formData, { schema });
if (!submission.value || submission.intent !== "submit") {
return json(submission);
}
const url = new URL(request.url);
const code = url.searchParams.get("code");
const configurationId = url.searchParams.get("configurationId");
const next = url.searchParams.get("next");
const stringArraySchema = z.array(z.string());
function safeParseStringArray(value: string | undefined): string[] | undefined {
if (!value) return undefined;
try {
const result = stringArraySchema.safeParse(JSON.parse(value));
return result.success && result.data.length > 0 ? result.data : undefined;
} catch {
return undefined;
}
}
const numberArraySchema = z.array(z.number());
function safeParseNumberArray(value: string | undefined): number[] | undefined {
if (!value) return undefined;
try {
const result = numberArraySchema.safeParse(JSON.parse(value));
return result.success && result.data.length > 0 ? result.data : undefined;
} catch {
return undefined;
}
}
const onboardingData: Record<string, Prisma.InputJsonValue> = {};
const workingOn = safeParseStringArray(submission.value.workingOn);
if (workingOn) {
onboardingData.workingOn = workingOn;
const workingOnPositions = safeParseNumberArray(submission.value.workingOnPositions);
if (workingOnPositions) onboardingData.workingOnPositions = workingOnPositions;
}
if (submission.value.workingOnOther) {
onboardingData.workingOnOther = submission.value.workingOnOther;
}
const technologies = safeParseStringArray(submission.value.technologies);
if (technologies) onboardingData.technologies = technologies;
const technologiesOther = safeParseStringArray(submission.value.technologiesOther);
if (technologiesOther) onboardingData.technologiesOther = technologiesOther;
const goals = safeParseStringArray(submission.value.goals);
if (goals) {
onboardingData.goals = goals;
const goalsPositions = safeParseNumberArray(submission.value.goalsPositions);
if (goalsPositions) onboardingData.goalsPositions = goalsPositions;
}
if (submission.value.goalsOther) {
onboardingData.goalsOther = submission.value.goalsOther;
}
try {
const project = await createProject({
organizationSlug: organizationSlug,
name: submission.value.projectName,
userId,
version: submission.value.projectVersion,
onboardingData: Object.keys(onboardingData).length > 0 ? onboardingData : undefined,
});
if (code && configurationId) {
const environment = await prisma.runtimeEnvironment.findFirst({
where: {
projectId: project.id,
slug: "prod",
archivedAt: null,
},
});
if (!environment) {
return redirectWithErrorMessage(
newProjectPath({ slug: organizationSlug }),
request,
"Failed to find project environment."
);
}
const state = await generateVercelOAuthState({
organizationId: project.organization.id,
projectId: project.id,
environmentSlug: environment.slug,
organizationSlug: project.organization.slug,
projectSlug: project.slug,
});
const params = new URLSearchParams({
state,
code,
configurationId,
origin: "marketplace",
});
if (next) {
params.set("next", next);
}
return redirect(`/vercel/connect?${params.toString()}`);
}
return redirectWithSuccessMessage(
v3ProjectPath(project.organization, project),
request,
`${submission.value.projectName} created`
);
} catch (error) {
if (error instanceof ExceededProjectLimitError) {
return redirectWithErrorMessage(
newProjectPath({ slug: organizationSlug }),
request,
error.message,
{
title: "Failed to create project",
action: {
label: "Request more projects",
variant: "secondary/small",
action: { type: "help", feedbackType: "help" },
},
}
);
}
return redirectWithErrorMessage(
newProjectPath({ slug: organizationSlug }),
request,
error instanceof Error ? error.message : "Something went wrong",
{ ephemeral: false }
);
}
};
export default function Page() {
const { organization, message } = useTypedLoaderData<typeof loader>();
const lastSubmission = useActionData();
const canCreateV3Projects = organization.v3Enabled;
const [form, { projectName, projectVersion }] = useForm({
id: "create-project",
lastSubmission: lastSubmission as any,
onValidate({ formData }) {
return parse(formData, { schema });
},
});
const navigation = useNavigation();
const isLoading = navigation.state === "submitting" || navigation.state === "loading";
const [selectedWorkingOn, setSelectedWorkingOn] = useState<string[]>([]);
const [workingOnOther, setWorkingOnOther] = useState("");
const [selectedTechnologies, setSelectedTechnologies] = useState<string[]>([]);
const [customTechnologies, setCustomTechnologies] = useState<string[]>([]);
const [selectedGoals, setSelectedGoals] = useState<string[]>([]);
const [goalsOther, setGoalsOther] = useState("");
const [shuffledWorkingOn, setShuffledWorkingOn] = useState<string[]>([...workingOnOptions]);
const [shuffledGoals, setShuffledGoals] = useState<string[]>([...goalOptions]);
useEffect(() => {
const nonOther = workingOnOptions.filter((o) => o !== WORKING_ON_OTHER);
setShuffledWorkingOn([...shuffleArray(nonOther), WORKING_ON_OTHER]);
const nonOtherGoals = goalOptions.filter((o) => o !== GOALS_OTHER);
setShuffledGoals([...shuffleArray(nonOtherGoals), GOALS_OTHER]);
}, []);
const showWorkingOnOther = selectedWorkingOn.includes(WORKING_ON_OTHER);
const showGoalsOther = selectedGoals.includes(GOALS_OTHER);
return (
<AppContainer className="bg-charcoal-900">
<BackgroundWrapper>
<MainCenteredContainer variant="onboarding" className="max-w-[29rem] rounded-lg border border-grid-bright bg-background-dimmed p-5 shadow-lg">
<div>
<FormTitle
LeadingIcon={<FolderIcon className="size-7 text-indigo-500" />}
title="Create a new project"
description={`This will create a new project in your "${organization.title}" organization.`}
/>
<Form method="post" {...form.props}>
{message && (
<Callout variant="success" className="mb-4">
{message}
</Callout>
)}
<Fieldset>
<InputGroup>
<Label htmlFor={projectName.id}>
Project name <span className="text-text-bright">*</span>
</Label>
<Input
{...conform.input(projectName, { type: "text" })}
placeholder="Your project name"
icon={FolderIcon}
autoFocus
/>
<FormError id={projectName.errorId}>{projectName.error}</FormError>
</InputGroup>
{canCreateV3Projects ? (
<input {...conform.input(projectVersion, { type: "hidden" })} value={"v3"} />
) : (
<input {...conform.input(projectVersion, { type: "hidden" })} value={"v2"} />
)}
<div className="border-t border-charcoal-700" />
<InputGroup>
<Label>What are you working on?</Label>
<input type="hidden" name="workingOn" value={JSON.stringify(selectedWorkingOn)} />
<input
type="hidden"
name="workingOnPositions"
value={JSON.stringify(
selectedWorkingOn.map((v) => shuffledWorkingOn.indexOf(v) + 1)
)}
/>
<MultiSelectField
value={selectedWorkingOn}
setValue={setSelectedWorkingOn}
items={shuffledWorkingOn}
icon={<CommandLineIcon className="mr-1 size-4 text-text-dimmed" />}
/>
{showWorkingOnOther && (
<>
<input type="hidden" name="workingOnOther" value={workingOnOther} />
<Input
type="text"
variant="small"
value={workingOnOther}
onChange={(e) => setWorkingOnOther(e.target.value)}
placeholder="Tell us what you're working on"
spellCheck={false}
containerClassName="h-8"
/>
</>
)}
</InputGroup>
<InputGroup>
<Label>What technologies are you using?</Label>
<input
type="hidden"
name="technologies"
value={JSON.stringify(selectedTechnologies)}
/>
<input
type="hidden"
name="technologiesOther"
value={JSON.stringify(customTechnologies)}
/>
<TechnologyPicker
value={selectedTechnologies}
onChange={setSelectedTechnologies}
customValues={customTechnologies}
onCustomValuesChange={setCustomTechnologies}
/>
</InputGroup>
<InputGroup>
<Label>What are you trying to do with Trigger.dev?</Label>
<input type="hidden" name="goals" value={JSON.stringify(selectedGoals)} />
<input
type="hidden"
name="goalsPositions"
value={JSON.stringify(
selectedGoals.map((v) => shuffledGoals.indexOf(v) + 1)
)}
/>
<MultiSelectField
value={selectedGoals}
setValue={setSelectedGoals}
items={shuffledGoals}
icon={<CommandLineIcon className="mr-1 size-4 text-text-dimmed" />}
/>
{showGoalsOther && (
<>
<input type="hidden" name="goalsOther" value={goalsOther} />
<Input
type="text"
variant="small"
value={goalsOther}
onChange={(e) => setGoalsOther(e.target.value)}
placeholder="Tell us what you're trying to do with Trigger.dev"
spellCheck={false}
containerClassName="h-8"
/>
</>
)}
</InputGroup>
<FormButtons
confirmButton={
<Button type="submit" variant={"primary/small"} isLoading={isLoading}>
Create
</Button>
}
cancelButton={
organization.projectsCount > 0 ? (
<LinkButton to={organizationPath(organization)} variant={"secondary/small"}>
Cancel
</LinkButton>
) : undefined
}
/>
</Fieldset>
</Form>
</div>
<Feedback button={<></>} />
</MainCenteredContainer>
</BackgroundWrapper>
</AppContainer>
);
}