paste-image.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. }