umami/components/forms/ShareUrlForm.js

88 lines
2.1 KiB
JavaScript
Raw Normal View History

import {
Form,
FormRow,
2023-01-06 07:56:36 +01:00
FormButtons,
Flexbox,
TextField,
2023-01-06 07:56:36 +01:00
SubmitButton,
Button,
Toggle,
} from 'react-basics';
2023-01-06 07:56:36 +01:00
import { useEffect, useMemo, useRef, useState } from 'react';
import { getRandomChars } from 'next-basics';
import useApi from 'hooks/useApi';
2020-08-08 05:36:57 +02:00
2023-01-06 07:56:36 +01:00
const generateId = () => getRandomChars(16);
export default function ShareUrlForm({ websiteId, data, onSave }) {
const { name, shareId } = data;
const [id, setId] = useState(shareId);
2023-01-06 07:56:36 +01:00
const { post, useMutation } = useApi();
const { mutate, error } = useMutation(({ shareId }) =>
post(`/websites/${websiteId}`, { shareId }),
);
const ref = useRef(null);
const url = useMemo(
2023-01-06 07:56:36 +01:00
() => `${location.origin}/share/${id}/${encodeURIComponent(name)}`,
[id, name],
);
const handleSubmit = async data => {
mutate(data, {
onSuccess: async () => {
onSave(data);
ref.current.reset(data);
},
});
};
const handleGenerate = () => {
const id = generateId();
ref.current.setValue('shareId', id, {
shouldValidate: true,
shouldDirty: true,
});
setId(id);
};
2023-01-06 07:56:36 +01:00
const handleCheck = checked => {
const data = { shareId: checked ? generateId() : null };
mutate(data, {
onSuccess: async () => {
onSave(data);
},
});
setId(data.shareId);
};
useEffect(() => {
if (id && id !== shareId) {
ref.current.setValue('shareId', id);
}
}, [id, shareId]);
2020-08-08 05:36:57 +02:00
return (
2023-01-06 07:56:36 +01:00
<Form key={websiteId} ref={ref} onSubmit={handleSubmit} error={error} values={data}>
<FormRow>
<Toggle checked={Boolean(id)} onChecked={handleCheck}>
Enable share URL
</Toggle>
</FormRow>
{id && (
2023-01-06 07:56:36 +01:00
<>
<FormRow>
<p>Your website stats are publically available at the following URL:</p>
2023-01-06 07:56:36 +01:00
<Flexbox gap={10}>
<TextField value={url} readOnly allowCopy />
<Button onClick={handleGenerate}>Regenerate URL</Button>
</Flexbox>
</FormRow>
<FormButtons>
<SubmitButton variant="primary">Save</SubmitButton>
</FormButtons>
2023-01-06 07:56:36 +01:00
</>
)}
2023-01-06 07:56:36 +01:00
</Form>
2020-08-08 05:36:57 +02:00
);
}