/
link-preview.tsx
88 lines (80 loc) · 2.31 KB
/
link-preview.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* eslint-disable @next/next/no-img-element */
'use server'
import { JSDOM } from 'jsdom'
import { ExternalLink } from '@/components/ui'
import { cn } from '@/lib/utils'
async function getOpenGraphTags(url: URL | string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Failed to fetch data from ${url}`)
}
const html = await response.text()
const dom = new JSDOM(html)
const document = dom.window.document
// Find and extract Open Graph tags
const ogData: { [key: string]: string } = {}
const metaTags = document.querySelectorAll('meta[property^="og:"]')
metaTags.forEach((tag) => {
if (tag.hasAttribute('property') && tag.hasAttribute('content')) {
const property = (tag.getAttribute('property') as string).replace(
'og:',
'',
)
const content = tag.getAttribute('content') as string
ogData[property] = content
}
})
return ogData
} catch (error) {
console.error(error)
}
}
export type LinkPreviewProps = {
href: string
withImage?: boolean
fullImage?: boolean
}
export const LinkPreview = async ({
href,
withImage,
fullImage,
}: LinkPreviewProps) => {
const url = new URL(href)
const data = await getOpenGraphTags(url)
return (
<div
className={cn('group mb-4 mt-2 border bg-color-secondary border-color', {
'max-w-lg': fullImage,
})}
>
<ExternalLink
href={data?.url || url.toString() || '#'}
className="no-underline"
>
{withImage && (
<div className="overflow-hidden">
<img
src={
(data?.image as string) ||
'/assets/main/placeholder-content.png'
}
alt={(data?.title as string) || 'Link preview image'}
className={cn('w-full', {
'max-h-24 object-cover sm:max-h-32': !fullImage,
})}
/>
</div>
)}
<div className="px-2 py-1.5">
<p className="line-clamp-1 font-medium group-hover:underline">
{data?.title || 'No title'}
</p>
<p className="line-clamp-3 text-sm text-color-secondary">
{data?.description || 'No description'}
</p>
</div>
</ExternalLink>
</div>
)
}