Files
knowledge-governance/web/src/qaWeeklyClipboard.ts
T
姚章浩 c239a5ef0e
build / build (push) Successful in 1m6s
feat(qa): 周报复制渲染后的排版文字
新增复制排版内容,同时提供富文本HTML与可读纯文本,保留MD下载。
各模式独立使用最新正文,不包含预览工具栏和原文查看器;局域网HTTP走原生复制回退,失败不虚报。
验证:富文本双格式、API缺失/拒绝/失败及复制入口先红后绿,编辑保存状态机回归、完整门禁和原生备份恢复通过。
2026-10-25 17:36:22 +08:00

73 lines
2.8 KiB
TypeScript

export interface FormattedClipboard {
html: string
text: string
}
export async function writeFormattedClipboard(content: FormattedClipboard, fallback: () => boolean): Promise<void> {
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<void> {
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()
}
}