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

89 lines
2.3 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-25 16:42:46 +01:00
import { useIntl } from 'react-intl';
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';
2023-01-25 16:42:46 +01:00
import { labels, messages } from 'components/messages';
2020-08-08 05:36:57 +02:00
2023-01-06 07:56:36 +01:00
const generateId = () => getRandomChars(16);
2023-01-10 08:59:26 +01:00
export default function ShareUrl({ websiteId, data, onSave }) {
2023-01-25 16:42:46 +01:00
const { formatMessage } = useIntl();
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-21 02:12:53 +01:00
() => `${process.env.analyticsUrl || 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-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
);
}