// Read-only share link for the open project: status, enable, change its rules (expiry, passcode), revoke, copy. import { useEffect, useState } from 'react'; import { disableSharing, enableSharing, getShareStatus } from '../syncService.js'; export function useShareLink(projectId) { const [shareToken, setShareToken] = useState(null); const [expiresAt, setExpiresAt] = useState(null); const [hasPasscode, setHasPasscode] = useState(false); const [revealAt, setRevealAt] = useState(null); const [shareBusy, setShareBusy] = useState(false); const [shareCopied, setShareCopied] = useState(false); const [shareError, setShareError] = useState(''); const apply = (data) => { setShareToken(data.shareToken ?? null); setExpiresAt(data.expiresAt ?? null); setHasPasscode(!!data.hasPasscode); setRevealAt(data.revealAt ?? null); }; useEffect(() => { setShareToken(null); setExpiresAt(null); setHasPasscode(false); setRevealAt(null); setShareError(''); if (!projectId) return undefined; let active = true; getShareStatus(projectId).then((result) => { if (active && result.ok) apply(result.data); }); return () => { active = false; }; }, [projectId]); const shareUrl = shareToken ? `${window.location.origin}${window.location.pathname}?share=${shareToken}` : ''; // Turns the link on, or changes its rules: { expiresInDays?: number | null, passcode?: string | null, revealAt?: number | null } const enable = async (options = {}) => { setShareBusy(true); setShareError(''); const result = await enableSharing(projectId, options); setShareBusy(false); if (result.ok) apply(result.data); else setShareError(result.error ?? 'Could not save the link settings.'); return result.ok; }; const revoke = async () => { if (!window.confirm('Revoke this share link? Anyone using it will lose access immediately.')) return; setShareBusy(true); const result = await disableSharing(projectId); setShareBusy(false); if (result.ok) apply({}); }; const copy = () => { if (!shareUrl) return; navigator.clipboard.writeText(shareUrl).then(() => { setShareCopied(true); window.setTimeout(() => setShareCopied(false), 2000); }); }; return { shareToken, shareUrl, expiresAt, hasPasscode, revealAt, shareBusy, shareCopied, shareError, enable, revoke, copy }; }