From d7b46b43dd6812fb2393643c9cc95b586146ded7 Mon Sep 17 00:00:00 2001 From: Abhishek Chaurasiya Date: Mon, 27 Oct 2025 05:49:16 +0530 Subject: [PATCH] fixes [#329](https://github.com/abhichaurasiya2022/usehooks/issues/329): Add multi-format clipboard support to useCopyToClipboard --- index.d.ts | 8 +++++++- index.js | 22 ++++++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/index.d.ts b/index.d.ts index db01dc2..0b2cd8e 100644 --- a/index.d.ts +++ b/index.d.ts @@ -116,6 +116,12 @@ export type SpeechState = { volume: number; }; +export type ClipboardFormats = { + plain?: string; + html?: string; + markdown?: string; +}; + declare module "@uidotdev/usehooks" { export function useBattery(): BatteryManager; @@ -125,7 +131,7 @@ declare module "@uidotdev/usehooks" { export function useCopyToClipboard(): [ string | null, - (value: string) => Promise + (value: string | ClipboardFormats) => Promise ]; export function useCounter( diff --git a/index.js b/index.js index f6e4fe2..cd8d7ee 100644 --- a/index.js +++ b/index.js @@ -145,18 +145,32 @@ export function useCopyToClipboard() { const copyToClipboard = React.useCallback((value) => { const handleCopy = async () => { try { - if (navigator?.clipboard?.writeText) { + // ClipboardItem API for multiple formats + if (typeof value === 'object' && value !== null && window.ClipboardItem) { + const items = {}; + if (value.plain) { + items["text/plain"] = new Blob([value.plain], { type: "text/plain" }); + } + if (value.html) { + items["text/html"] = new Blob([value.html], { type: "text/html" }); + } + if (value.markdown) { + items["text/markdown"] = new Blob([value.markdown], { type: "text/markdown" }); + } + const clipboardItem = new ClipboardItem(items); + await navigator.clipboard.write([clipboardItem]); + setState(value.plain || value.html || value.markdown); + } else if (navigator?.clipboard?.writeText) { await navigator.clipboard.writeText(value); setState(value); } else { throw new Error("writeText not supported"); } } catch (e) { - oldSchoolCopy(value); - setState(value); + oldSchoolCopy(typeof value === 'object' ? value.plain : value); + setState(typeof value === 'object' ? value.plain : value); } }; - handleCopy(); }, []);