You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.4 KiB
57 lines
1.4 KiB
import {
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
} from 'react'
|
|
|
|
export type TUseCardFrontside = {
|
|
preview?: string,
|
|
previewURL?: string,
|
|
}
|
|
|
|
const PREVIEW_WIDTH = 400 // макс. 1920
|
|
|
|
export const useCardPreview = ({
|
|
preview,
|
|
previewURL,
|
|
}: TUseCardFrontside) => {
|
|
const [previewImage, setPreviewImage] = useState('')
|
|
const currentPreviewURL = useMemo(() => (
|
|
previewURL ? `${previewURL}?width=${PREVIEW_WIDTH}` : preview
|
|
), [preview, previewURL])
|
|
|
|
useEffect(() => {
|
|
const controller = new AbortController()
|
|
const { signal } = controller;
|
|
|
|
(async () => {
|
|
if (!currentPreviewURL) return
|
|
|
|
try {
|
|
const image = await fetch(String(currentPreviewURL), {
|
|
signal,
|
|
})
|
|
.then(async (result) => ({
|
|
blob: await result.blob(),
|
|
status: result.status,
|
|
}))
|
|
|
|
if (image.status === 200) {
|
|
setPreviewImage(URL.createObjectURL(image.blob))
|
|
}
|
|
} catch (e) {
|
|
// eslint-disable-next-line no-console
|
|
console.error(e)
|
|
}
|
|
})()
|
|
|
|
return () => {
|
|
URL.revokeObjectURL(previewImage)
|
|
controller.abort()
|
|
}
|
|
// добавление previewImage в зависимость вызывает бесконечный цикл
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [currentPreviewURL])
|
|
|
|
return { previewImage }
|
|
}
|
|
|