-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthorizeForm.tsx
308 lines (286 loc) · 9.12 KB
/
AuthorizeForm.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
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
import { useRevalidator } from '@remix-run/react'
import { useEffect, useRef, useState } from 'react'
import { wait } from 'remix-utils/timers'
import { CloseInterceptReason } from '../organism/ModalWrapper/ModalWrapper'
import MessageContainer from '../pending/MessageContainer'
import { useDispatch, useDispatchState } from '../pending/ProcessProvider'
interface AuthorizeFormProps {
setCloseInterceptReason?: (reason: CloseInterceptReason) => void
setPopupWindow?: (window: Window | null) => void
}
const AuthorizeForm: React.FC<AuthorizeFormProps> = ({
setCloseInterceptReason,
setPopupWindow,
}) => {
const [showFallback, setShowFallback] = useState(false)
const [fallbackUrl, setFallbackUrl] = useState('')
const [steamPopupOpened, setSteamPopupOpened] = useState(false)
const [steamPopup, setSteamPopup] = useState<Window | null>(null)
const revalidator = useRevalidator()
const callback = () => {
revalidator.revalidate()
}
const [showAlternative, setShowAlternative] = useState(false)
const [visible, setVisible] = useState(false)
const timerRef = useRef<NodeJS.Timeout | null>(null)
const transitionRef = useRef<HTMLDivElement | null>(null)
const dispatch = useDispatch()
const state = useDispatchState()
const currentDispatch = state.find(dispatch => dispatch.inProgress)
const errorMessage = currentDispatch?.message
useEffect(() => {
if (visible) {
timerRef.current = setTimeout(() => {
setShowAlternative(true)
}, 1500)
}
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current)
}
setShowAlternative(false)
}
}, [visible])
const handleCancel = (event?: React.MouseEvent) => {
if (event) {
event.stopPropagation() // Prevents the event from propagating further
}
if (timerRef.current) {
clearTimeout(timerRef.current)
}
setShowAlternative(false)
setVisible(false)
if (transitionRef.current) {
transitionRef.current.addEventListener(
'transitionend',
() => {
// Perform actions after the transition ends
setSteamPopup(null)
setSteamPopupOpened(false)
setPopupWindow?.(null)
setShowFallback(false)
setCloseInterceptReason?.(CloseInterceptReason.None)
},
{ once: true },
)
}
}
const resetForm = () => {
setVisible(false)
setSteamPopup(null)
setSteamPopupOpened(false)
setPopupWindow?.(null)
setShowFallback(false)
setCloseInterceptReason?.(CloseInterceptReason.None)
}
useEffect(() => {
if (setCloseInterceptReason) {
setCloseInterceptReason(CloseInterceptReason.None)
}
const handleMessage = (event: MessageEvent) => {
if (event.data.type === 'steam-auth-success') {
console.log(
'[AuthorizeForm.tsx] User has successfully integrated their steam.',
)
console.log('[AuthorizeForm.tsx] Steam Authentication Flow: Popup')
callback()
} else if (event.data.type === 'steam-auth-error') {
console.error(
'[AuthorizeForm.tsx] Error during Steam authentication:',
event.data.message,
)
console.log('[AuthorizeForm.tsx] Steam Authentication Flow: Popup')
// Handle error and reset form
dispatch.send(event.data.message)
resetForm()
// TODO: implement toast in future during ui/ux enhancement related tasks
// alert(`Steam authentication error: ${event.data.message}`)
} else {
if (event.data.type) {
console.log('[AuthorizeForm.tsx] Event was unknown:', event.data.type) // To see exactly which unknown event was received
}
}
}
// This might be skipped and not needed. Confirmed that event "steamAuthSuccess" was caught in CheckProcess.tsx.
const handleEvent = (event: Event) => {
console.log('[AuthorizeForm.tsx] Received event:', event.type) // To see exactly which event was received
if (event.type === 'steamAuthSuccess') {
console.log(
'[AuthorizeForm.tsx] User has successfully integrated their Steam account.',
)
console.log('[AuthorizeForm.tsx] Steam Authentication Flow: Redirect')
callback()
} else if (event.type === 'steamAuthError') {
console.error(
'[AuthorizeForm.tsx] Error during Steam authentication from redirect.',
)
console.log('[AuthorizeForm.tsx] Steam Authentication Flow: Redirect')
// console.error('[AuthorizeForm.tsx] Error during Steam authentication:', event.data.message)
// TODO: implement toast in future during ui/ux enhancement related tasks
// TODO: Update redirect flash to include error message from callback
// alert(`Steam authentication error: ${event.data.message}`)
dispatch.send('Error during Steam authentication from redirect.')
resetForm()
} else {
console.log('[AuthorizeForm.tsx] Event was unknown:', event.type) // To see exactly which unknown event was received
}
}
window.addEventListener('message', handleMessage)
window.addEventListener('event', handleEvent)
return () => {
window.removeEventListener('message', handleMessage)
window.removeEventListener('event', handleEvent)
}
}, [])
const initiateSteamLinking = async () => {
setVisible(true)
if (setCloseInterceptReason) {
setCloseInterceptReason(CloseInterceptReason.RequestInProgress)
}
try {
const response = await fetch('/authorize/steam')
const data = await response.json()
if (data.url) {
const popup = window.open(
data.url,
'steamPopup',
'width=600,height=700',
)
setFallbackUrl(data.fallback)
if (!popup) {
console.error(
'Popup failed to open, likely blocked by popup blocker.',
)
setShowFallback(true)
setSteamPopupOpened(false)
setPopupWindow?.(null)
setCloseInterceptReason?.(CloseInterceptReason.None)
} else {
setSteamPopup(popup)
setPopupWindow?.(popup)
setSteamPopupOpened(true)
setCloseInterceptReason?.(CloseInterceptReason.ActivePopup)
}
} else {
alert('Failed to initiate Steam linking. Please try again.')
setCloseInterceptReason?.(CloseInterceptReason.None)
}
} catch (error) {
console.error('Failed to fetch Steam linking URL', error)
setShowFallback(true)
handleCancel()
setSteamPopupOpened(false)
setPopupWindow?.(null)
}
}
useEffect(() => {
let interval: NodeJS.Timeout
if (steamPopupOpened && steamPopup) {
interval = setInterval(async () => {
if (steamPopup.closed) {
handleCancel()
await wait(750)
clearInterval(interval)
setSteamPopup(null)
setSteamPopupOpened(false)
setPopupWindow?.(null)
setShowFallback(false)
setCloseInterceptReason?.(CloseInterceptReason.None)
}
}, 500)
}
return () => {
if (interval) {
clearInterval(interval)
}
}
}, [steamPopupOpened, steamPopup, setCloseInterceptReason, setPopupWindow])
const handleFallbackClick = (
e:
| React.MouseEvent<HTMLButtonElement>
| React.KeyboardEvent<HTMLButtonElement>,
) => {
e.preventDefault()
// Close the popup if it's open
if (steamPopup && !steamPopup.closed) {
steamPopup.close()
setSteamPopup(null)
setSteamPopupOpened(false)
setPopupWindow?.(null)
setShowFallback(false)
setCloseInterceptReason?.(CloseInterceptReason.None)
}
// Redirect the parent window to steam openid url after potential popup cleanup.
window.location.href = fallbackUrl
}
return (
<div>
{errorMessage && !steamPopupOpened && !visible ? (
<MessageContainer message={errorMessage} />
) : null}
{!steamPopupOpened && !visible ? (
<div className="cta-container">
<div className="cta-text">Link your Steam account to continue?</div>
<button
className="steam-button button transition hover:border-none"
onClick={initiateSteamLinking}
style={{ visibility: visible ? 'hidden' : 'visible' }}
>
Link Steam Account
</button>
</div>
) : (
<div
className="loader"
style={{
animation: visible ? 'fadeIn 1s forwards' : 'fadeOut 1s forwards',
}}
>
<div className="spinner"></div>
<p id="loaderText">
Please link your Steam account in the popup window.
</p>
<p
className="bg-stone-900/95 p-2"
id="alternativeText"
style={{
opacity: showAlternative ? 1 : 0,
transform: `translateY(${showAlternative ? '0px' : '20px'})`,
}}
>
{showFallback ? (
<>
We believe your browser may have blocked the popup. No worries,
you can{' '}
<button
onClick={e => handleFallbackClick(e)}
onKeyDown={e => handleFallbackClick(e)}
rel="noopener noreferrer"
className="text-red-500 no-underline hover:cursor-pointer hover:underline focus:cursor-default"
>
click Here
</button>{' '}
to sign in manually.
</>
) : (
<>
Still having trouble? It's possible your browser blocked
the popup. No worries, you can{' '}
<button
onClick={e => handleFallbackClick(e)}
onKeyDown={e => handleFallbackClick(e)}
rel="noopener noreferrer"
className="text-red-500 no-underline hover:cursor-pointer hover:underline focus:cursor-default"
>
click Here
</button>{' '}
to sign in manually.
</>
)}
</p>
</div>
)}
</div>
)
}
export default AuthorizeForm