Back

Link Preview

An interactive link component with rich preview tooltip showing website metadata.

Category
CardReact
CSS
shadcn

Manual

Create a file and paste the following code into it.

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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"use client";

import Image from "next/image";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { Globe02Icon, HugeiconsIcon } from "@/components/icons";

import {
	Tooltip,
	TooltipContent,
	TooltipTrigger,
} from "@/components/ui/tooltip";

interface UrlMetadata {
	title: string | null;
	description: string | null;
	favicon: string | null;
	website_name: string | null;
	website_image: string | null;
	url: string;
}

interface LinkPreviewProps {
	href: string;
	children: ReactNode | string | null;
	className?: string;
}

const isEmail = (str: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);

const isValidHttpUrl = (str: string): boolean => {
	try {
		const url = new URL(str);
		return /^(http|https):$/.test(url.protocol);
	} catch {
		return false;
	}
};

export function LinkPreview({
	href,
	children,
	className = "cursor-pointer rounded-sm bg-primary/20 px-1 text-sm font-medium text-primary transition-all hover:text-white hover:underline",
}: LinkPreviewProps) {
	const elementRef = useRef<HTMLAnchorElement>(null);
	const [isInView, setIsInView] = useState(false);
	const [validFavicon, setValidFavicon] = useState(true);
	const [validImage, setValidImage] = useState(true);
	const [metadata, setMetadata] = useState<UrlMetadata | null>(null);
	const [isLoading, setIsLoading] = useState(false);
	const [error, setError] = useState<Error | null>(null);

	const isValidUrl =
		href &&
		isValidHttpUrl(href) &&
		!isEmail(href) &&
		!href.startsWith("mailto:");

	// Fetch metadata when in view
	useEffect(() => {
		if (!isInView || !isValidUrl || metadata) return;

		let isMounted = true;

		async function fetchMetadata() {
			setIsLoading(true);
			setError(null);

			try {
				// Fetch the URL directly
				const response = await fetch(href);

				if (!response.ok) {
					throw new Error("Failed to fetch URL");
				}

				const html = await response.text();

				// Extract metadata from HTML
				const getMetaTag = (name: string): string | null => {
					const patterns = [
						new RegExp(
							`<meta[^>]*property=["']${name}["'][^>]*content=["']([^"']*)["']`,
							"i",
						),
						new RegExp(
							`<meta[^>]*name=["']${name}["'][^>]*content=["']([^"']*)["']`,
							"i",
						),
						new RegExp(
							`<meta[^>]*content=["']([^"']*)["'][^>]*property=["']${name}["']`,
							"i",
						),
						new RegExp(
							`<meta[^>]*content=["']([^"']*)["'][^>]*name=["']${name}["']`,
							"i",
						),
					];

					for (const pattern of patterns) {
						const match = html.match(pattern);
						if (match) return match[1];
					}
					return null;
				};

				const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
				const urlObj = new URL(href);

				const data: UrlMetadata = {
					title:
						getMetaTag("og:title") ||
						getMetaTag("twitter:title") ||
						titleMatch?.[1] ||
						null,
					description:
						getMetaTag("og:description") ||
						getMetaTag("twitter:description") ||
						getMetaTag("description") ||
						null,
					website_image:
						getMetaTag("og:image") || getMetaTag("twitter:image") || null,
					favicon:
						getMetaTag("icon") ||
						getMetaTag("shortcut icon") ||
						`${urlObj.origin}/favicon.ico`,
					website_name: getMetaTag("og:site_name") || urlObj.hostname,
					url: href,
				};

				if (isMounted) {
					setMetadata(data);
					setIsLoading(false);
				}
			} catch (err) {
				if (isMounted) {
					setError(err as Error);
					setIsLoading(false);
				}
			}
		}

		fetchMetadata();

		return () => {
			isMounted = false;
		};
	}, [isInView, isValidUrl, href, metadata]);

	// Set up intersection observer to detect when element is in view
	useEffect(() => {
		const element = elementRef.current;
		if (!element || !href) return;

		const observer = new IntersectionObserver(
			([entry]) => {
				if (entry.isIntersecting) {
					setIsInView(true);
					observer.unobserve(element);
				}
			},
			{
				rootMargin: "100px", // Start fetching 100px before element comes into view
				threshold: 0.1,
			},
		);

		observer.observe(element);

		return () => {
			observer.unobserve(element);
		};
	}, [href]);

	if (!href) return null;

	return (
		<Tooltip>
			<TooltipTrigger asChild>
				<a
					ref={elementRef}
					href={href}
					className={className}
					rel="noopener noreferrer"
					target="_blank"
				>
					{children}
				</a>
			</TooltipTrigger>
			<TooltipContent className="max-w-[280px] border border-zinc-700 bg-zinc-900 p-3 text-white shadow-lg">
				{isLoading ? (
					<div className="flex justify-center p-5">
						<div className="size-5 animate-spin rounded-full border-2 border-zinc-700 border-t-white" />
					</div>
				) : error || !isValidUrl ? (
					<div className="flex items-center gap-2 p-3 text-red-400">
						<HugeiconsIcon icon={Globe02Icon} size={16} />
						<span className="text-sm">
							{!isValidUrl ? "Invalid URL" : "Failed to load preview"}
						</span>
					</div>
				) : metadata ? (
					<div className="flex w-full flex-col gap-2">
						{/* Website Image */}
						{metadata.website_image && validImage && (
							<div className="relative aspect-video w-full overflow-hidden rounded-lg">
								<Image
									src={metadata.website_image}
									alt="Website preview"
									fill
									className="rounded-lg object-cover"
									onError={() => setValidImage(false)}
								/>
							</div>
						)}

						{/* Website Name & Favicon */}
						{(metadata.website_name || (metadata.favicon && validFavicon)) && (
							<div className="flex items-center gap-2">
								{metadata.favicon && validFavicon ? (
									<Image
										width={20}
										height={20}
										alt="Favicon"
										className="size-5 rounded-full"
										src={metadata.favicon}
										onError={() => setValidFavicon(false)}
									/>
								) : (
									<HugeiconsIcon
										icon={Globe02Icon}
										size={20}
										className="text-gray-400"
									/>
								)}
								{metadata.website_name && (
									<div className="truncate text-sm font-semibold">
										{metadata.website_name}
									</div>
								)}
							</div>
						)}

						{/* Title */}
						{metadata.title && (
							<div className="truncate text-sm font-medium text-white">
								{metadata.title}
							</div>
						)}

						{/* Description */}
						{metadata.description && (
							<div className="line-clamp-3 text-xs text-gray-400 w-full">
								{metadata.description}
							</div>
						)}

						{/* URL Link */}
						<div className="truncate text-xs text-primary">
							{href.replace("https://", "").replace("http://", "")}
						</div>
					</div>
				) : (
					<div className="flex items-center gap-2 p-3">
						<HugeiconsIcon
							icon={Globe02Icon}
							size={16}
							className="text-gray-400"
						/>
						<span className="text-sm text-gray-400">No preview available</span>
					</div>
				)}
			</TooltipContent>
		</Tooltip>
	);
}

Update the import paths to match your project setup.

Similar screens