umami/components/pages/settings/teams/TeamEditForm.js

72 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-01-10 08:59:26 +01:00
import {
SubmitButton,
Form,
FormInput,
FormRow,
FormButtons,
TextField,
Button,
Flexbox,
} from 'react-basics';
import { getRandomChars } from 'next-basics';
import { useRef, useState } from 'react';
2022-12-28 05:20:44 +01:00
import useApi from 'hooks/useApi';
2023-03-22 22:05:55 +01:00
import useMessages from 'hooks/useMessages';
2023-01-10 08:59:26 +01:00
const generateId = () => getRandomChars(16);
2023-02-02 20:59:38 +01:00
export default function TeamEditForm({ teamId, data, onSave, readOnly }) {
2023-03-22 22:05:55 +01:00
const { formatMessage, labels } = useMessages();
2023-01-10 08:59:26 +01:00
const { post, useMutation } = useApi();
const { mutate, error } = useMutation(data => post(`/teams/${teamId}`, data));
const ref = useRef(null);
2023-01-10 08:59:26 +01:00
const [accessCode, setAccessCode] = useState(data.accessCode);
const handleSubmit = async data => {
mutate(data, {
onSuccess: async () => {
ref.current.reset(data);
onSave(data);
},
});
};
2023-01-10 08:59:26 +01:00
const handleRegenerate = () => {
const code = generateId();
ref.current.setValue('accessCode', code, {
shouldValidate: true,
shouldDirty: true,
});
setAccessCode(code);
};
return (
2023-01-31 06:44:07 +01:00
<Form ref={ref} onSubmit={handleSubmit} error={error} values={data} style={{ width: 600 }}>
2023-01-25 16:42:46 +01:00
<FormRow label={formatMessage(labels.teamId)}>
<TextField value={teamId} readOnly allowCopy />
</FormRow>
2023-01-25 16:42:46 +01:00
<FormRow label={formatMessage(labels.name)}>
2023-02-02 20:59:38 +01:00
{!readOnly && (
<FormInput name="name" rules={{ required: formatMessage(labels.required) }}>
<TextField />
</FormInput>
)}
{readOnly && data.name}
2023-01-06 07:56:36 +01:00
</FormRow>
2023-01-25 16:42:46 +01:00
<FormRow label={formatMessage(labels.accessCode)}>
2023-01-10 08:59:26 +01:00
<Flexbox gap={10}>
<TextField value={accessCode} readOnly allowCopy />
2023-02-02 20:59:38 +01:00
{!readOnly && (
<Button onClick={handleRegenerate}>{formatMessage(labels.regenerate)}</Button>
)}
2023-01-10 08:59:26 +01:00
</Flexbox>
</FormRow>
2023-02-02 20:59:38 +01:00
{!readOnly && (
<FormButtons>
<SubmitButton variant="primary">{formatMessage(labels.save)}</SubmitButton>
</FormButtons>
)}
</Form>
);
}