umami/components/forms/DeleteForm.js

94 lines
2.7 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';
2020-09-13 10:26:54 +02:00
const CONFIRMATION_WORD = 'DELETE';
const validate = ({ confirmation }) => {
const errors = {};
2020-09-13 10:26:54 +02:00
if (confirmation !== CONFIRMATION_WORD) {
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}
>
2020-09-13 10:26:54 +02:00
{props => (
<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."
2020-09-13 10:26:54 +02:00
values={{ delete: <b>{CONFIRMATION_WORD}</b> }}
2020-09-06 02:27:01 +02:00
/>
</p>
<FormRow>
2020-08-15 10:17:15 +02:00
<Field name="confirmation" type="text" />
<FormError name="confirmation" />
</FormRow>
<FormButtons>
2020-09-13 10:26:54 +02:00
<Button
type="submit"
variant="danger"
disabled={props.values.confirmation !== CONFIRMATION_WORD}
>
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>
);
}