Skip to content

Commit d7b46b4

Browse files
fixes [#329](https://github.com/abhichaurasiya2022/usehooks/issues/329): Add multi-format clipboard support to useCopyToClipboard
1 parent 945436d commit d7b46b4

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

index.d.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,12 @@ export type SpeechState = {
116116
volume: number;
117117
};
118118

119+
export type ClipboardFormats = {
120+
plain?: string;
121+
html?: string;
122+
markdown?: string;
123+
};
124+
119125
declare module "@uidotdev/usehooks" {
120126
export function useBattery(): BatteryManager;
121127

@@ -125,7 +131,7 @@ declare module "@uidotdev/usehooks" {
125131

126132
export function useCopyToClipboard(): [
127133
string | null,
128-
(value: string) => Promise<void>
134+
(value: string | ClipboardFormats) => Promise<void>
129135
];
130136

131137
export function useCounter(

index.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,18 +145,32 @@ export function useCopyToClipboard() {
145145
const copyToClipboard = React.useCallback((value) => {
146146
const handleCopy = async () => {
147147
try {
148-
if (navigator?.clipboard?.writeText) {
148+
// ClipboardItem API for multiple formats
149+
if (typeof value === 'object' && value !== null && window.ClipboardItem) {
150+
const items = {};
151+
if (value.plain) {
152+
items["text/plain"] = new Blob([value.plain], { type: "text/plain" });
153+
}
154+
if (value.html) {
155+
items["text/html"] = new Blob([value.html], { type: "text/html" });
156+
}
157+
if (value.markdown) {
158+
items["text/markdown"] = new Blob([value.markdown], { type: "text/markdown" });
159+
}
160+
const clipboardItem = new ClipboardItem(items);
161+
await navigator.clipboard.write([clipboardItem]);
162+
setState(value.plain || value.html || value.markdown);
163+
} else if (navigator?.clipboard?.writeText) {
149164
await navigator.clipboard.writeText(value);
150165
setState(value);
151166
} else {
152167
throw new Error("writeText not supported");
153168
}
154169
} catch (e) {
155-
oldSchoolCopy(value);
156-
setState(value);
170+
oldSchoolCopy(typeof value === 'object' ? value.plain : value);
171+
setState(typeof value === 'object' ? value.plain : value);
157172
}
158173
};
159-
160174
handleCopy();
161175
}, []);
162176

0 commit comments

Comments
 (0)