aboutsummaryrefslogtreecommitdiff
path: root/apps/web/components/new/add-document/link.tsx
blob: 2efb67dcacbbfdfe8028097240b4a19e00ee6fb0 (plain) (blame)
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
"use client"

import { useState, useEffect } from "react"
import { cn } from "@lib/utils"
import { Button } from "@ui/components/button"
import { dmSansClassName } from "@/lib/fonts"
import { useHotkeys } from "react-hotkeys-hook"
import { Image as ImageIcon, Loader2 } from "lucide-react"
import { toast } from "sonner"

export interface LinkData {
	url: string
	title: string
	description: string
	image?: string
}

interface LinkContentProps {
	onSubmit?: (data: LinkData) => void
	onDataChange?: (data: LinkData) => void
	isSubmitting?: boolean
	isOpen?: boolean
}

export function LinkContent({
	onSubmit,
	onDataChange,
	isSubmitting,
	isOpen,
}: LinkContentProps) {
	const [url, setUrl] = useState("")
	const [title, setTitle] = useState("")
	const [description, setDescription] = useState("")
	const [image, setImage] = useState<string | undefined>(undefined)
	const [isPreviewLoading, setIsPreviewLoading] = useState(false)

	const canSubmit = url.trim().length > 0 && !isSubmitting

	const handleSubmit = () => {
		if (canSubmit && onSubmit) {
			let normalizedUrl = url.trim()
			if (
				!normalizedUrl.startsWith("http://") &&
				!normalizedUrl.startsWith("https://")
			) {
				normalizedUrl = `https://${normalizedUrl}`
			}
			onSubmit({ url: normalizedUrl, title, description })
		}
	}

	const updateData = (
		newUrl: string,
		newTitle: string,
		newDescription: string,
		newImage?: string,
	) => {
		onDataChange?.({
			url: newUrl,
			title: newTitle,
			description: newDescription,
			...(newImage && { image: newImage }),
		})
	}

	const handleUrlChange = (newUrl: string) => {
		setUrl(newUrl)
		updateData(newUrl, title, description, image)
	}

	const handleTitleChange = (newTitle: string) => {
		setTitle(newTitle)
		updateData(url, newTitle, description)
	}

	const handleDescriptionChange = (newDescription: string) => {
		setDescription(newDescription)
		updateData(url, title, newDescription, image)
	}

	const handlePreviewLink = async () => {
		if (!url.trim()) {
			toast.error("Please enter a URL first")
			return
		}

		let normalizedUrl = url.trim()
		if (
			!normalizedUrl.startsWith("http://") &&
			!normalizedUrl.startsWith("https://")
		) {
			normalizedUrl = `https://${normalizedUrl}`
			setUrl(normalizedUrl)
			updateData(normalizedUrl, title, description, image)
		}

		setIsPreviewLoading(true)
		try {
			const response = await fetch(
				`/api/og?url=${encodeURIComponent(normalizedUrl)}`,
			)

			if (!response.ok) {
				const errorData = await response.json().catch(() => ({}))
				throw new Error(errorData.error || "Failed to fetch preview")
			}

			const data = await response.json()

			const newTitle = data.title || ""
			const newDescription = data.description || ""
			const newImage = data.image || undefined

			setTitle(newTitle)
			setDescription(newDescription)
			setImage(newImage)
			updateData(url, newTitle, newDescription, newImage)

			if (!newTitle && !newDescription && !newImage) {
				toast.info("No Open Graph data found for this URL")
			} else {
				toast.success("Preview loaded successfully")
			}
		} catch (error) {
			console.error("Preview error:", error)
			toast.error(
				error instanceof Error ? error.message : "Failed to load preview",
			)
		} finally {
			setIsPreviewLoading(false)
		}
	}

	useHotkeys("mod+enter", handleSubmit, {
		enabled: isOpen && canSubmit,
		enableOnFormTags: ["INPUT", "TEXTAREA"],
	})

	// Reset content when modal closes
	useEffect(() => {
		if (!isOpen) {
			setUrl("")
			setTitle("")
			setDescription("")
			setImage(undefined)
			onDataChange?.({ url: "", title: "", description: "" })
		}
	}, [isOpen, onDataChange])

	return (
		<div className={cn("flex flex-col space-y-4 pt-4 mb-4", dmSansClassName())}>
			<div>
				<p
					className={cn("text-[16px] font-medium pl-2 pb-2", dmSansClassName())}
				>
					Paste a link to turn it into a memory
				</p>
				<div className="flex relative">
					<input
						type="text"
						value={url}
						onChange={(e) => handleUrlChange(e.target.value)}
						placeholder="https://example.com"
						disabled={isSubmitting}
						className="w-full p-4 rounded-xl bg-[#14161A] shadow-inside-out disabled:opacity-50 outline-1 outline-transparent focus:outline-[#525D6EB2]"
					/>
					<Button
						variant="linkPreview"
						className="absolute right-2 top-2"
						disabled={isSubmitting || isPreviewLoading || !url.trim()}
						onClick={handlePreviewLink}
					>
						{isPreviewLoading ? (
							<>
								<Loader2 className="size-4 animate-spin mr-2" />
								Loading...
							</>
						) : (
							"Preview Link"
						)}
					</Button>
				</div>
			</div>
			<div className="bg-[#14161A] rounded-[14px] py-6 px-4 space-y-4 shadow-inside-out">
				<div>
					<p className="pl-2 pb-2 font-semibold text-[16px] text-[#737373]">
						Link title
					</p>
					<input
						type="text"
						value={title}
						onChange={(e) => handleTitleChange(e.target.value)}
						placeholder="Mahesh Sanikommu - Portfolio"
						disabled
						className="w-full px-4 py-3 bg-[#0F1217] rounded-xl disabled:opacity-50 outline-1 outline-transparent focus:outline-[#525D6EB2]"
					/>
				</div>
				<div>
					<p className="pl-2 pb-2 font-semibold text-[16px] text-[#737373]">
						Link description
					</p>
					<textarea
						value={description}
						onChange={(e) => handleDescriptionChange(e.target.value)}
						placeholder="Portfolio website of Mahesh Sanikommu"
						disabled
						className="w-full px-4 py-3 bg-[#0F1217] rounded-xl resize-none disabled:opacity-50 outline-1 outline-transparent focus:outline-[#525D6EB2]"
					/>
				</div>
				<div>
					<p className="pl-2 pb-2 font-semibold text-[16px] text-[#737373]">
						Link Preview Image
					</p>
					{image ? (
						<div className="w-full max-w-md aspect-4/2 bg-[#0F1217] rounded-xl overflow-hidden">
							<img
								src={image}
								alt={title || "Link preview"}
								className="w-full h-full object-cover"
								onError={(e) => {
									e.currentTarget.style.display = "none"
									e.currentTarget.parentElement?.classList.add("opacity-50")
									e.currentTarget.parentElement?.classList.add("flex")
									e.currentTarget.parentElement?.classList.add("items-center")
									e.currentTarget.parentElement?.classList.add("justify-center")
								}}
							/>
						</div>
					) : (
						<div className="w-full max-w-md aspect-4/2 bg-[#0F1217] opacity-50 rounded-xl flex items-center justify-center">
							<ImageIcon className="w-8 h-8 text-[#737373]" />
						</div>
					)}
				</div>
			</div>
		</div>
	)
}