misc_pterodactyl-panel/resources/scripts/components/admin/locations/NewLocationButton.tsx

113 lines
4.4 KiB
TypeScript
Raw Normal View History

2021-01-06 22:39:23 +00:00
import React, { useState } from 'react';
import Button from '@/components/elements/Button';
import Field from '@/components/elements/Field';
import Modal from '@/components/elements/Modal';
import FlashMessageRender from '@/components/FlashMessageRender';
import useFlash from '@/plugins/useFlash';
import { Form, Formik, FormikHelpers } from 'formik';
import tw from 'twin.macro';
import { object, string } from 'yup';
import createLocation from '@/api/admin/locations/createLocation';
import getLocations from '@/api/admin/locations/getLocations';
interface Values {
short: string,
long: string,
}
const schema = object().shape({
short: string()
.required('A location short name must be provided.')
.max(32, 'Location short name must not exceed 32 characters.'),
long: string()
.max(255, 'Location long name must not exceed 255 characters.'),
});
export default () => {
const [ visible, setVisible ] = useState(false);
const { clearFlashes, clearAndAddHttpError } = useFlash();
const { mutate } = getLocations();
const submit = ({ short, long }: Values, { setSubmitting }: FormikHelpers<Values>) => {
clearFlashes('location:create');
setSubmitting(true);
createLocation(short, long)
2021-09-10 21:26:02 +00:00
.then(async (location) => {
await mutate(data => ({ ...data!, items: data!.items.concat(location) }), false);
2021-01-06 22:39:23 +00:00
setVisible(false);
})
.catch(error => {
2021-01-08 17:02:49 +00:00
clearAndAddHttpError({ key: 'location:create', error });
2021-01-06 22:39:23 +00:00
setSubmitting(false);
});
};
return (
<>
<Formik
onSubmit={submit}
initialValues={{ short: '', long: '' }}
validationSchema={schema}
>
{
({ isSubmitting, resetForm }) => (
<Modal
visible={visible}
dismissable={!isSubmitting}
showSpinnerOverlay={isSubmitting}
onDismissed={() => {
resetForm();
setVisible(false);
}}
>
<FlashMessageRender byKey={'location:create'} css={tw`mb-6`}/>
<h2 css={tw`mb-6 text-2xl text-neutral-100`}>New Location</h2>
2021-01-06 22:39:23 +00:00
<Form css={tw`m-0`}>
<Field
type={'string'}
id={'short'}
name={'short'}
label={'Short'}
description={'A short name used to identify this location.'}
autoFocus
2021-01-06 22:39:23 +00:00
/>
<div css={tw`mt-6`}>
<Field
type={'string'}
id={'long'}
name={'long'}
label={'Long'}
description={'A long name for this location.'}
/>
</div>
<div css={tw`flex flex-wrap justify-end mt-6`}>
<Button
type={'button'}
isSecondary
css={tw`w-full sm:w-auto sm:mr-2`}
onClick={() => setVisible(false)}
>
Cancel
</Button>
<Button css={tw`w-full mt-4 sm:w-auto sm:mt-0`} type={'submit'}>
Create Location
</Button>
</div>
</Form>
</Modal>
)
}
</Formik>
<Button type={'button'} size={'large'} css={tw`h-10 px-4 py-0 whitespace-nowrap`} onClick={() => setVisible(true)}>
2021-01-06 22:39:23 +00:00
New Location
</Button>
</>
);
};