import { createElement, useState } from '@wordpress/element'
import {
useBlockProps,
__experimentalUseBorderProps as useBorderProps,
} from '@wordpress/block-editor'
import classnames from 'classnames'
import { useSelect } from '@wordpress/data'
import { useEntityProp, store as coreStore } from '@wordpress/core-data'
function getMediaSourceUrlBySizeSlug(media, slug) {
return media?.media_details?.sizes?.[slug]?.source_url || media?.source_url
}
const VideoIndicator = () => (
)
const ImagePreview = ({
postType,
postId,
attributes,
attributes: {
aspectRatio,
width,
height,
imageAlign,
has_field_link,
sizeSlug,
image_hover_effect,
videoThumbnail,
},
}) => {
const [isLoaded, setIsLoaded] = useState(false)
const blockProps = useBlockProps({
className: classnames('ct-dynamic-media wp-block-image', {
[`align${imageAlign}`]: imageAlign,
}),
style: {
aspectRatio,
width,
height,
},
...(image_hover_effect !== 'none'
? { 'data-hover': image_hover_effect }
: {}),
})
const borderProps = useBorderProps(attributes)
const [featuredImage, setFeaturedImage] = useEntityProp(
'postType',
postType,
'featured_media',
postId
)
const { media } = useSelect(
(select) => {
const { getMedia } = select(coreStore)
return {
media:
featuredImage &&
getMedia(featuredImage, {
context: 'view',
}),
}
},
[featuredImage]
)
const maybeUrl = getMediaSourceUrlBySizeSlug(media, sizeSlug)
const imageStyles = {
...borderProps.style,
height: aspectRatio ? '100%' : height,
width: !!aspectRatio && '100%',
objectFit: !!(height || aspectRatio) && 'cover',
}
if (!maybeUrl) {
return (
)
}
let content = (
setIsLoaded(true)}
loading="lazy"
/>
)
if (
has_field_link &&
!media.has_video &&
videoThumbnail !== 'yes' &&
!isLoaded
) {
content = {content}
}
return (
{content}
{media.has_video && videoThumbnail === 'yes' ? (
) : null}
)
}
export default ImagePreview