useImageViewer.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import { canPreviewFile } from '@shared/utils/files'
  3. import type { MaybeRef } from '@vueuse/shared'
  4. import { ref, unref, watchEffect } from 'vue'
  5. interface ImagePreview {
  6. src?: string
  7. title?: string
  8. }
  9. interface CachedFile {
  10. name?: string
  11. content?: string
  12. preview?: string
  13. type?: Maybe<string>
  14. }
  15. interface ViewerOptions {
  16. images: ImagePreview[]
  17. index: number
  18. visible: boolean
  19. }
  20. export const imageViewerOptions = ref<ViewerOptions>({
  21. visible: false,
  22. index: 0,
  23. images: [],
  24. })
  25. const useImageViewer = (viewFiles: MaybeRef<CachedFile[]>) => {
  26. const indexMap = new WeakMap<CachedFile, number>()
  27. let images: ImagePreview[] = []
  28. watchEffect(() => {
  29. images = unref(viewFiles)
  30. .filter((file) => canPreviewFile(file.type))
  31. .map((image, index) => {
  32. // we need to keep track of indexes, because they might
  33. // be different from original files, if they had non-image uploads
  34. indexMap.set(image, index)
  35. return {
  36. src: image.preview || image.content,
  37. title: image.name,
  38. }
  39. })
  40. })
  41. const showImage = (image: CachedFile) => {
  42. const foundIndex = indexMap.get(image) ?? 0
  43. imageViewerOptions.value = {
  44. index: foundIndex,
  45. images,
  46. visible: true,
  47. }
  48. }
  49. const hideImage = () => {
  50. imageViewerOptions.value = {
  51. images: [],
  52. index: 0,
  53. visible: false,
  54. }
  55. }
  56. const isViewable = (file: CachedFile) => indexMap.has(file)
  57. return {
  58. isViewable,
  59. showImage,
  60. hideImage,
  61. }
  62. }
  63. export default useImageViewer