attachments.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import { onMount } from "solid-js"
  2. import { makeEventListener } from "@solid-primitives/event-listener"
  3. import { showToast } from "@opencode-ai/ui/toast"
  4. import { usePrompt, type ContentPart, type ImageAttachmentPart } from "@/context/prompt"
  5. import { useLanguage } from "@/context/language"
  6. import { uuid } from "@/utils/uuid"
  7. import { getCursorPosition } from "./editor-dom"
  8. import { attachmentMime } from "./files"
  9. import { normalizePaste, pasteMode } from "./paste"
  10. function dataUrl(file: File, mime: string) {
  11. return new Promise<string>((resolve) => {
  12. const reader = new FileReader()
  13. reader.addEventListener("error", () => resolve(""))
  14. reader.addEventListener("load", () => {
  15. const value = typeof reader.result === "string" ? reader.result : ""
  16. const idx = value.indexOf(",")
  17. if (idx === -1) {
  18. resolve(value)
  19. return
  20. }
  21. resolve(`data:${mime};base64,${value.slice(idx + 1)}`)
  22. })
  23. reader.readAsDataURL(file)
  24. })
  25. }
  26. type PromptAttachmentsInput = {
  27. editor: () => HTMLDivElement | undefined
  28. isDialogActive: () => boolean
  29. setDraggingType: (type: "image" | "@mention" | null) => void
  30. focusEditor: () => void
  31. addPart: (part: ContentPart) => boolean
  32. readClipboardImage?: () => Promise<File | null>
  33. }
  34. export function createPromptAttachments(input: PromptAttachmentsInput) {
  35. const prompt = usePrompt()
  36. const language = useLanguage()
  37. const warn = () => {
  38. showToast({
  39. title: language.t("prompt.toast.pasteUnsupported.title"),
  40. description: language.t("prompt.toast.pasteUnsupported.description"),
  41. })
  42. }
  43. const add = async (file: File, toast = true) => {
  44. const mime = await attachmentMime(file)
  45. if (!mime) {
  46. if (toast) warn()
  47. return false
  48. }
  49. const editor = input.editor()
  50. if (!editor) return false
  51. const url = await dataUrl(file, mime)
  52. if (!url) return false
  53. const attachment: ImageAttachmentPart = {
  54. type: "image",
  55. id: uuid(),
  56. filename: file.name,
  57. mime,
  58. dataUrl: url,
  59. }
  60. const cursor = prompt.cursor() ?? getCursorPosition(editor)
  61. prompt.set([...prompt.current(), attachment], cursor)
  62. return true
  63. }
  64. const addAttachment = (file: File) => add(file)
  65. const addAttachments = async (files: File[], toast = true) => {
  66. let found = false
  67. for (const file of files) {
  68. const ok = await add(file, false)
  69. if (ok) found = true
  70. }
  71. if (!found && files.length > 0 && toast) warn()
  72. return found
  73. }
  74. const removeAttachment = (id: string) => {
  75. const current = prompt.current()
  76. const next = current.filter((part) => part.type !== "image" || part.id !== id)
  77. prompt.set(next, prompt.cursor())
  78. }
  79. const handlePaste = async (event: ClipboardEvent) => {
  80. const clipboardData = event.clipboardData
  81. if (!clipboardData) return
  82. event.preventDefault()
  83. event.stopPropagation()
  84. const files = Array.from(clipboardData.items).flatMap((item) => {
  85. if (item.kind !== "file") return []
  86. const file = item.getAsFile()
  87. return file ? [file] : []
  88. })
  89. if (files.length > 0) {
  90. await addAttachments(files)
  91. return
  92. }
  93. const plainText = clipboardData.getData("text/plain") ?? ""
  94. // Desktop: Browser clipboard has no images and no text, try platform's native clipboard for images
  95. if (input.readClipboardImage && !plainText) {
  96. const file = await input.readClipboardImage()
  97. if (file) {
  98. await addAttachment(file)
  99. return
  100. }
  101. }
  102. if (!plainText) return
  103. const text = normalizePaste(plainText)
  104. const put = () => {
  105. if (input.addPart({ type: "text", content: text, start: 0, end: 0 })) return true
  106. input.focusEditor()
  107. return input.addPart({ type: "text", content: text, start: 0, end: 0 })
  108. }
  109. if (pasteMode(text) === "manual") {
  110. put()
  111. return
  112. }
  113. const inserted = typeof document.execCommand === "function" && document.execCommand("insertText", false, text)
  114. if (inserted) return
  115. put()
  116. }
  117. const handleGlobalDragOver = (event: DragEvent) => {
  118. if (input.isDialogActive()) return
  119. event.preventDefault()
  120. const hasFiles = event.dataTransfer?.types.includes("Files")
  121. const hasText = event.dataTransfer?.types.includes("text/plain")
  122. if (hasFiles) {
  123. input.setDraggingType("image")
  124. } else if (hasText) {
  125. input.setDraggingType("@mention")
  126. }
  127. }
  128. const handleGlobalDragLeave = (event: DragEvent) => {
  129. if (input.isDialogActive()) return
  130. if (!event.relatedTarget) {
  131. input.setDraggingType(null)
  132. }
  133. }
  134. const handleGlobalDrop = async (event: DragEvent) => {
  135. if (input.isDialogActive()) return
  136. event.preventDefault()
  137. input.setDraggingType(null)
  138. const plainText = event.dataTransfer?.getData("text/plain")
  139. const filePrefix = "file:"
  140. if (plainText?.startsWith(filePrefix)) {
  141. const filePath = plainText.slice(filePrefix.length)
  142. input.focusEditor()
  143. input.addPart({ type: "file", path: filePath, content: "@" + filePath, start: 0, end: 0 })
  144. return
  145. }
  146. const dropped = event.dataTransfer?.files
  147. if (!dropped) return
  148. await addAttachments(Array.from(dropped))
  149. }
  150. onMount(() => {
  151. makeEventListener(document, "dragover", handleGlobalDragOver)
  152. makeEventListener(document, "dragleave", handleGlobalDragLeave)
  153. makeEventListener(document, "drop", handleGlobalDrop)
  154. })
  155. return {
  156. addAttachment,
  157. addAttachments,
  158. removeAttachment,
  159. handlePaste,
  160. }
  161. }