Newer
Older
import { CutterField, Template as TemplateDto } from 'lib/client/index';
import { FC, FormEventHandler, useCallback, useLayoutEffect, useRef, useState } from 'react';
import { useAuth } from 'react-oidc-context';
import { useProjectApi } from 'lib/useApi';
import { useMutation, useQuery } from '@tanstack/react-query';
import { AxiosRequestConfig } from 'axios';
import Form from 'components/template/Form';
import Button from 'components/Button';
import LoadingSpinner from 'components/LoadingSpinner';
const hasDefaultValue = (field: CutterField) => {
// TODO: type assertion because of api spec/generator issue
const defaultValue = field.default as string;
return defaultValue.length > 0;
};
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
type TemplateFormProps = {
template: TemplateDto;
};
const TemplateForm: FC<TemplateFormProps> = ({ template }) => {
const auth = useAuth();
const api = useProjectApi();
const fields = useQuery(['fields', template.id], () => api.fetchFields(template.id));
const generate = useMutation(
['generate', template.id],
(data: Record<string, string>) =>
api.generateProject(template.id, data, {
responseType: 'blob',
} as AxiosRequestConfig),
{
onSuccess: (data) => {
const link = document.createElement('a');
const blob = new Blob([data.data], { type: 'application/zip' });
link.href = URL.createObjectURL(blob);
link.download =
data.headers['content-disposition']?.replace(/attachment;\s*filename=/, '') ??
'cookiecutter.zip';
link.click();
},
}
);
const formSubmitButton = useRef<HTMLButtonElement>(null);
const missingFieldsModal = useRef<HTMLDialogElement>(null);
const [overrideMissingFieldsWarning, setOverrideMissingFieldsWarning] = useState(false);
const [emptyFields, setEmptyFields] = useState<string[]>([]);
const findMissingFields = useCallback(
(form: FormData) => {
if (!fields.isSuccess) {
throw new Error("Can't validate missing fields without fields");
}
// all fields that expect a value without default
const keysToCheck = fields.data.data
.filter((f) => f.type !== 'checkbox' && !hasDefaultValue(f))
.map((f) => f.name);
// all fields that are empty
return Array.from(form.entries())
.filter(([key, value]) => keysToCheck.includes(key) && value.length == 0)
.map(([key, _]) => key);
},
[fields.isSuccess, fields.data]
);
const handleSubmit: FormEventHandler<HTMLFormElement> = (e) => {
e.preventDefault();
if (!fields.isSuccess || auth.user?.access_token === undefined) {
return;
}
const form = new FormData(e.currentTarget);
if (!overrideMissingFieldsWarning) {
const emptyFields = findMissingFields(form);
if (emptyFields.length !== 0) {
setEmptyFields(emptyFields);
missingFieldsModal.current?.showModal();
setOverrideMissingFieldsWarning(true);
console.warn('Missing fields:', emptyFields);
return;
}
}
// TODO: get rid of type assertion, asserting because we have no files
const entries = Array.from(form.entries()).filter((entry) => entry[1].length > 0);
const json = Object.fromEntries(entries) as Record<string, string>;
generate.mutate(json);
};
useLayoutEffect(() => {
if (generate.isError && generate.error) {
document.getElementById('something-went-wrong')?.scrollIntoView({ behavior: 'smooth' });
}
}, [generate.error]);
return (
<div>
<form onSubmit={handleSubmit} className="mb-0">
<p>
Filling this web-form will generate a .zip file with the folders generated by
the cookiecutter.
</p>
<div>
{fields.isSuccess && (
<>
<Form fields={fields.data.data} flaggedFields={emptyFields} />
<div className="flex justify-center pt-2">
{auth.isAuthenticated && (
<Button
type="submit"
ref={formSubmitButton}
disabled={generate.isLoading}
>
Generate
</Button>
)}
{!auth.isAuthenticated && (
<Button
type="button"
onClick={() => auth.signinRedirect()}
variant="secondary"
>
Login
</Button>
)}
</div>
</>
)}
</div>
{(fields.isLoading || generate.isLoading) && (
<div className="w-full flex justify-center mb-4">
<LoadingSpinner />
</div>
)}
{generate.isError && (
<span className="text-error" id="something-went-wrong">
Something went wrong, please try again later.
<pre>
<code>{JSON.stringify(generate.error, null, 2)}</code>
</pre>
</span>
)}
</form>
<dialog id="missing-fields" ref={missingFieldsModal} className="modal p-3">
<p>
It looks like you haven't filled out all the fields. Are you sure you want
to submit the form?{' '}
</p>
<p>Missing fields:</p>
<ul>
{emptyFields.map((f) => (
<li key={f} style={{ marginBlock: '.1rem', listStyle: 'disc inside' }}>
{f}
</li>
))}
</ul>
<div className="flex justify-end flex-gap">
<Button
variant="secondary"
onClick={() => {
missingFieldsModal.current?.close();
setOverrideMissingFieldsWarning(false);
}}
>
Cancel
</Button>
<Button
variant="warning"
onClick={() => {
missingFieldsModal.current?.close();
// HACK: manually retrigger submission here, find a more proper way?
formSubmitButton.current?.click();
setOverrideMissingFieldsWarning(false);
}}
>
Submit
</Button>
</div>
</dialog>
</div>
);
};
export default TemplateForm;