| 1 | import type { KeyboardEvent } from "react"; |
| 2 | import { sha256 } from "./attachDedup"; |
| 3 | import type { PersistentComposerDraft } from "./composerDraftTypes"; |
| 4 | import { replaceInvocationTextRange } from "./invocationDisplay"; |
| 5 | |
| 6 | export function cutUnchangedComposerText( |
| 7 | current: PersistentComposerDraft, |
| 8 | captured: Pick<PersistentComposerDraft, "text" | "invocations" | "pastedBlocks">, |
| 9 | selection: { from: number; to: number; afterInvocationId?: string }, |
| 10 | ): PersistentComposerDraft | undefined { |
| 11 | // An async clipboard write owns the captured content, never later edits. |
| 12 | if (current.text !== captured.text |
| 13 | || JSON.stringify(current.invocations) !== JSON.stringify(captured.invocations) |
| 14 | || JSON.stringify(current.pastedBlocks) !== JSON.stringify(captured.pastedBlocks)) return; |
| 15 | const next = replaceInvocationTextRange(current.text, current.invocations, selection.from, selection.to, "", selection.afterInvocationId); |
| 16 | return { ...current, text: next.text, invocations: next.invocations }; |
| 17 | } |
| 18 | |
| 19 | function fileKey(file: File): string { |
| 20 | return `${file.name}:${file.type}:${file.size}:${file.lastModified}`; |
| 21 | } |
| 22 | |
| 23 | export function clipboardFiles(data: DataTransfer): File[] { |
| 24 | const files = Array.from(data.files); |
| 25 | const seen = new Set(files.map(fileKey)); |
| 26 | for (const item of Array.from(data.items)) { |
| 27 | if (item.kind !== "file") continue; |
| 28 | const file = item.getAsFile(); |
| 29 | if (!file) continue; |
| 30 | const key = fileKey(file); |
| 31 | if (seen.has(key)) continue; |
| 32 | seen.add(key); |
| 33 | files.push(file); |
| 34 | } |
| 35 | return files; |
| 36 | } |
| 37 | |
| 38 | export function clipboardHasImageHint(data: DataTransfer): boolean { |
| 39 | const imageType = (value: string) => { |
| 40 | const type = value.toLowerCase(); |
| 41 | return type.startsWith("image/") || type.includes("png") || type.includes("jpeg") || type.includes("jpg") || type.includes("tiff"); |
| 42 | }; |
| 43 | return Array.from(data.items).some((item) => imageType(item.type)) || Array.from(data.types).some(imageType); |
| 44 | } |
| 45 | |
| 46 | export function isPasteShortcut(e: KeyboardEvent<HTMLElement>): boolean { |
| 47 | return e.key.toLowerCase() === "v" && (e.metaKey || e.ctrlKey) && !e.altKey; |
| 48 | } |
| 49 | |
| 50 | export async function dataURLHash(dataUrl: string): Promise<string> { |
| 51 | try { |
| 52 | const res = await fetch(dataUrl); |
| 53 | return sha256(await res.blob()); |
| 54 | } catch { |
| 55 | return ""; |
| 56 | } |
| 57 | } |
| 58 |