-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainCard.tsx
More file actions
273 lines (248 loc) · 7.87 KB
/
MainCard.tsx
File metadata and controls
273 lines (248 loc) · 7.87 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
import { Progress, Button } from '@pinback/design-system/ui';
import { useState, useEffect, lazy, Suspense } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import SocialLoginStep from './step/SocialLoginStep';
const StoryStep = lazy(() => import('./step/StoryStep'));
const JobStep = lazy(() => import('./step/JobStep'));
const AlarmStep = lazy(() => import('./step/AlarmStep'));
const MacStep = lazy(() => import('./step/MacStep'));
const FinalStep = lazy(() => import('./step/FinalStep'));
import { cva } from 'class-variance-authority';
import { usePostSignUp } from '@shared/apis/queries';
import { useNavigate, useLocation } from 'react-router-dom';
import { firebaseConfig } from '../../../../firebase-config';
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken } from 'firebase/messaging';
import { registerServiceWorker } from '@pages/onBoarding/utils/registerServiceWorker';
import { AlarmsType } from '@constants/alarms';
import { normalizeTime } from '@pages/onBoarding/utils/formatRemindTime';
const stepProgress = [{ progress: 33 }, { progress: 66 }, { progress: 100 }];
import {
Step,
stepOrder,
StepType,
storySteps,
} from '@pages/onBoarding/constants/onboardingSteps';
const variants = {
slideIn: (direction: number) => ({
x: direction > 0 ? 200 : -200,
opacity: 0,
}),
slideCenter: { x: 0, opacity: 1 },
slideOut: (direction: number) => ({
x: direction > 0 ? -200 : 200,
opacity: 0,
}),
};
const CardStyle = cva(
'bg-white-bg flex h-[54.8rem] w-full flex-col items-center justify-between rounded-[2.4rem] pt-[3.2rem]',
{
variants: {
overflow: {
true: 'overflow-visible',
false: 'overflow-hidden',
},
size: {
default: 'max-w-[63.2rem]',
wide: 'max-w-[82.6rem]',
},
},
defaultVariants: { overflow: false, size: 'default' },
}
);
const MainCard = () => {
const navigate = useNavigate();
const location = useLocation();
const { mutate: postSignData } = usePostSignUp();
const [step, setStep] = useState<StepType>(Step.STORY_0);
const [direction, setDirection] = useState(0);
const [alarmSelected, setAlarmSelected] = useState<1 | 2 | 3>(1);
const [isMac, setIsMac] = useState(false);
const [userEmail, setUserEmail] = useState('');
const [remindTime, setRemindTime] = useState('09:00');
const [fcmToken, setFcmToken] = useState<string | null>(null);
const [jobShareAgree, setJobShareAgree] = useState(true);
useEffect(() => {
const params = new URLSearchParams(location.search);
const storedEmail = localStorage.getItem('email');
if (storedEmail) {
setUserEmail(storedEmail);
}
const stepParam = params.get('step') as StepType;
if (stepParam && Object.values(Step).includes(stepParam)) {
setStep(stepParam);
}
}, [location.search]);
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
const requestFCMToken = async (): Promise<string | null> => {
try {
const permission = await Notification.requestPermission();
registerServiceWorker();
if (permission !== 'granted') {
alert('알림 권한 허용이 필요합니다!');
return null;
}
const forFcmtoken = await getToken(messaging, {
vapidKey: import.meta.env.VITE_FIREBASE_VAPID_KEY,
});
if (forFcmtoken) {
return forFcmtoken;
} else {
alert('토큰 생성 실패. 다시 시도해주세요.');
return null;
}
} catch (error) {
console.error('FCM 토큰 받는 도중 오류:', error);
alert('알림 설정 중 오류가 발생했습니다. 다시 시도해주세요.');
return null;
}
};
useEffect(() => {
const ua = navigator.userAgent.toLowerCase();
if (ua.includes('mac os') || ua.includes('iphone') || ua.includes('ipad')) {
setIsMac(true);
}
(async () => {
const token = await requestFCMToken();
if (token) {
setFcmToken(token);
localStorage.setItem('FcmToken', token);
} else {
alert('푸시 알람 설정 에러');
}
})();
}, []);
const renderStep = () => {
switch (step) {
case Step.STORY_0:
case Step.STORY_1:
case Step.STORY_2:
return (
<StoryStep step={Number(step.replace('STORY_', '')) as 0 | 1 | 2} />
);
case Step.SOCIAL_LOGIN:
return <SocialLoginStep />;
case Step.JOB:
return (
<JobStep
agreeChecked={jobShareAgree}
onAgreeChange={setJobShareAgree}
/>
);
case Step.ALARM:
return (
<AlarmStep selected={alarmSelected} setSelected={setAlarmSelected} />
);
case Step.MAC:
return <MacStep />;
case Step.FINAL:
return <FinalStep />;
default:
return <FinalStep />;
}
};
const nextStep = async () => {
const idx = stepOrder.indexOf(step);
const next = stepOrder[idx + 1];
const isAlarmStep = step === Step.ALARM;
const isFinalStep = step === Step.FINAL;
const isMacStep = next === Step.MAC;
const shouldSkipMacStep = isMacStep && !isMac;
if (isAlarmStep) {
if (alarmSelected === 1) setRemindTime('09:00');
else if (alarmSelected === 2) setRemindTime('20:00');
else {
const raw = AlarmsType[alarmSelected - 1].time;
setRemindTime(normalizeTime(raw));
}
}
if (shouldSkipMacStep) {
setDirection(1);
setStep(Step.FINAL);
navigate(`/onboarding?step=${Step.FINAL}`);
return;
}
if (isFinalStep) {
postSignData(
{ email: userEmail, remindDefault: remindTime, fcmToken },
{
onSuccess: () => (window.location.href = '/'),
onError: () => {
const savedEmail = localStorage.getItem('email');
if (savedEmail) window.location.href = '/';
},
}
);
return;
}
setDirection(1);
setStep(next);
navigate(`/onboarding?step=${next}`);
};
const prevStep = () => {
const idx = stepOrder.indexOf(step);
if (idx > 0) {
const previous = stepOrder[idx - 1];
setDirection(-1);
setStep(previous);
navigate(`/onboarding?step=${previous}`);
}
};
return (
<div
className={CardStyle({
overflow: step === Step.ALARM && alarmSelected === 3,
size: step === Step.JOB ? 'wide' : 'default',
})}
>
{storySteps.includes(step) && (
<Progress
value={stepProgress[storySteps.indexOf(step)].progress}
variant="profile"
className="w-[15.6rem]"
/>
)}
<div className="relative flex h-full w-full items-center justify-center">
<AnimatePresence custom={direction} mode="wait">
<motion.div
key={step}
custom={direction}
variants={variants}
initial="slideIn"
animate="slideCenter"
exit="slideOut"
transition={{ duration: 0.4 }}
className="flex h-full flex-col items-center"
>
<Suspense fallback={null}>{renderStep()}</Suspense>
</motion.div>
</AnimatePresence>
</div>
<div className="mb-[4.8rem] mt-[1.2rem] flex w-full justify-between px-[3.2rem]">
{!([Step.STORY_0, Step.SOCIAL_LOGIN] as StepType[]).includes(step) && (
<Button
variant="secondary"
size="medium"
className="w-[4.8rem]"
onClick={prevStep}
>
뒤로
</Button>
)}
{step !== Step.SOCIAL_LOGIN && (
<Button
variant="primary"
size="medium"
className="ml-auto w-[4.8rem]"
onClick={nextStep}
isDisabled={step === Step.JOB && !jobShareAgree}
>
다음
</Button>
)}
</div>
</div>
);
};
export default MainCard;