Logs.UpdateSavedQueryModal.tsx 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { zodResolver } from '@hookform/resolvers/zod'
  2. import { useEffect } from 'react'
  3. import { SubmitHandler, useForm } from 'react-hook-form'
  4. import { Button, Form, FormControl, FormField, Input, Modal, Textarea } from 'ui'
  5. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  6. import * as z from 'zod'
  7. const formSchema = z.object({
  8. name: z.string().min(1, 'Required'),
  9. description: z.string().optional(),
  10. })
  11. type SavedQuery = z.infer<typeof formSchema>
  12. export interface UpdateSavedQueryProps {
  13. header: string
  14. visible: boolean
  15. onCancel: () => void
  16. onSubmit: SubmitHandler<SavedQuery>
  17. initialValues: SavedQuery
  18. }
  19. export const UpdateSavedQueryModal = ({
  20. header,
  21. visible,
  22. onCancel,
  23. onSubmit,
  24. initialValues,
  25. }: UpdateSavedQueryProps) => {
  26. const form = useForm<SavedQuery>({
  27. resolver: zodResolver(formSchema as any),
  28. defaultValues: { ...initialValues, description: initialValues.description ?? '' },
  29. })
  30. const { reset, formState } = form
  31. const { isDirty, isSubmitting } = formState
  32. useEffect(() => {
  33. if (isDirty) return
  34. reset({ ...initialValues, description: initialValues.description ?? '' })
  35. }, [isDirty, initialValues, reset])
  36. const handleCancel = () => {
  37. form.reset()
  38. onCancel()
  39. }
  40. return (
  41. <Modal visible={visible} onCancel={handleCancel} hideFooter header={header} size="medium">
  42. <Form {...form}>
  43. <form onSubmit={form.handleSubmit(onSubmit)} noValidate>
  44. <Modal.Content>
  45. <FormField
  46. control={form.control}
  47. name="name"
  48. render={({ field }) => (
  49. <FormItemLayout layout="vertical" label="Name">
  50. <FormControl>
  51. <Input {...field} placeholder="Enter text" />
  52. </FormControl>
  53. </FormItemLayout>
  54. )}
  55. />
  56. </Modal.Content>
  57. <Modal.Content>
  58. <FormField
  59. control={form.control}
  60. name="description"
  61. render={({ field }) => (
  62. <FormItemLayout layout="vertical" label="Description">
  63. <FormControl>
  64. <Textarea {...field} placeholder="Describe query" className="resize-none" />
  65. </FormControl>
  66. </FormItemLayout>
  67. )}
  68. />
  69. </Modal.Content>
  70. <Modal.Separator />
  71. <Modal.Content className="flex items-center justify-end gap-2">
  72. <Button htmlType="reset" type="default" onClick={handleCancel} disabled={isSubmitting}>
  73. Cancel
  74. </Button>
  75. <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting || !isDirty}>
  76. Save query
  77. </Button>
  78. </Modal.Content>
  79. </form>
  80. </Form>
  81. </Modal>
  82. )
  83. }