(root: HTMLDivElement, getLabels: () => CopyLabels)
| 281 | } |
| 282 | |
| 283 | function setupCodeCopy(root: HTMLDivElement, getLabels: () => CopyLabels) { |
| 284 | const timeouts = new Map<HTMLElement, ReturnType<typeof setTimeout>>() |
| 285 | |
| 286 | const updateLabel = (button: HTMLElement) => { |
| 287 | const labels = getLabels() |
| 288 | const copied = button.getAttribute("data-copied") === "true" |
| 289 | setCopyState(button, labels, copied) |
| 290 | } |
| 291 | |
| 292 | const handleClick = async (event: MouseEvent) => { |
| 293 | const target = event.target |
| 294 | if (!(target instanceof Element)) return |
| 295 | |
| 296 | const button = target.closest('[data-slot="markdown-copy-button"]') |
| 297 | if (!(button instanceof HTMLElement)) return |
| 298 | const code = button.closest('[data-component="markdown-code"]')?.querySelector("code") |
| 299 | const content = code?.textContent ?? "" |
| 300 | if (!content) return |
| 301 | const clipboard = navigator?.clipboard |
| 302 | if (!clipboard) return |
| 303 | await clipboard.writeText(content) |
| 304 | const labels = getLabels() |
| 305 | setCopyState(button, labels, true) |
| 306 | const existing = timeouts.get(button) |
| 307 | if (existing) clearTimeout(existing) |
| 308 | const timeout = setTimeout(() => setCopyState(button, labels, false), 2000) |
| 309 | timeouts.set(button, timeout) |
| 310 | } |
| 311 | |
| 312 | const buttons = Array.from(root.querySelectorAll('[data-slot="markdown-copy-button"]')) |
| 313 | for (const button of buttons) { |
| 314 | if (button instanceof HTMLElement) updateLabel(button) |
| 315 | } |
| 316 | |
| 317 | root.addEventListener("click", handleClick) |
| 318 | |
| 319 | return () => { |
| 320 | root.removeEventListener("click", handleClick) |
| 321 | for (const timeout of timeouts.values()) { |
| 322 | clearTimeout(timeout) |
| 323 | } |
| 324 | disposeCopyButtons(root) |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | function initialResult(text: string, key: string | undefined, projection: Projection, owner: string): RenderResult { |
| 329 | if (!text) return { text, blocks: [] } |
no test coverage detected