paste-image.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export const ALLOWED_IMAGE_TYPES = new Set([
  2. 'image/jpeg',
  3. 'image/png',
  4. 'application/pdf',
  5. ])
  6. export function isAllowedImageType(mimeType: string): boolean {
  7. return ALLOWED_IMAGE_TYPES.has(mimeType)
  8. }
  9. export type PastedImageData = {
  10. name: string
  11. type: string
  12. data: Blob
  13. }
  14. export function dispatchFigureModalPasteEvent(
  15. imageData: PastedImageData
  16. ): void {
  17. window.dispatchEvent(
  18. new CustomEvent<PastedImageData>('figure-modal:paste-image', {
  19. detail: imageData,
  20. })
  21. )
  22. }
  23. export async function findImageInClipboard(): Promise<File | null> {
  24. try {
  25. const clipboardItems = await navigator.clipboard.read()
  26. for (const item of clipboardItems) {
  27. for (const type of item.types) {
  28. if (isAllowedImageType(type)) {
  29. const blob = await item.getType(type)
  30. const file = new File([blob], `image.${type.split('/')[1]}`, {
  31. type,
  32. })
  33. return file
  34. }
  35. }
  36. }
  37. } catch (error) {
  38. // Clipboard.read() may fail in some browsers
  39. }
  40. return null
  41. }
  42. export const handleImagePaste = async (): Promise<boolean> => {
  43. const imageFile = await findImageInClipboard()
  44. if (imageFile) {
  45. dispatchFigureModalPasteEvent({
  46. name: imageFile.name,
  47. type: imageFile.type,
  48. data: imageFile,
  49. })
  50. return true
  51. }
  52. return false
  53. }