umami/components/forms/DeleteForm.js

100 lines
2.8 KiB
JavaScript
Raw Normal View History

import React, { useState } from 'react';
2020-10-01 07:34:16 +02:00
import { FormattedMessage } from 'react-intl';
import { useRouter } from 'next/router';
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-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 }) {
2020-10-01 07:34:16 +02:00
const { basePath } = useRouter();
const [message, setMessage] = useState();
2020-08-09 11:03:37 +02:00
const handleSubmit = async ({ type, id }) => {
2020-10-01 07:34:16 +02:00
const { ok, data } = await del(`${basePath}/api/${type}/${id}`);
2020-10-01 07:34:16 +02:00
if (ok) {
onSave();
} else {
2020-10-01 07:34:16 +02:00
setMessage(
data || <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>
<div>
<Field name="confirmation" type="text" />
<FormError name="confirmation" />
</div>
</FormRow>
<FormButtons>
2020-09-13 10:26:54 +02:00
<Button
type="submit"
variant="danger"
disabled={props.values.confirmation !== CONFIRMATION_WORD}
>
2020-10-13 07:53:59 +02:00
<FormattedMessage id="label.delete" defaultMessage="Delete" />
2020-09-06 02:27:01 +02:00
</Button>
<Button onClick={onClose}>
2020-10-13 07:53:59 +02:00
<FormattedMessage id="label.cancel" defaultMessage="Cancel" />
</Button>
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
);
}