AddMediaForm.tsx 4.4 KB
Newer Older
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
import type { MediaDetails } from '@/api/sshoc'
import { useImportMedia, useUploadMedia } from '@/api/sshoc'
import { Button } from '@/elements/Button/Button'
import { useToast } from '@/elements/Toast/useToast'
import { MediaError } from '@/lib/error/MediaError'
import { useAuth } from '@/modules/auth/AuthContext'
import { FormFileInput } from '@/modules/form/components/FormFileInput/FormFileInput'
import { FormTextField } from '@/modules/form/components/FormTextField/FormTextField'
import { Form } from '@/modules/form/Form'
import { isUrl } from '@/modules/form/validate'

interface AddMediaFormValues {
  files?: FileList
  sourceUrl?: string
  caption?: string
}

interface AddMediaFormProps {
  onDismiss: () => void
  onSuccess?: (mediaInfo: MediaDetails, caption?: string) => void
  accept?: string
}

/**
 * Add media form.
 */
export function AddMediaForm(props: AddMediaFormProps): JSX.Element {
  const auth = useAuth()
  const uploadMedia = useUploadMedia()
  const importMedia = useImportMedia()
  const toast = useToast()

  const accept = props.accept ?? 'image/*,video/*'

  function onSubmit(values: AddMediaFormValues) {
    if (auth.session?.accessToken === undefined) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

    const caption = values.caption

    const callbacks = {
      onSuccess(mediaInfo: MediaDetails) {
        props.onSuccess?.(mediaInfo, caption)
        toast.success('Sucessfully added media.')
      },
      onError(error: unknown) {
        toast.error(
          error instanceof MediaError ? error.message : 'Failed to add media.',
        )
      },
      onSettled() {
        props.onDismiss()
      },
    }

    if (values.files !== undefined) {
      if (values.files.length === 0) return
      const file = values.files[0]
      const formData = new FormData()
      formData.set('file', file)
      uploadMedia.mutate(
        [
          // @ts-expect-error openapi document is wrong
          undefined,
          {
            token: auth.session.accessToken,
            hooks: {
              request(_request) {
                const request = new Request(_request, { body: formData })
                return request
              },
            },
          },
        ],
        callbacks,
      )
    } else {
      importMedia.mutate(
        [values, { token: auth.session.accessToken }],
        callbacks,
      )
    }
  }

  function onValidate(values: Partial<AddMediaFormValues>) {
    const errors: Partial<Record<keyof typeof values, any>> = {}

    if (values.sourceUrl !== undefined && !isUrl(values.sourceUrl)) {
      errors.sourceUrl = 'Must be a valid URL.'
    }
    if (
      values.sourceUrl !== undefined &&
      values.files !== undefined &&
      values.files.length > 0
    ) {
      errors.sourceUrl = errors.files =
        'Please choose between uploading a file, or importing a URL.'
    }

    return errors
  }

  return (
    <Form onSubmit={onSubmit} validate={onValidate}>
      {({ handleSubmit, pristine, invalid, submitting }) => {
        return (
          <form
            noValidate
            className="flex flex-col space-y-6"
            onSubmit={handleSubmit}
          >
            <FormFileInput
              name="files"
              accept={accept}
              label="Upload media"
              variant="form"
              style={{ flex: 1 }}
            />
            <p>or</p>
            <FormTextField
              name="sourceUrl"
              label="Import media"
              variant="form"
              style={{ flex: 1 }}
              placeholder="https://"
            />
            <FormTextField
              name="caption"
              label="Caption"
              variant="form"
              style={{ flex: 1 }}
            />
            <div className="flex justify-end space-x-12">
              <Button variant="link" onPress={props.onDismiss}>
                Cancel
              </Button>
              <Button
                type="submit"
                variant="gradient"
                isLoading={uploadMedia.isLoading || importMedia.isLoading}
                isDisabled={
                  pristine ||
                  invalid ||
                  submitting ||
                  uploadMedia.isLoading ||
                  importMedia.isLoading
                }
              >
                Add
              </Button>
            </div>
          </form>
        )
      }}
    </Form>
  )
}