base-url-dialog.tsx77 lines · main
1import { useState } from 'react'
2import { Alert } from 'ui/src/components/shadcn/ui/alert'
3import { Button } from 'ui/src/components/shadcn/ui/button'
4import {
5 Dialog,
6 DialogContent,
7 DialogDescription,
8 DialogFooter,
9 DialogHeader,
10 DialogTitle,
11} from 'ui/src/components/shadcn/ui/dialog'
12
13import { Input } from '../DataInputs/Input'
14
15export type BaseUrlDialogProps = {
16 defaultValue?: string
17 onChange?: (value: string) => void
18 open?: boolean
19 onOpenChange?: (open: boolean) => void
20}
21
22export function BaseUrlDialog({ open, onOpenChange, defaultValue, onChange }: BaseUrlDialogProps) {
23 const [value, setValue] = useState(defaultValue ?? '')
24 const [error, setError] = useState<Error>()
25
26 return (
27 <Dialog
28 open={open}
29 onOpenChange={(open) => {
30 onOpenChange?.(open)
31 }}
32 >
33 <DialogContent className="sm:max-w-[425px]">
34 <DialogHeader className="pb-0">
35 <DialogTitle>Change base URL</DialogTitle>
36 <DialogDescription>
37 Change the base URL shown in the generated snippets.
38 </DialogDescription>
39 </DialogHeader>
40 <form
41 className="flex flex-col gap-4"
42 onSubmit={(e) => {
43 e.preventDefault()
44
45 try {
46 const baseUrl = new URL(value)
47 const newValue = (baseUrl.origin + baseUrl.pathname).replace(/\/+$/, '')
48
49 setValue(newValue)
50 onChange?.(newValue)
51 onOpenChange?.(false)
52 setError(undefined)
53 } catch (err) {
54 setError(new Error('Invalid URL'))
55 }
56 }}
57 >
58 <div className="px-7 flex flex-col gap-4">
59 <Input
60 value={value}
61 placeholder="https://example.com"
62 onChange={(e) => {
63 setValue(e.target.value)
64 }}
65 />
66 {error && <Alert className="text-red-900">{error.message}</Alert>}
67 </div>
68 <DialogFooter>
69 <Button variant="outline" type="submit">
70 Change
71 </Button>
72 </DialogFooter>
73 </form>
74 </DialogContent>
75 </Dialog>
76 )
77}