export interface FormattedClipboard { html: string text: string } export async function writeFormattedClipboard(content: FormattedClipboard, fallback: () => boolean): Promise { try { if (navigator.clipboard?.write && typeof ClipboardItem !== 'undefined') { await navigator.clipboard.write([ new ClipboardItem({ 'text/html': new Blob([content.html], { type: 'text/html' }), 'text/plain': new Blob([content.text], { type: 'text/plain' }), }), ]) return } } catch { // LAN HTTP and browsers denying the async API still support user-triggered native copying. } if (!fallback()) throw Error('复制未成功,请在预览中选中文字后复制。') } export async function copyRenderedWeeklyReport(source: HTMLElement): Promise { const holder = source.cloneNode(true) as HTMLElement holder.style.cssText = 'position:fixed;left:-10000px;top:0;width:760px;pointer-events:none;' holder.setAttribute('aria-hidden', 'true') document.body.append(holder) try { const html = holder.innerHTML // Plain-text destinations also need the ordinal/bullet markers that innerText omits. for (const li of holder.querySelectorAll('li')) { const parent = li.parentElement! const marker = parent.tagName === 'OL' ? String(Number(parent.getAttribute('start') || 1) + Array.from(parent.children).indexOf(li)) + '. ' : '• ' li.prepend(document.createTextNode(marker)) } const text = holder.innerText const content = { html, text } await writeFormattedClipboard(content, () => { const selection = window.getSelection() if (!selection) return false const previous = Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i).cloneRange()) const focus = document.activeElement as HTMLElement | null const range = document.createRange() range.selectNodeContents(holder) let handled = false const onCopy = (event: ClipboardEvent) => { if (!event.clipboardData) return event.clipboardData.setData('text/html', html) event.clipboardData.setData('text/plain', text) event.preventDefault() handled = true } document.addEventListener('copy', onCopy, true) try { selection.removeAllRanges() selection.addRange(range) return document.execCommand('copy') && handled } catch { return false } finally { document.removeEventListener('copy', onCopy, true) selection.removeAllRanges() for (const old of previous) if (old.commonAncestorContainer.isConnected) selection.addRange(old) if (focus?.isConnected) focus.focus({ preventScroll: true }) } }) } finally { holder.remove() } }