|
| 1 | +import * as React from 'react'; |
| 2 | + |
| 3 | +import {getGalleryItemImage, getGalleryItemVideo} from '../../components'; |
| 4 | +import {useGallery} from '../useGallery'; |
| 5 | + |
| 6 | +import {extensionRegex, supportedExtensions, supportedVideoExtensions} from './constants'; |
| 7 | +import {GalleryItemPropsWithUrl} from './types'; |
| 8 | + |
| 9 | +export function useFilesGalleryFromContent(customFiles?: GalleryItemPropsWithUrl[]) { |
| 10 | + const openFilesGallery = useGallery(); |
| 11 | + |
| 12 | + return React.useCallback( |
| 13 | + (event: React.MouseEvent<HTMLDivElement>) => { |
| 14 | + if (event.target instanceof HTMLElement) { |
| 15 | + let fileLink = ''; |
| 16 | + |
| 17 | + if (event.target.tagName === 'IMG' && !event.target.closest('a')) { |
| 18 | + fileLink = event.target.getAttribute('src') ?? ''; |
| 19 | + } else if (event.target.tagName === 'A') { |
| 20 | + fileLink = event.target.getAttribute('href') ?? ''; |
| 21 | + } |
| 22 | + |
| 23 | + if (!fileLink) { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + const filesFromContent = [ |
| 28 | + ...(event.currentTarget?.querySelectorAll('img,a') ?? []), |
| 29 | + ].reduce<GalleryItemPropsWithUrl[]>((result, element) => { |
| 30 | + const isImage = element.tagName === 'IMG'; |
| 31 | + const link = isImage |
| 32 | + ? element.getAttribute('src') |
| 33 | + : element.getAttribute('href'); |
| 34 | + |
| 35 | + if (link && !customFiles?.some((item) => item.url === link)) { |
| 36 | + const extension = link.match(extensionRegex)?.[0] || ''; |
| 37 | + |
| 38 | + if (isImage || supportedExtensions.includes(extension)) { |
| 39 | + const name = |
| 40 | + (isImage |
| 41 | + ? element.getAttribute('alt') |
| 42 | + : element.getAttribute('title')) || ''; |
| 43 | + |
| 44 | + result.push({ |
| 45 | + ...(supportedVideoExtensions.includes(extension) |
| 46 | + ? getGalleryItemVideo({src: link, name: name}) |
| 47 | + : getGalleryItemImage({src: link, name: name})), |
| 48 | + url: link, |
| 49 | + }); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | + }, []); |
| 55 | + |
| 56 | + const files = [...(customFiles ?? []), ...filesFromContent]; |
| 57 | + |
| 58 | + const initialItemIndex = files.findIndex((item) => item.url === fileLink); |
| 59 | + |
| 60 | + if (initialItemIndex !== -1) { |
| 61 | + event.preventDefault(); |
| 62 | + openFilesGallery(files, initialItemIndex); |
| 63 | + } |
| 64 | + } |
| 65 | + }, |
| 66 | + [customFiles, openFilesGallery], |
| 67 | + ); |
| 68 | +} |
0 commit comments