Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

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

export function useCopyToClipboard(): [
string | null,
(value: string) => Promise<void>
(value: string | ClipboardFormats) => Promise<void>
];

export function useCounter(
Expand Down
22 changes: 18 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}, []);

Expand Down