403 lines
12 KiB
TypeScript
403 lines
12 KiB
TypeScript
/**
|
|
* Preview dialog: load share payload, then share (native / social / copy) or download PNG.
|
|
* Desktop browsers rarely support Web Share with files — we must not silently download.
|
|
*/
|
|
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
|
|
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
|
|
import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded';
|
|
import FacebookRoundedIcon from '@mui/icons-material/FacebookRounded';
|
|
import ShareRoundedIcon from '@mui/icons-material/ShareRounded';
|
|
import TelegramIcon from '@mui/icons-material/Telegram';
|
|
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
|
|
import XIcon from '@mui/icons-material/X';
|
|
import {
|
|
Alert,
|
|
Box,
|
|
Button,
|
|
CircularProgress,
|
|
Dialog,
|
|
DialogActions,
|
|
DialogContent,
|
|
DialogTitle,
|
|
IconButton,
|
|
ListItemIcon,
|
|
ListItemText,
|
|
Menu,
|
|
MenuItem,
|
|
Stack,
|
|
Typography,
|
|
} from '@mui/material';
|
|
import { toPng } from 'html-to-image';
|
|
import { useEffect, useRef, useState, type MouseEvent } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import axios from 'axios';
|
|
import { copyTextToClipboard } from '../../shared/utils/clipboard';
|
|
import { fetchShareCardPayload, fetchWalletShareCardPayload } from './hooks';
|
|
import { ShareResultCard } from './ShareResultCard';
|
|
import type { ShareCardPayload } from './types';
|
|
|
|
type Props = {
|
|
open: boolean;
|
|
betId?: string | null;
|
|
transactionId?: string | null;
|
|
onClose: () => void;
|
|
};
|
|
|
|
type NavShare = Navigator & {
|
|
share?: (data: ShareData) => Promise<void>;
|
|
canShare?: (data: ShareData) => boolean;
|
|
};
|
|
|
|
function errorMessage(e: unknown, fallback: string): string {
|
|
if (axios.isAxiosError(e)) {
|
|
const data = e.response?.data as { error?: string } | undefined;
|
|
if (data?.error) return data.error;
|
|
}
|
|
if (e instanceof Error && e.message) return e.message;
|
|
return fallback;
|
|
}
|
|
|
|
function canShareFiles(file: File): boolean {
|
|
const nav = navigator as NavShare;
|
|
if (typeof nav.share !== 'function') return false;
|
|
if (typeof nav.canShare !== 'function') return false;
|
|
try {
|
|
return nav.canShare({ files: [file] });
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function canShareUrlOnly(): boolean {
|
|
const nav = navigator as NavShare;
|
|
return typeof nav.share === 'function';
|
|
}
|
|
|
|
function shareCaption(inviteUrl: string): string {
|
|
return `Prediqo — ${inviteUrl}`;
|
|
}
|
|
|
|
async function tryNativeShare(opts: {
|
|
blob: Blob;
|
|
filename: string;
|
|
inviteUrl: string;
|
|
}): Promise<'shared' | 'cancelled' | 'unsupported'> {
|
|
const nav = navigator as NavShare;
|
|
if (typeof nav.share !== 'function') return 'unsupported';
|
|
|
|
const file = new File([opts.blob], opts.filename, { type: 'image/png' });
|
|
const withFiles = canShareFiles(file);
|
|
|
|
try {
|
|
if (withFiles) {
|
|
await nav.share({
|
|
files: [file],
|
|
title: 'Prediqo',
|
|
text: shareCaption(opts.inviteUrl),
|
|
});
|
|
return 'shared';
|
|
}
|
|
// Desktop / limited browsers: share invite link only (no silent download).
|
|
await nav.share({
|
|
title: 'Prediqo',
|
|
text: shareCaption(opts.inviteUrl),
|
|
url: opts.inviteUrl,
|
|
});
|
|
return 'shared';
|
|
} catch (e) {
|
|
// User dismissed the sheet — not a failure that should download.
|
|
if (e instanceof DOMException && e.name === 'AbortError') return 'cancelled';
|
|
return 'unsupported';
|
|
}
|
|
}
|
|
|
|
function downloadBlob(blob: Blob, filename: string): void {
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = filename;
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
export function ShareResultDialog({ open, betId, transactionId, onClose }: Props) {
|
|
const { t } = useTranslation();
|
|
const cardRef = useRef<HTMLDivElement>(null);
|
|
const [payload, setPayload] = useState<ShareCardPayload | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [hint, setHint] = useState<string | null>(null);
|
|
const [menuAnchor, setMenuAnchor] = useState<null | HTMLElement>(null);
|
|
const [cachedExport, setCachedExport] = useState<{
|
|
blob: Blob;
|
|
filename: string;
|
|
} | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!open || (!betId && !transactionId)) {
|
|
setPayload(null);
|
|
setError(null);
|
|
setHint(null);
|
|
setCachedExport(null);
|
|
setMenuAnchor(null);
|
|
setLoading(false);
|
|
setBusy(false);
|
|
return;
|
|
}
|
|
let cancelled = false;
|
|
// Always drop the previous card before loading the next target.
|
|
setPayload(null);
|
|
setCachedExport(null);
|
|
setHint(null);
|
|
setLoading(true);
|
|
setError(null);
|
|
const targetId = transactionId ?? betId!;
|
|
const loader = transactionId
|
|
? fetchWalletShareCardPayload(transactionId)
|
|
: fetchShareCardPayload(betId!);
|
|
void loader
|
|
.then((data) => {
|
|
if (cancelled) return;
|
|
// Guard against out-of-order responses if the target changed mid-flight.
|
|
const dataId =
|
|
data.kind === 'wallet' ? data.transactionId : data.betId;
|
|
if (dataId !== targetId) return;
|
|
setPayload(data);
|
|
})
|
|
.catch((e: unknown) => {
|
|
if (!cancelled) {
|
|
setError(errorMessage(e, t('shareCard.loadError')));
|
|
setPayload(null);
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [open, betId, transactionId, t]);
|
|
|
|
useEffect(() => {
|
|
setCachedExport(null);
|
|
}, [payload]);
|
|
|
|
const buildExport = async () => {
|
|
if (!cardRef.current || !payload) return null;
|
|
if (cachedExport) return cachedExport;
|
|
const dataUrl = await toPng(cardRef.current, {
|
|
cacheBust: true,
|
|
pixelRatio: 2,
|
|
backgroundColor: '#0B1220',
|
|
});
|
|
const res = await fetch(dataUrl);
|
|
const blob = await res.blob();
|
|
const id =
|
|
payload.kind === 'wallet'
|
|
? payload.transactionId.slice(0, 8)
|
|
: payload.betId.slice(0, 8);
|
|
const tag = payload.kind === 'wallet' ? payload.operationType : payload.status;
|
|
const filename = `prediqo-${tag}-${id}.png`;
|
|
const next = { blob, filename };
|
|
setCachedExport(next);
|
|
return next;
|
|
};
|
|
|
|
const onDownload = async () => {
|
|
if (!payload) return;
|
|
setBusy(true);
|
|
setHint(null);
|
|
try {
|
|
const exported = await buildExport();
|
|
if (!exported) throw new Error('export');
|
|
downloadBlob(exported.blob, exported.filename);
|
|
setHint(t('shareCard.downloaded'));
|
|
} catch {
|
|
setHint(t('shareCard.exportFailed'));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const onShareClick = async (event: MouseEvent<HTMLElement>) => {
|
|
if (!payload) return;
|
|
setBusy(true);
|
|
setHint(null);
|
|
try {
|
|
const exported = await buildExport();
|
|
if (!exported) throw new Error('export');
|
|
|
|
// Prefer native sheet when available (mobile / some desktops).
|
|
if (canShareUrlOnly()) {
|
|
const result = await tryNativeShare({
|
|
blob: exported.blob,
|
|
filename: exported.filename,
|
|
inviteUrl: payload.registerUrl,
|
|
});
|
|
if (result === 'shared') {
|
|
setHint(t('shareCard.sharedOrDownloaded'));
|
|
return;
|
|
}
|
|
if (result === 'cancelled') return;
|
|
}
|
|
|
|
// Fallback: explicit share menu (never silent download).
|
|
setMenuAnchor(event.currentTarget);
|
|
setHint(t('shareCard.nativeShareUnavailable'));
|
|
} catch {
|
|
setHint(t('shareCard.exportFailed'));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const closeMenu = () => setMenuAnchor(null);
|
|
|
|
const copyLink = async () => {
|
|
if (!payload) return;
|
|
closeMenu();
|
|
const ok = await copyTextToClipboard(payload.registerUrl);
|
|
setHint(ok ? t('shareCard.linkCopied') : t('shareCard.exportFailed'));
|
|
};
|
|
|
|
const openSocial = (url: string) => {
|
|
closeMenu();
|
|
window.open(url, '_blank', 'noopener,noreferrer');
|
|
};
|
|
|
|
const inviteUrl = payload?.registerUrl ?? '';
|
|
const encodedUrl = encodeURIComponent(inviteUrl);
|
|
const encodedText = encodeURIComponent(shareCaption(inviteUrl));
|
|
|
|
return (
|
|
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
|
<DialogTitle sx={{ pr: 6 }}>
|
|
{t('shareCard.previewTitle')}
|
|
<IconButton
|
|
onClick={onClose}
|
|
sx={{ position: 'absolute', right: 8, top: 8 }}
|
|
aria-label={t('shareCard.cancel')}
|
|
>
|
|
<CloseRoundedIcon />
|
|
</IconButton>
|
|
</DialogTitle>
|
|
<DialogContent>
|
|
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
|
|
{t('shareCard.previewHint')}
|
|
</Typography>
|
|
{loading && (
|
|
<Box sx={{ display: 'grid', placeItems: 'center', py: 6 }}>
|
|
<CircularProgress size={32} />
|
|
</Box>
|
|
)}
|
|
{error && !loading && <Alert severity="error">{error}</Alert>}
|
|
{!loading && payload ? (
|
|
<Stack sx={{ alignItems: 'center' }}>
|
|
<ShareResultCard
|
|
key={
|
|
payload.kind === 'wallet'
|
|
? `${payload.transactionId}-${payload.amountSignedDisplay}`
|
|
: `${payload.betId}-${payload.resultSignedDisplay}-${payload.status}`
|
|
}
|
|
payload={payload}
|
|
cardRef={cardRef}
|
|
/>
|
|
</Stack>
|
|
) : null}
|
|
{hint && (
|
|
<Alert severity="info" sx={{ mt: 2 }}>
|
|
{hint}
|
|
</Alert>
|
|
)}
|
|
</DialogContent>
|
|
<DialogActions sx={{ px: 3, pb: 2, flexWrap: 'wrap', gap: 1 }}>
|
|
<Button onClick={onClose}>{t('shareCard.cancel')}</Button>
|
|
<Button
|
|
startIcon={<DownloadRoundedIcon />}
|
|
disabled={!payload || busy}
|
|
onClick={() => void onDownload()}
|
|
>
|
|
{t('shareCard.download')}
|
|
</Button>
|
|
<Button
|
|
variant="contained"
|
|
startIcon={<ShareRoundedIcon />}
|
|
disabled={!payload || busy}
|
|
onClick={(e) => void onShareClick(e)}
|
|
>
|
|
{t('shareCard.share')}
|
|
</Button>
|
|
<Menu
|
|
anchorEl={menuAnchor}
|
|
open={Boolean(menuAnchor)}
|
|
onClose={closeMenu}
|
|
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
|
|
transformOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
|
>
|
|
<MenuItem disabled>
|
|
<ListItemText primary={t('shareCard.shareVia')} />
|
|
</MenuItem>
|
|
<MenuItem onClick={() => void copyLink()}>
|
|
<ListItemIcon>
|
|
<ContentCopyRoundedIcon fontSize="small" />
|
|
</ListItemIcon>
|
|
<ListItemText>{t('shareCard.copyLink')}</ListItemText>
|
|
</MenuItem>
|
|
<MenuItem
|
|
onClick={() =>
|
|
openSocial(`https://wa.me/?text=${encodedText}`)
|
|
}
|
|
>
|
|
<ListItemIcon>
|
|
<WhatsAppIcon fontSize="small" />
|
|
</ListItemIcon>
|
|
<ListItemText>{t('shareCard.shareWhatsApp')}</ListItemText>
|
|
</MenuItem>
|
|
<MenuItem
|
|
onClick={() =>
|
|
openSocial(`https://t.me/share/url?url=${encodedUrl}&text=${encodedText}`)
|
|
}
|
|
>
|
|
<ListItemIcon>
|
|
<TelegramIcon fontSize="small" />
|
|
</ListItemIcon>
|
|
<ListItemText>{t('shareCard.shareTelegram')}</ListItemText>
|
|
</MenuItem>
|
|
<MenuItem
|
|
onClick={() =>
|
|
openSocial(`https://twitter.com/intent/tweet?url=${encodedUrl}&text=${encodedText}`)
|
|
}
|
|
>
|
|
<ListItemIcon>
|
|
<XIcon fontSize="small" />
|
|
</ListItemIcon>
|
|
<ListItemText>{t('shareCard.shareX')}</ListItemText>
|
|
</MenuItem>
|
|
<MenuItem
|
|
onClick={() =>
|
|
openSocial(`https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`)
|
|
}
|
|
>
|
|
<ListItemIcon>
|
|
<FacebookRoundedIcon fontSize="small" />
|
|
</ListItemIcon>
|
|
<ListItemText>{t('shareCard.shareFacebook')}</ListItemText>
|
|
</MenuItem>
|
|
<MenuItem
|
|
onClick={() => {
|
|
closeMenu();
|
|
void onDownload();
|
|
}}
|
|
>
|
|
<ListItemIcon>
|
|
<DownloadRoundedIcon fontSize="small" />
|
|
</ListItemIcon>
|
|
<ListItemText>{t('shareCard.download')}</ListItemText>
|
|
</MenuItem>
|
|
</Menu>
|
|
</DialogActions>
|
|
</Dialog>
|
|
);
|
|
}
|