umami/components/forms/WebsiteEditForm.js

86 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-08-07 11:27:12 +02:00
import React, { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import { post } from 'lib/web';
2020-08-08 05:36:57 +02:00
import Button from 'components/common/Button';
2020-08-07 11:27:12 +02:00
import FormLayout, {
FormButtons,
FormError,
FormMessage,
FormRow,
} from 'components/layout/FormLayout';
import Checkbox from 'components/common/Checkbox';
import { DOMAIN_REGEX } from 'lib/constants';
2020-08-07 11:27:12 +02:00
2020-08-09 08:48:43 +02:00
const initialValues = {
name: '',
domain: '',
2020-08-15 10:17:15 +02:00
public: false,
2020-08-09 08:48:43 +02:00
};
2020-08-07 11:27:12 +02:00
const validate = ({ name, domain }) => {
const errors = {};
if (!name) {
errors.name = 'Required';
}
if (!domain) {
errors.domain = 'Required';
} else if (!DOMAIN_REGEX.test(domain)) {
errors.domain = 'Invalid domain';
2020-08-07 11:27:12 +02:00
}
return errors;
};
2020-08-08 05:36:57 +02:00
export default function WebsiteEditForm({ values, onSave, onClose }) {
2020-08-07 11:27:12 +02:00
const [message, setMessage] = useState();
const handleSubmit = async values => {
const response = await post(`/api/website`, values);
2020-08-09 11:03:37 +02:00
if (typeof response !== 'string') {
2020-08-07 11:27:12 +02:00
onSave();
} else {
2020-08-09 11:03:37 +02:00
setMessage('Something went wrong');
2020-08-07 11:27:12 +02:00
}
};
return (
<FormLayout>
2020-08-09 08:48:43 +02:00
<Formik
2020-08-17 06:28:54 +02:00
initialValues={{ ...initialValues, ...values, enable_share_url: !!values?.share_id }}
2020-08-09 08:48:43 +02:00
validate={validate}
onSubmit={handleSubmit}
>
2020-08-07 11:27:12 +02:00
{() => (
<Form>
<FormRow>
<label htmlFor="name">Name</label>
<Field name="name" type="text" />
<FormError name="name" />
</FormRow>
<FormRow>
<label htmlFor="domain">Domain</label>
<Field name="domain" type="text" />
<FormError name="domain" />
</FormRow>
2020-08-15 10:17:15 +02:00
<FormRow>
<label></label>
2020-08-17 06:28:54 +02:00
<Field name="enable_share_url">
{({ field }) => <Checkbox {...field} label="Enable share URL" />}
2020-08-15 10:17:15 +02:00
</Field>
</FormRow>
2020-08-07 11:27:12 +02:00
<FormButtons>
<Button type="submit" variant="action">
Save
</Button>
2020-08-07 11:27:12 +02:00
<Button onClick={onClose}>Cancel</Button>
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
);
}