-
Notifications
You must be signed in to change notification settings - Fork 542
Expand file tree
/
Copy pathuseLoginProModal.tsx
More file actions
405 lines (364 loc) · 12.5 KB
/
useLoginProModal.tsx
File metadata and controls
405 lines (364 loc) · 12.5 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
import { BottomActionBar, BottomActionBarError, Form, useStreamingTerminal } from "@/components"
import { useProInstanceManager, useProInstances, useProvider, useProviders } from "@/contexts"
import { canHealthCheck, exists, useFormErrors } from "@/lib"
import { Routes } from "@/routes"
import {
Box,
Button,
Container,
Divider,
FormControl,
FormErrorMessage,
FormHelperText,
FormLabel,
Heading,
Input,
InputGroup,
InputLeftAddon,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
Tooltip,
useDisclosure,
VStack,
} from "@chakra-ui/react"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { SubmitHandler, useForm } from "react-hook-form"
import { useNavigate } from "react-router"
import { ConfigureProviderOptionsForm, useSetupProvider } from "@/views/Providers"
import { To } from "react-router-dom"
import { useQueryClient } from "@tanstack/react-query"
import { client } from "@/client"
import { QueryKeys } from "@/queryKeys"
type TFormValues = {
[FieldName.PRO_HOST]: string
[FieldName.ACCESS_KEY]: string | undefined
}
const FieldName = {
PRO_HOST: "proURL",
ACCESS_KEY: "accessKey",
} as const
type TSetupProInitialData = {
host: string
accessKey?: string
suggestedOptions: Record<string, string>
}
export function useLoginProModal() {
const [suggestedOptions, setSuggestedOptions] = useState<
TSetupProInitialData["suggestedOptions"]
>({})
const { terminal, connectStream, clear: clearTerminal } = useStreamingTerminal({ fontSize: "sm" })
const [[proInstances], { login, disconnect }] = useProInstances()
const [[providers]] = useProviders()
const { isOpen, onClose, onOpen } = useDisclosure()
const { handleSubmit, formState, register, reset, setValue } = useForm<TFormValues>({
mode: "onBlur",
})
const containerRef = useRef<HTMLDivElement>(null)
const onSubmit = useCallback<SubmitHandler<TFormValues>>(
(data) => {
clearTerminal()
login.run({
host: data[FieldName.PRO_HOST],
accessKey: data[FieldName.ACCESS_KEY],
streamListener: connectStream,
})
},
[connectStream, login, clearTerminal]
)
const handleOpenLogin = useCallback(
(data?: TSetupProInitialData) => {
onOpen()
if (data === undefined || login.status === "loading") {
return
}
setValue(FieldName.PRO_HOST, data.host)
if (data.accessKey) {
setValue(FieldName.ACCESS_KEY, data.accessKey)
}
setSuggestedOptions(data.suggestedOptions)
handleSubmit(onSubmit)()
},
[handleSubmit, login.status, onOpen, onSubmit, setValue]
)
const {
state,
reset: resetSetupProvider,
completeSetupProvider,
completeConfigureProvider,
removeDanglingProviders,
} = useSetupProvider()
const { proURLError } = useFormErrors(Object.values(FieldName), formState)
const resetModal = useCallback(
(checkDanglingProInstance: boolean = false) => {
reset()
login.reset()
if (checkDanglingProInstance) {
const proInstanceID = proInstances?.find((pro) => pro.provider === state.providerID)?.host
if (proInstanceID) {
disconnect.run({ id: proInstanceID })
}
}
onClose()
},
[disconnect, login, onClose, proInstances, reset, state.providerID]
)
useEffect(() => {
if (state.currentStep === "done") {
resetSetupProvider()
removeDanglingProviders()
}
}, [removeDanglingProviders, resetSetupProvider, state.currentStep])
const areInputsDisabled = useMemo(
() => login.status === "success" || login.status === "loading",
[login.status]
)
const navigate = useNavigate()
const completeFlow = useCallback(() => {
completeConfigureProvider()
resetModal()
const proInstanceID = proInstances?.find((pro) => pro.provider === state.providerID)?.host
if (!proInstanceID || !state.providerID) return
const provider = providers?.[state.providerID]
let route: To
// We only redirect to the new experience if the provider supports it.
// Support can be determined via canHealthCheck.
if (provider && canHealthCheck(provider.config)) {
route = Routes.toProInstance(proInstanceID)
} else {
route = Routes.toWorkspaceCreate({
workspaceID: null,
ide: null,
rawSource: null,
providerID: state.providerID,
})
}
// workaround for layout shift after closing modal, no clue why
setTimeout(() => {
navigate(route)
}, 0)
}, [completeConfigureProvider, navigate, providers, proInstances, resetModal, state.providerID])
const [provider] = useProvider(state.providerID)
const supportsProFlow = useMemo(() => {
return canHealthCheck(provider?.config)
}, [provider])
const queryClient = useQueryClient()
const saveAndSkipForm = useCallback(async () => {
if (!state.providerID) {
return
}
;(
await client.providers.configure(state.providerID, {
useAsDefaultProvider: true,
reuseMachine: false,
options: {},
})
).unwrap()
await queryClient.invalidateQueries(QueryKeys.PROVIDERS)
completeFlow()
}, [queryClient, state.providerID, completeFlow])
const skippedConfigurationRef = useRef<boolean>(false)
useEffect(() => {
if (login.status === "success" && !skippedConfigurationRef.current) {
const providerID = login.provider?.config?.name
if (!exists(providerID)) {
return
}
completeSetupProvider({ providerID, suggestedOptions })
if (supportsProFlow) {
skippedConfigurationRef.current = true
saveAndSkipForm()
}
}
}, [
completeSetupProvider,
supportsProFlow,
saveAndSkipForm,
login.provider,
login.status,
suggestedOptions,
])
const modal = useMemo(() => {
return (
<Modal
onClose={() => resetModal(true)}
isOpen={isOpen}
closeOnEsc={login.status !== "loading"}
closeOnOverlayClick={login.status !== "loading"}
isCentered
size="4xl"
scrollBehavior="inside">
<ModalOverlay />
<ModalContent overflow="hidden">
{login.status !== "loading" && <ModalCloseButton />}
<ModalHeader>Connect to DevPod Pro</ModalHeader>
<ModalBody overflowX="hidden" overflowY="auto" paddingBottom="0" ref={containerRef}>
<VStack align="start" spacing="8" paddingX="4" paddingTop="4">
<Form onSubmit={handleSubmit(onSubmit)} justifyContent="center">
<Container minHeight="40" maxWidth="container.md">
<FormControl
isRequired
isInvalid={exists(proURLError)}
isDisabled={areInputsDisabled}>
<FormLabel>URL</FormLabel>
<InputGroup>
<InputLeftAddon>https://</InputLeftAddon>
<Input
type="text"
placeholder="my-pro.my-domain.com"
{...register(FieldName.PRO_HOST, {
required: true,
validate: {
url: (value) => {
try {
new URL(`https://${value.replace(/^https?:\/\//, "")}`)
return true
} catch (error) {
return "Please enter a valid URL"
}
},
unique: (value) => {
const isHostTaken = proInstances?.some(
(instance) => instance.host === value
)
return isHostTaken
? `URL must be unique, an instance with the URL https://${value} already exists`
: true
},
},
})}
/>
</InputGroup>
{proURLError && proURLError.message ? (
<FormErrorMessage>{proURLError.message}</FormErrorMessage>
) : (
<FormHelperText>
Enter a URL to the DevPod Pro instance you intend to connect to. If
you're unsure about it, ask your company administrator or create a new
Pro instance on your local machine.
</FormHelperText>
)}
</FormControl>
</Container>
{login.status !== "idle" && state.currentStep === "select-provider" && (
<Box width="full" height="10rem">
{terminal}
</Box>
)}
{state.currentStep !== "configure-provider" && (
<BottomActionBar isModal>
<Tooltip label="Please fill in URL" isDisabled={formState.isValid}>
<Button
type="submit"
variant="primary"
isLoading={formState.isSubmitting || login.status === "loading"}
isDisabled={!formState.isValid}
title="Login">
Login
</Button>
</Tooltip>
<BottomActionBarError containerRef={containerRef} error={login.error} />
</BottomActionBar>
)}
</Form>
{!supportsProFlow && state.currentStep === "configure-provider" && (
<>
<Divider />
<Heading size="md" as="h2">
Configure your Pro provider
</Heading>
<ConfigureProviderOptionsForm
isModal
isDefault
addProvider
reuseMachine={false}
showBottomActionBar={true}
providerID={state.providerID}
containerRef={containerRef}
suggestedOptions={state.suggestedOptions}
onFinish={completeFlow}
/>
</>
)}
</VStack>
</ModalBody>
</ModalContent>
</Modal>
)
}, [
resetModal,
isOpen,
login.status,
login.error,
handleSubmit,
onSubmit,
proURLError,
areInputsDisabled,
register,
state,
terminal,
formState.isValid,
formState.isSubmitting,
completeFlow,
proInstances,
])
return { modal, handleOpenLogin }
}
export function useReLoginProModal() {
const { terminal, connectStream, clear: clearTerminal } = useStreamingTerminal({ fontSize: "sm" })
const { login } = useProInstanceManager()
const { isOpen, onClose, onOpen } = useDisclosure()
const containerRef = useRef<HTMLDivElement>(null)
const handleOpenLogin = useCallback(
(data: NonNullable<Pick<TSetupProInitialData, "host">>) => {
onOpen()
login.run({ host: data.host, streamListener: connectStream })
},
[connectStream, login, onOpen]
)
const resetModal = useCallback(() => {
clearTerminal()
onClose()
}, [clearTerminal, onClose])
const modal = useMemo(() => {
return (
<Modal
onClose={resetModal}
isOpen={isOpen}
closeOnEsc={login.status !== "loading"}
closeOnOverlayClick={login.status !== "loading"}
isCentered
size="4xl"
scrollBehavior="inside">
<ModalOverlay />
<ModalContent overflow="hidden">
{login.status !== "loading" && <ModalCloseButton />}
<ModalHeader>Login to DevPod Pro</ModalHeader>
<ModalBody overflowX="hidden" overflowY="auto" paddingBottom="0" ref={containerRef}>
<VStack align="start" spacing="8" paddingX="4" paddingTop="4" paddingBottom="6">
{login.status !== "idle" && (
<Box width="full" height="10rem">
{terminal}
</Box>
)}
</VStack>
</ModalBody>
<ModalFooter>
<Button
isDisabled={login.status !== "success"}
isLoading={login.status === "loading"}
variant="solid"
onClick={resetModal}>
Done
</Button>
</ModalFooter>
</ModalContent>
</Modal>
)
}, [resetModal, isOpen, login.status, terminal])
return { modal, handleOpenLogin }
}