WorkflowCreateForm.tsx 7.13 KB
Newer Older
1
import type { Config as FormConfig } from 'final-form'
Stefan Probst's avatar
Stefan Probst committed
2
import { useRouter } from 'next/router'
3
4
import type { ReactNode } from 'react'
import { Fragment, useState } from 'react'
Stefan Probst's avatar
Stefan Probst committed
5
import { useQueryClient } from 'react-query'
6
7
8
9
10
11
import {
  useCreateWorkflow,
  useGetLoggedInUser,
  WorkflowCore,
  WorkflowDto,
} from '@/api/sshoc'
Stefan Probst's avatar
Stefan Probst committed
12
import type { ItemCategory, ItemSearchQuery } from '@/api/sshoc/types'
Stefan Probst's avatar
Stefan Probst committed
13
14
15
16
17
import { ActorsFormSection } from '@/components/item/ActorsFormSection/ActorsFormSection'
import { MainFormSection } from '@/components/item/MainFormSection/MainFormSection'
import { PropertiesFormSection } from '@/components/item/PropertiesFormSection/PropertiesFormSection'
import { RelatedItemsFormSection } from '@/components/item/RelatedItemsFormSection/RelatedItemsFormSection'
import { SourceFormSection } from '@/components/item/SourceFormSection/SourceFormSection'
18
import { WorkflowStepsFormSection } from '@/components/item/WorkflowStepsFormSection/WorkflowStepsFormSection'
Stefan Probst's avatar
Stefan Probst committed
19
20
import { Button } from '@/elements/Button/Button'
import { useToast } from '@/elements/Toast/useToast'
Stefan Probst's avatar
Stefan Probst committed
21
import { validateCommonFormFields } from '@/lib/sshoc/validateCommonFormFields'
Stefan Probst's avatar
Stefan Probst committed
22
23
import { useAuth } from '@/modules/auth/AuthContext'
import { Form } from '@/modules/form/Form'
24
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
Stefan Probst's avatar
Stefan Probst committed
25

Stefan Probst's avatar
Stefan Probst committed
26
27
28
export interface ItemFormValues extends WorkflowCore {
  draft?: boolean
}
Stefan Probst's avatar
Stefan Probst committed
29
30
31
32
33
34
35
36
37
38
39
40

export interface ItemFormProps<T> {
  category: ItemCategory
  initialValues?: Partial<T>
}

/**
 * Item edit form.
 */
export function ItemForm(props: ItemFormProps<ItemFormValues>): JSX.Element {
  const { category, initialValues } = props

41
  const categoryLabel = getSingularItemCategoryLabel(category)
Stefan Probst's avatar
Stefan Probst committed
42

Stefan Probst's avatar
Stefan Probst committed
43
44
45
46
47
  const useItemMutation = useCreateWorkflow

  const toast = useToast()
  const router = useRouter()
  const auth = useAuth()
48
49
50
51
52
  const user = useGetLoggedInUser()
  const isAllowedToPublish =
    user.data?.role !== undefined
      ? ['administrator', 'moderator'].includes(user.data.role)
      : false
Stefan Probst's avatar
Stefan Probst committed
53
54
55
  const queryClient = useQueryClient()
  const create = useItemMutation({
    onSuccess(data: WorkflowDto) {
56
57
58
59
60
      toast.success(
        `Successfully ${
          isAllowedToPublish ? 'published' : 'submitted'
        } ${categoryLabel}.`,
      )
Stefan Probst's avatar
Stefan Probst committed
61
62
63
64
65
66
67
68
69
70
71

      queryClient.invalidateQueries({
        queryKey: ['itemSearch'],
      })
      queryClient.invalidateQueries({
        queryKey: ['getWorkflows'],
      })
      // queryClient.invalidateQueries({
      //   queryKey: ['getWorkflow', { id: data.persistentId }],
      // })

Stefan Probst's avatar
Stefan Probst committed
72
73
74
75
76
77
78
79
80
81
82
83
84
      /**
       * if the item is published (i.e. submitted as admin), redirect to details page.
       */
      if (data.status === 'approved') {
        router.push({ pathname: `/${data.category}/${data.persistentId}` })
      } else {
        // TODO: redirect to separate page explaining that the submmited item is in moderation queue
        const query: ItemSearchQuery = {
          categories: [data.category!],
          order: ['label'],
        }
        router.push({ pathname: '/search', query })
      }
Stefan Probst's avatar
Stefan Probst committed
85
86
    },
    onError() {
87
88
89
90
91
      toast.error(
        `Failed to ${
          isAllowedToPublish ? 'publish' : 'submit'
        } ${categoryLabel}.`,
      )
Stefan Probst's avatar
Stefan Probst committed
92
93
94
    },
  })

Stefan Probst's avatar
Stefan Probst committed
95
  function onSubmit({ draft, ...values }: ItemFormValues) {
Stefan Probst's avatar
Stefan Probst committed
96
97
98
99
100
101
102
103
104
105
106
107
    if (auth.session?.accessToken == null) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

    /**
     * Backend crashes with `source: {}`.
     */
    if (values.source && values.source.id === undefined) {
      delete values.source
    }

Stefan Probst's avatar
Stefan Probst committed
108
109
110
111
112
    return create.mutateAsync([
      { draft },
      values,
      { token: auth.session.accessToken },
    ])
Stefan Probst's avatar
Stefan Probst committed
113
114
  }

115
  function onValidateWorkflow(values: Partial<ItemFormValues>) {
Stefan Probst's avatar
Stefan Probst committed
116
117
    const errors: Partial<Record<keyof typeof values, string>> = {}

Stefan Probst's avatar
Stefan Probst committed
118
    validateCommonFormFields(values, errors)
Stefan Probst's avatar
Stefan Probst committed
119
120
121
122
123
124
125
126

    return errors
  }

  function onCancel() {
    router.push('/')
  }

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
  /**
   *  Multi-page form.
   * */
  const [state, setState] = useState({ page: 0, values: initialValues })

  const pages = [
    <FormPage key="workflow-page" onValidate={onValidateWorkflow}>
      <MainFormSection />
      <ActorsFormSection />
      <PropertiesFormSection />
      <RelatedItemsFormSection />
      <SourceFormSection />
    </FormPage>,
    <FormPage key="steps-page">
      <WorkflowStepsFormSection />
    </FormPage>,
  ]

  const activePage = pages[state.page]
  const isLastPage = state.page === pages.length - 1

  function nextPage(values: Partial<ItemFormValues>) {
    setState((state) => ({
      values,
      page: Math.min(state.page + 1, pages.length - 1),
    }))
  }

  function previousPage() {
    setState((state) => ({
      values: state.values,
      page: Math.max(state.page - 1, 0),
    }))
  }

  function handleSubmit(values: Partial<ItemFormValues>) {
    if (isLastPage) {
      return onSubmit(values)
    } else {
      nextPage(values)
    }
  }

  function validate(values: Partial<ItemFormValues>) {
    return typeof activePage.props.onValidate === 'function'
      ? activePage.props.onValidate(values)
      : undefined
  }

Stefan Probst's avatar
Stefan Probst committed
176
177
  return (
    <Form
178
179
180
      onSubmit={handleSubmit}
      validate={validate}
      initialValues={state.values}
Stefan Probst's avatar
Stefan Probst committed
181
    >
Stefan Probst's avatar
Stefan Probst committed
182
      {({ handleSubmit, form, pristine, invalid, submitting }) => {
Stefan Probst's avatar
Stefan Probst committed
183
184
185
186
187
188
        return (
          <form
            onSubmit={handleSubmit}
            noValidate
            className="flex flex-col space-y-12"
          >
189
            {pages[state.page]}
Stefan Probst's avatar
Stefan Probst committed
190
            <div className="flex items-center justify-end space-x-6">
191
              <pre>{JSON.stringify(pristine)}</pre>
Stefan Probst's avatar
Stefan Probst committed
192
193
194
              <Button onPress={onCancel} variant="link">
                Cancel
              </Button>
195
196
197
198
199
200
201
202
203
204
205
              {state.page > 0 ? (
                <Button onPress={previousPage}>Previous</Button>
              ) : null}
              {isLastPage ? (
                <Fragment>
                  <Button
                    type="submit"
                    onPress={() => {
                      form.change('draft', true)
                    }}
                    isDisabled={
206
207
                      /* FIXME: handle `pristine` for multi-step form || */
                      invalid || submitting || create.isLoading
208
209
210
211
212
213
214
215
216
217
218
                    }
                    variant="link"
                  >
                    Save as draft
                  </Button>
                  <Button
                    type="submit"
                    onPress={() => {
                      form.change('draft', undefined)
                    }}
                    isDisabled={
219
220
                      /* FIXME: pristine || */
                      invalid || submitting || create.isLoading
221
222
223
224
225
226
227
228
229
230
                    }
                  >
                    {isAllowedToPublish ? 'Publish' : 'Submit'}
                  </Button>
                </Fragment>
              ) : (
                <Button type="submit" isDisabled={invalid}>
                  Next
                </Button>
              )}
Stefan Probst's avatar
Stefan Probst committed
231
232
233
234
235
236
237
            </div>
          </form>
        )
      }}
    </Form>
  )
}
238
239
240
241
242
243
244
245
246

interface FormPageProps {
  onValidate?: FormConfig<ItemFormValues>['validate']
  children: ReactNode
}

function FormPage(props: FormPageProps) {
  return <Fragment>{props.children}</Fragment>
}