-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.tsx
217 lines (200 loc) · 6.83 KB
/
form.tsx
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
'use client';
import { useState, useTransition } from 'react';
import { ConfigProvider, Form } from 'antd';
import { useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import MemberList from '@/components/VirtualLab/create-entity-flows/common/member-form';
import Overview from '@/components/VirtualLab/create-entity-flows/virtual-lab/overview';
import Footer from '@/components/VirtualLab/create-entity-flows/virtual-lab/footer';
import Plans from '@/components/VirtualLab/subscription-plans';
import useNotification from '@/hooks/notifications';
import { List } from '@/components/VirtualLab/create-entity-flows/common/member-avatar';
import { createVirtualLab } from '@/api/virtual-lab-svc/queries/virtual-lab';
import { VirtualLabPayload } from '@/api/virtual-lab-svc/types';
import { generateLabUrl } from '@/util/virtual-lab/urls';
import { extractInitials } from '@/util/slugify';
import {
virtualLabFlowSteps,
type VirtualLabFlowSteps,
} from '@/components/VirtualLab/create-entity-flows/common/types';
type Props = {
step: VirtualLabFlowSteps;
onCancel: () => void;
onStepChange: (step: VirtualLabFlowSteps) => void;
};
function Members() {
const { data } = useSession();
const id = data?.user.email!;
const name = data?.user.name!;
const email = data?.user.email!;
const initials = extractInitials(name);
return (
<List
members={[
{
id,
email,
role: 'admin',
name,
initials,
},
]}
/>
);
}
export default function CreationForm({ step, onCancel, onStepChange }: Props) {
const notify = useNotification();
const { push: navigate } = useRouter();
const { data } = useSession();
const params = useSearchParams();
const [form] = Form.useForm<VirtualLabPayload>();
const [isFormValid, setIsFormValid] = useState(false);
const [pending, startTransition] = useTransition();
const [slideDirection, setSlideDirection] = useState<'right' | 'left'>('right');
const fields = Form.useWatch<Omit<VirtualLabPayload, 'include_members'>>([], form);
const disableNextPlans = Boolean(!(isFormValid && fields?.email_status === 'verified'));
const disableNextMembers = !fields?.plan_id;
const allowAskCode = Boolean(isFormValid && fields.email_status !== 'verified');
const firstLogin = params.get('t') === 'f';
const onNextStep = () => {
setSlideDirection('left');
const currentIndex = virtualLabFlowSteps.findIndex((s) => s.id === step);
if (currentIndex < virtualLabFlowSteps.length - 1) {
onStepChange(virtualLabFlowSteps[currentIndex + 1].id);
}
};
const onPreviousStep = () => {
setSlideDirection('right');
const currentIndex = virtualLabFlowSteps.findIndex((s) => s.id === step);
if (currentIndex > 0) {
onStepChange(virtualLabFlowSteps[currentIndex - 1].id);
}
};
const resetForm = () => form.resetFields();
const onSelectPlan = (id: string) => {
form.setFieldValue('plan_id', id);
if (typeof window !== 'undefined')
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
};
const onValuesChange = () => {
form
.validateFields()
.then(() => {
setIsFormValid(true);
})
.catch((error) => {
if (error.errorFields.length > 0) {
setIsFormValid(false);
} else {
setIsFormValid(true);
}
});
};
const onFormSubmit = async (values: VirtualLabPayload) => {
startTransition(async () => {
try {
const formValues = {
...values,
include_members:
values.include_members?.map((o) => ({ email: o.email, role: o.role })) ?? null,
};
const result = await createVirtualLab(formValues);
if (result && result.data) {
notify.success(
'Your Virtual Lab has been created successfully and is now ready to use.',
undefined,
'topRight',
undefined
);
resetForm();
const labUrl = generateLabUrl(result.data.virtual_lab.id);
navigate(`${labUrl}/overview`);
} else {
throw new Error('Virtual lab creation failed');
}
} catch (error) {
notify.error(
'Virtual Lab creation failed. Please check your details and try again.',
undefined,
'topRight',
undefined
);
}
});
};
return (
<ConfigProvider theme={{ hashed: false }}>
<Form
name="virtual-lab-creation-flow"
form={form}
layout="vertical"
onFinish={onFormSubmit}
className="relative flex h-full flex-grow flex-col px-4 py-2"
requiredMark={false}
validateTrigger={['onChange']}
initialValues={{
name: firstLogin ? `${data?.user.name}'s virtual lab` : undefined,
description: '',
entity: null,
include_members: [],
}}
onValuesChange={onValuesChange}
disabled={pending}
>
<Form.Item hidden name="plan_id">
<input name="plan_id" type="text" hidden />
</Form.Item>
<AnimatePresence initial={false} custom={slideDirection} mode="wait">
<motion.div
key={step}
custom={slideDirection}
variants={{
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 },
}}
initial="enter"
animate="center"
exit="exit"
transition={{
duration: 0.3,
type: 'tween',
ease: 'easeInOut',
}}
className="relative flex h-full flex-grow flex-col"
>
<div className={step !== 'information' ? 'hidden' : ''}>
<Overview allowAskCode={allowAskCode} />
</div>
<div className={step !== 'members' ? 'hidden' : ''}>
<MemberList
ListCompo={Members}
cls={{ listContainer: 'max-h-[calc(100vh-500px)] mb-5 secondary-scrollbar' }}
/>
</div>
<div className={step !== 'plans' ? 'hidden' : ''}>
<Plans selectedPlan={fields?.plan_id} onSelectPlan={onSelectPlan} />
</div>
</motion.div>
</AnimatePresence>
<div className="mx-auto mt-auto w-full max-w-5xl lg:max-w-full">
<div className="py-4">
<Footer
{...{
step,
onCancel,
onNextStep,
onPreviousStep,
disableNextPlans,
disableNextMembers,
loading: pending,
disableCreate: !isFormValid || pending,
}}
/>
</div>
</div>
</Form>
</ConfigProvider>
);
}