import { useEffect, useRef, useState } from 'react'; import type { Article } from '../api/articles'; interface ShareButtonProps { article: Pick; className?: string; } export function ShareButton({ article, className = 'icon-btn' }: ShareButtonProps) { const [isOpen, setIsOpen] = useState(false); const [copied, setCopied] = useState(false); const menuRef = useRef(null); const url = article.url || window.location.href; // Escape closes only the menu, not the reader behind it. useEffect(() => { if (!isOpen) return; const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopImmediatePropagation(); setIsOpen(false); } }; window.addEventListener('keydown', onKey, true); menuRef.current?.querySelector('[role="menuitem"]')?.focus(); return () => window.removeEventListener('keydown', onKey, true); }, [isOpen]); const handleShare = async () => { if (navigator.share) { try { await navigator.share({ title: article.title, text: article.excerpt?.slice(0, 120), url }); return; } catch (err) { if ((err as DOMException)?.name === 'AbortError') return; } } setIsOpen((o) => !o); }; const copyToClipboard = async () => { try { await navigator.clipboard.writeText(url); setCopied(true); setTimeout(() => setCopied(false), 2000); } finally { setIsOpen(false); } }; const openLink = (href: string) => { window.open(href, '_blank', 'noopener,noreferrer'); setIsOpen(false); }; const enc = encodeURIComponent; const items = [ { label: 'E-mail', href: `mailto:?subject=${enc(article.title)}&body=${enc(url)}` }, { label: 'WhatsApp', href: `https://wa.me/?text=${enc(`${article.title} ${url}`)}` }, { label: 'X / Twitter', href: `https://twitter.com/intent/tweet?text=${enc(article.title)}&url=${enc(url)}` }, { label: 'LinkedIn', href: `https://www.linkedin.com/sharing/share-offsite/?url=${enc(url)}` }, ]; return (
{copied && ( Lien copiƩ )} {isOpen && ( <>
setIsOpen(false)} />
{items.map((it) => ( ))}
)}
); }