The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as React from "react"; |
| 2 | import * as Schema from "effect/Schema"; |
| 3 | import { |
| 4 | COMPOSER_CONTEXT_CLIPBOARD_MIME, |
| 5 | encodeComposerContextClipboardHtml, |
| 6 | } from "@t3tools/shared/composerContextClipboard"; |
| 7 | import { msg } from "gt-react"; |
| 8 | |
| 9 | import { m } from "../i18n/messages"; |
| 10 | import { useStableCallback } from "./useStableCallback"; |
| 11 | |
| 12 | /** `msg()` sentences, resolved when the error is shown, so users read whole ones. */ |
| 13 | export interface ClipboardTarget { |
| 14 | /** An English noun for logs. */ |
| 15 | readonly target: string; |
| 16 | /** Shown when the clipboard API is missing. */ |
| 17 | readonly unavailableMessage: string; |
| 18 | /** Shown when the browser rejects the copy or read. */ |
| 19 | readonly failureMessage: string; |
| 20 | } |
| 21 | |
| 22 | /** Copying something the user named, such as a file: its name goes into the sentences as is. */ |
| 23 | export function namedClipboardTarget(name: string): ClipboardTarget { |
| 24 | return { |
| 25 | target: name, |
| 26 | unavailableMessage: msg("Clipboard API is unavailable while copying {target}.", { |
| 27 | target: name, |
| 28 | }), |
| 29 | failureMessage: msg("Failed to copy {target} to the clipboard.", { target: name }), |
| 30 | }; |
| 31 | } |
| 32 | |
| 33 | const DEFAULT_CLIPBOARD_TARGET = "text"; |
| 34 | |
| 35 | function clipboardTargetFields( |
| 36 | target: ClipboardTarget | undefined, |
| 37 | failure: "unavailable" | "failure", |
| 38 | ) { |
| 39 | if (target === undefined) return { target: DEFAULT_CLIPBOARD_TARGET }; |
| 40 | return { |
| 41 | target: target.target, |
| 42 | displayMessage: failure === "unavailable" ? target.unavailableMessage : target.failureMessage, |
| 43 | }; |
| 44 | } |
| 45 | |
| 46 | export class ClipboardApiUnavailableError extends Schema.TaggedError<ClipboardApiUnavailableError>()( |
| 47 | "ClipboardApiUnavailableError", |
| 48 | { |
| 49 | target: Schema.String, |
| 50 | displayMessage: Schema.optional(Schema.String), |
| 51 | }, |
| 52 | ) { |
| 53 | override get message(): string { |
| 54 | if (this.displayMessage !== undefined) return m(this.displayMessage); |
| 55 | return m(msg("Clipboard API is unavailable while copying text.")); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export class ClipboardWriteError extends Schema.TaggedError<ClipboardWriteError>()( |
| 60 | "ClipboardWriteError", |
| 61 | { |
| 62 | target: Schema.String, |
| 63 | displayMessage: Schema.optional(Schema.String), |
| 64 | cause: Schema.Defect(), |
| 65 | }, |
| 66 | ) { |
| 67 | override get message(): string { |
| 68 | if (this.displayMessage !== undefined) return m(this.displayMessage); |
| 69 | return m(msg("Failed to copy text to the clipboard.")); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | export class ClipboardReadUnavailableError extends Schema.TaggedError<ClipboardReadUnavailableError>()( |
| 74 | "ClipboardReadUnavailableError", |
| 75 | { |
| 76 | target: Schema.String, |
| 77 | displayMessage: Schema.optional(Schema.String), |
| 78 | }, |
| 79 | ) { |
| 80 | override get message(): string { |
| 81 | if (this.displayMessage !== undefined) return m(this.displayMessage); |
| 82 | return m(msg("Clipboard API is unavailable while reading text.")); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | export class ClipboardReadError extends Schema.TaggedError<ClipboardReadError>()( |
| 87 | "ClipboardReadError", |
| 88 | { |
| 89 | target: Schema.String, |
| 90 | displayMessage: Schema.optional(Schema.String), |
| 91 | cause: Schema.Defect(), |
| 92 | }, |
| 93 | ) { |
| 94 | override get message(): string { |
| 95 | if (this.displayMessage !== undefined) return m(this.displayMessage); |
| 96 | return m(msg("Failed to read text from the clipboard.")); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | function writeTextWithExecCommand( |
| 101 | value: string, |
| 102 | extraFlavors?: Readonly<Record<string, string>>, |
| 103 | ): boolean { |
| 104 | if (typeof document === "undefined" || typeof document.execCommand !== "function") return false; |
| 105 | |
| 106 | const textarea = document.createElement("textarea"); |
| 107 | textarea.value = value; |
| 108 | textarea.setAttribute("readonly", ""); |
| 109 | textarea.setAttribute("aria-hidden", "true"); |
| 110 | textarea.style.position = "fixed"; |
| 111 | textarea.style.top = "0"; |
| 112 | textarea.style.left = "0"; |
| 113 | textarea.style.opacity = "0"; |
| 114 | textarea.style.fontSize = "16px"; |
| 115 | |
| 116 | const previouslyFocused = document.activeElement; |
| 117 | const copy = (event: ClipboardEvent) => { |
| 118 | if (!extraFlavors || !event.clipboardData) return; |
| 119 | event.clipboardData.setData("text/plain", value); |
| 120 | for (const [type, data] of Object.entries(extraFlavors)) |
| 121 | event.clipboardData.setData(type, data); |
| 122 | event.preventDefault(); |
| 123 | }; |
| 124 | document.body.appendChild(textarea); |
| 125 | textarea.addEventListener("copy", copy); |
| 126 | try { |
| 127 | textarea.focus({ preventScroll: true }); |
| 128 | textarea.select(); |
| 129 | textarea.setSelectionRange(0, value.length); |
| 130 | return document.execCommand("copy"); |
| 131 | } catch { |
| 132 | return false; |
| 133 | } finally { |
| 134 | textarea.removeEventListener("copy", copy); |
| 135 | textarea.remove(); |
| 136 | const restoreFocus = (previouslyFocused as { focus?: unknown } | null)?.focus; |
| 137 | if (typeof restoreFocus === "function") { |
| 138 | restoreFocus.call(previouslyFocused); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | export async function writeTextToClipboard( |
| 144 | value: string, |
| 145 | target?: ClipboardTarget, |
| 146 | extraFlavors?: Readonly<Record<string, string>>, |
| 147 | ) { |
| 148 | if (typeof window === "undefined") { |
| 149 | throw new ClipboardApiUnavailableError(clipboardTargetFields(target, "unavailable")); |
| 150 | } |
| 151 | |
| 152 | if (!value) return false; |
| 153 | if (extraFlavors) { |
| 154 | extraFlavors = Object.fromEntries( |
| 155 | Object.entries(extraFlavors).filter(([type]) => type !== "text/plain"), |
| 156 | ); |
| 157 | } |
| 158 | const contextFragment = extraFlavors?.[COMPOSER_CONTEXT_CLIPBOARD_MIME]; |
| 159 | if (contextFragment) |
| 160 | extraFlavors = { |
| 161 | ...extraFlavors, |
| 162 | "text/html": encodeComposerContextClipboardHtml( |
| 163 | value, |
| 164 | contextFragment, |
| 165 | extraFlavors?.["text/html"], |
| 166 | ), |
| 167 | }; |
| 168 | |
| 169 | if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) { |
| 170 | if (writeTextWithExecCommand(value, extraFlavors)) return true; |
| 171 | throw new ClipboardApiUnavailableError(clipboardTargetFields(target, "unavailable")); |
| 172 | } |
| 173 | |
| 174 | try { |
| 175 | if (extraFlavors && typeof ClipboardItem !== "undefined" && navigator.clipboard.write) { |
| 176 | try { |
| 177 | await navigator.clipboard.write([ |
| 178 | new ClipboardItem({ |
| 179 | "text/plain": new Blob([value], { type: "text/plain" }), |
| 180 | ...Object.fromEntries( |
| 181 | Object.entries(extraFlavors).map(([type, data]) => [ |
| 182 | type, |
| 183 | new Blob([data], { type }), |
| 184 | ]), |
| 185 | ), |
| 186 | }), |
| 187 | ]); |
| 188 | return true; |
| 189 | } catch { |
| 190 | // Safari/native bridges may accept HTML but reject Chromium's custom web flavor. |
| 191 | const html = extraFlavors["text/html"]; |
| 192 | if (html) { |
| 193 | try { |
| 194 | await navigator.clipboard.write([ |
| 195 | new ClipboardItem({ |
| 196 | "text/plain": new Blob([value], { type: "text/plain" }), |
| 197 | "text/html": new Blob([html], { type: "text/html" }), |
| 198 | }), |
| 199 | ]); |
| 200 | return true; |
| 201 | } catch {} |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | await navigator.clipboard.writeText(value); |
| 206 | return true; |
| 207 | } catch (cause) { |
| 208 | throw new ClipboardWriteError({ ...clipboardTargetFields(target, "failure"), cause }); |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | export async function readTextFromClipboard(target?: ClipboardTarget): Promise<string> { |
| 213 | if ( |
| 214 | typeof window === "undefined" || |
| 215 | typeof navigator === "undefined" || |
| 216 | !navigator.clipboard?.readText |
| 217 | ) { |
| 218 | throw new ClipboardReadUnavailableError(clipboardTargetFields(target, "unavailable")); |
| 219 | } |
| 220 | |
| 221 | try { |
| 222 | return await navigator.clipboard.readText(); |
| 223 | } catch (cause) { |
| 224 | throw new ClipboardReadError({ ...clipboardTargetFields(target, "failure"), cause }); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | export function useCopyToClipboard<TContext = void>({ |
| 229 | timeout = 2000, |
| 230 | target, |
| 231 | onCopy, |
| 232 | onError, |
| 233 | extraFlavors, |
| 234 | }: { |
| 235 | timeout?: number; |
| 236 | target?: ClipboardTarget; |
| 237 | onCopy?: (ctx: TContext) => void; |
| 238 | onError?: (error: Error, ctx: TContext) => void; |
| 239 | extraFlavors?: Readonly<Record<string, string>>; |
| 240 | } = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } { |
| 241 | const [isCopied, setIsCopied] = React.useState(false); |
| 242 | const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null); |
| 243 | const copyToClipboard = useStableCallback((value: string, ctx: TContext): void => { |
| 244 | void writeTextToClipboard(value, target, extraFlavors).then( |
| 245 | (didCopy) => { |
| 246 | if (!didCopy) return; |
| 247 | if (timeoutIdRef.current) { |
| 248 | clearTimeout(timeoutIdRef.current); |
| 249 | } |
| 250 | setIsCopied(true); |
| 251 | |
| 252 | onCopy?.(ctx); |
| 253 | |
| 254 | if (timeout !== 0) { |
| 255 | timeoutIdRef.current = setTimeout(() => { |
| 256 | setIsCopied(false); |
| 257 | timeoutIdRef.current = null; |
| 258 | }, timeout); |
| 259 | } |
| 260 | }, |
| 261 | (error) => { |
| 262 | console.error(error); |
| 263 | onError?.(error, ctx); |
| 264 | }, |
| 265 | ); |
| 266 | }); |
| 267 | |
| 268 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the copied-state reset timer on unmount |
| 269 | React.useEffect(() => { |
| 270 | return (): void => { |
| 271 | if (timeoutIdRef.current) { |
| 272 | clearTimeout(timeoutIdRef.current); |
| 273 | } |
| 274 | }; |
| 275 | }, []); |
| 276 | |
| 277 | return { copyToClipboard, isCopied }; |
| 278 | } |