|
| 1 | +import { useEffect, useState } from 'react'; |
| 2 | +import { freefeedAttachmentId, IMAGE, useMediaLink } from './helpers'; |
| 3 | +import { getAttachmentInfo } from '../../services/batch-attachments-info'; |
| 4 | +import { attachmentPreviewUrl } from '../../services/api'; |
| 5 | +import { getDefaultAspectRatio, getVideoId, T_YOUTUBE_VIDEO } from '../link-preview/video'; |
| 6 | +import styles from './media-link-preview.module.scss'; |
| 7 | + |
| 8 | +export function MediaLinkPreview({ href: url }) { |
| 9 | + const [mediaType, handleClick] = useMediaLink(url); |
| 10 | + |
| 11 | + if (mediaType !== IMAGE && mediaType !== T_YOUTUBE_VIDEO) { |
| 12 | + return null; |
| 13 | + } |
| 14 | + |
| 15 | + // Freefeed attachment? |
| 16 | + const attId = freefeedAttachmentId(url); |
| 17 | + if (attId) { |
| 18 | + return ( |
| 19 | + <a href={url} target="_blank" rel="noreferrer" onClick={handleClick}> |
| 20 | + <FreeFeedMediaPreview id={attId} /> |
| 21 | + </a> |
| 22 | + ); |
| 23 | + } |
| 24 | + |
| 25 | + if (mediaType === T_YOUTUBE_VIDEO) { |
| 26 | + return ( |
| 27 | + <a href={url} target="_blank" rel="noreferrer" onClick={handleClick}> |
| 28 | + <YouTubeMediaPreview url={url} /> |
| 29 | + </a> |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + return ( |
| 34 | + <a href={url} target="_blank" rel="noreferrer" onClick={handleClick}> |
| 35 | + <img src={url} alt="" width={60} height={60} className={styles.preview} loading="lazy" /> |
| 36 | + </a> |
| 37 | + ); |
| 38 | +} |
| 39 | + |
| 40 | +function FreeFeedMediaPreview({ id }) { |
| 41 | + const [src, setSrc] = useState(null); |
| 42 | + |
| 43 | + useEffect(() => { |
| 44 | + getAttachmentInfo(id) |
| 45 | + .then((info) => { |
| 46 | + if (info?.mediaType === 'image' || info?.mediaType === 'video') { |
| 47 | + setSrc(attachmentPreviewUrl(id, 'image', 120, 120)); |
| 48 | + } |
| 49 | + return null; |
| 50 | + }) |
| 51 | + .catch((err) => { |
| 52 | + // Just ignore |
| 53 | + // eslint-disable-next-line no-console |
| 54 | + console.error('Failed to get attachment info', id, err); |
| 55 | + }); |
| 56 | + }, [id]); |
| 57 | + |
| 58 | + return src ? ( |
| 59 | + <img src={src} alt="" width={60} height={60} className={styles.preview} loading="lazy" /> |
| 60 | + ) : null; |
| 61 | +} |
| 62 | + |
| 63 | +function YouTubeMediaPreview({ url }) { |
| 64 | + const aspectRatio = getDefaultAspectRatio(url); |
| 65 | + return ( |
| 66 | + <img |
| 67 | + src={`https://img.youtube.com/vi/${getVideoId(url)}/default.jpg`} |
| 68 | + alt="" |
| 69 | + width={60 / aspectRatio} |
| 70 | + height={60} |
| 71 | + className={styles.preview} |
| 72 | + loading="lazy" |
| 73 | + /> |
| 74 | + ); |
| 75 | +} |
0 commit comments