import { __ } from '../lib/i18n'; import { useRef, useState, useEffect } from 'preact/hooks'; import { Icon } from './Icon'; export function commentPlainText(html: string): string { const template = document.createElement('template'); template.innerHTML = html.replace(//gi, '\n').replace(/<\/(p|div|li|h[1-6]|blockquote)>/gi, '\n'); return (template.content.textContent ?? '').replace(/\u00a0/g, ' ').replace(/\n{3,}/g, '\n\n').trim(); } export function CopyCommentButton({ html, className = 'commentmate-icon-button' }: { html: string; className?: string }) { const [state, setState] = useState<'idle' | 'copied' | 'error'>('idle'); const timer = useRef(); useEffect(() => () => window.clearTimeout(timer.current), []); const copy = async () => { try { await navigator.clipboard.writeText(commentPlainText(html)); setState('copied'); } catch { setState('error'); } window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setState('idle'), 2200); }; const label = state === 'copied' ? __('Comment copied', 'commentmate') : state === 'error' ? __('Copy failed. Select and copy the comment text.', 'commentmate') : __('Copy comment', 'commentmate'); return ; }