umami/components/pages/settings/websites/ShareUrl.js

95 lines
2.4 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';
2023-07-27 23:14:55 +02:00
import { useRouter } from 'next/router';
import useApi from 'hooks/useApi';
2023-03-22 22:05:55 +01:00
import useMessages from 'hooks/useMessages';
2020-08-08 05:36:57 +02:00
2023-01-06 07:56:36 +01:00
const generateId = () => getRandomChars(16);
2023-04-21 17:00:42 +02:00
export function ShareUrl({ websiteId, data, onSave }) {
2023-03-22 22:05:55 +01:00
const { formatMessage, labels, messages } = useMessages();
const { name, shareId } = data;
const [id, setId] = useState(shareId);
2023-01-06 07:56:36 +01:00
const { post, useMutation } = useApi();
2023-07-27 23:14:55 +02:00
const { basePath } = useRouter();
const { mutate, error } = useMutation(({ shareId }) =>
post(`/websites/${websiteId}`, { shareId }),
);
const ref = useRef(null);
const url = useMemo(
2023-07-27 23:14:55 +02:00
() =>
`${process.env.analyticsUrl || location.origin}${basePath}/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-25 16:42:46 +01:00
<>
<Toggle checked={Boolean(id)} onChecked={handleCheck} style={{ marginBottom: 30 }}>
{formatMessage(labels.enableShareUrl)}
</Toggle>
{id && (
2023-01-25 16:42:46 +01:00
<Form key={websiteId} ref={ref} onSubmit={handleSubmit} error={error} values={data}>
<FormRow>
2023-01-25 16:42:46 +01:00
<p>{formatMessage(messages.shareUrl)}</p>
2023-01-06 07:56:36 +01:00
<Flexbox gap={10}>
<TextField value={url} readOnly allowCopy />
2023-01-25 16:42:46 +01:00
<Button onClick={handleGenerate}>{formatMessage(labels.regenerate)}</Button>
2023-01-06 07:56:36 +01:00
</Flexbox>
</FormRow>
<FormButtons>
2023-01-25 16:42:46 +01:00
<SubmitButton variant="primary">{formatMessage(labels.save)}</SubmitButton>
</FormButtons>
2023-01-25 16:42:46 +01:00
</Form>
)}
2023-01-25 16:42:46 +01:00
</>
2020-08-08 05:36:57 +02:00
);
}
2023-04-21 17:00:42 +02:00
export default ShareUrl;