umami/components/forms/DeleteForm.js

88 lines
2.5 KiB
JavaScript
Raw Normal View History

import React, { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import { del } from 'lib/web';
2020-08-08 05:36:57 +02:00
import Button from 'components/common/Button';
import FormLayout, {
FormButtons,
FormError,
FormMessage,
FormRow,
} from 'components/layout/FormLayout';
2020-09-06 02:27:01 +02:00
import { FormattedMessage } from 'react-intl';
const validate = ({ confirmation }) => {
const errors = {};
if (confirmation !== 'DELETE') {
2020-09-06 02:27:01 +02:00
errors.confirmation = !confirmation ? (
<FormattedMessage id="label.required" defaultMessage="Required" />
) : (
<FormattedMessage id="label.invalid" defaultMessage="Invalid" />
);
}
return errors;
};
2020-08-09 11:03:37 +02:00
export default function DeleteForm({ values, onSave, onClose }) {
const [message, setMessage] = useState();
2020-08-09 11:03:37 +02:00
const handleSubmit = async ({ type, id }) => {
const response = await del(`/api/${type}/${id}`);
2020-08-09 11:03:37 +02:00
if (typeof response !== 'string') {
onSave();
} else {
2020-09-06 02:27:01 +02:00
setMessage(<FormattedMessage id="message.failure" defaultMessage="Something went wrong." />);
}
};
return (
<FormLayout>
<Formik
2020-08-08 05:36:57 +02:00
initialValues={{ confirmation: '', ...values }}
validate={validate}
onSubmit={handleSubmit}
>
{() => (
<Form>
<div>
2020-09-06 02:27:01 +02:00
<FormattedMessage
id="message.confirm-delete"
defaultMessage="Are your sure you want to delete {target}?"
values={{ target: <b>{values.name}</b> }}
/>
</div>
<div>
<FormattedMessage
id="message.delete-warning"
defaultMessage="All associated data will be deleted as well."
/>
</div>
<p>
2020-09-06 02:27:01 +02:00
<FormattedMessage
id="message.type-delete"
defaultMessage="Type {delete} in the box below to confirm."
values={{ delete: <b>DELETE</b> }}
/>
</p>
<FormRow>
2020-08-15 10:17:15 +02:00
<Field name="confirmation" type="text" />
<FormError name="confirmation" />
</FormRow>
<FormButtons>
<Button type="submit" variant="danger">
2020-09-06 02:27:01 +02:00
<FormattedMessage id="button.delete" defaultMessage="Delete" />
</Button>
<Button onClick={onClose}>
<FormattedMessage id="button.cancel" defaultMessage="Cancel" />
</Button>
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
);
}