GIFs work now

This commit is contained in:
2026-06-30 15:11:15 +02:00
parent 1e8f979cf9
commit 7a5e833722
5 changed files with 401 additions and 90 deletions
+57
View File
@@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
const GIPHY_API_KEY = process.env.GIPHY_API_KEY
const GIPHY_BASE = "https://api.giphy.com/v1/gifs"
export async function GET(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
if (!GIPHY_API_KEY) {
return NextResponse.json({ error: "GIPHY API key not configured" }, { status: 500 })
}
const { searchParams } = new URL(request.url)
const type = searchParams.get("type") || "trending"
const query = searchParams.get("q") || ""
const offset = parseInt(searchParams.get("offset") || "0", 10)
const limit = Math.min(parseInt(searchParams.get("limit") || "20", 10), 50)
let url: string
if (type === "search" && query) {
url = `${GIPHY_BASE}/search?api_key=${GIPHY_API_KEY}&q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}&rating=g`
} else {
url = `${GIPHY_BASE}/trending?api_key=${GIPHY_API_KEY}&limit=${limit}&offset=${offset}&rating=g`
}
const res = await fetch(url)
if (!res.ok) {
const errBody = await res.text()
console.error("GIPHY API error:", res.status, errBody)
return NextResponse.json({ error: `GIPHY API error (${res.status}): ${errBody}` }, { status: res.status })
}
const data = await res.json()
const gifs = (data.data || []).map((gif: any) => ({
id: gif.id,
title: gif.title,
url: gif.images?.original?.url || "",
previewUrl: gif.images?.fixed_width?.url || "",
previewHeight: gif.images?.fixed_width?.height || 150,
width: gif.images?.original?.width || 0,
height: gif.images?.original?.height || 0,
}))
return NextResponse.json({
gifs,
pagination: data.pagination || { total_count: 0, count: gifs.length, offset },
})
} catch (error: any) {
console.error("GIPHY proxy error:", error)
return NextResponse.json({ error: error.message || "Internal server error" }, { status: 500 })
}
}
+60 -23
View File
@@ -1,8 +1,8 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
const TENOR_API_KEY = process.env.TENOR_API_KEY || ""
const TENOR_BASE = "https://tenor.googleapis.com/v2"
const GIPHY_API_KEY = process.env.GIPHY_API_KEY
const GIPHY_BASE = "https://api.giphy.com/v1/gifs"
export async function GET(request: NextRequest) {
try {
@@ -12,41 +12,78 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const q = searchParams.get("q") || ""
const limit = Math.min(parseInt(searchParams.get("limit") || "20", 10), 50)
const pos = searchParams.get("pos") || ""
const pos = parseInt(searchParams.get("pos") || "0", 10) || 0
if (!TENOR_API_KEY) {
if (!GIPHY_API_KEY) {
console.error("Missing GIPHY_API_KEY environment variable")
return NextResponse.json({ results: [], noKey: true })
}
const endpoint = q
? `${TENOR_BASE}/search?q=${encodeURIComponent(q)}&key=${TENOR_API_KEY}&limit=${limit}&media_filter=minimal`
: `${TENOR_BASE}/featured?key=${TENOR_API_KEY}&limit=${limit}&media_filter=minimal`
const url = pos ? `${endpoint}&pos=${pos}` : endpoint
let data: any
if (q) {
const url = `${GIPHY_BASE}/search?api_key=${GIPHY_API_KEY}&q=${encodeURIComponent(q)}&limit=${limit}&offset=${pos}&rating=g`
const res = await fetch(url, { signal: AbortSignal.timeout(8000) })
if (!res.ok) {
return NextResponse.json({ results: [], error: "Tenor API error" }, { status: 502 })
const errBody = await res.text()
console.error("GIPHY API search error:", res.status, errBody)
return NextResponse.json({ results: [], error: `GIPHY error: ${errBody}` }, { status: 502 })
}
data = await res.json()
} else {
const trendingUrl = `${GIPHY_BASE}/trending?api_key=${GIPHY_API_KEY}&limit=${limit}&offset=${pos}&rating=g`
const trendingRes = await fetch(trendingUrl, { signal: AbortSignal.timeout(8000) })
const data = await res.json()
const results = (data.results || []).map((item: any) => {
const media = item.media_formats?.gif || item.media_formats?.tinygif || {}
const preview = item.media_formats?.tinygif || item.media_formats?.gif || {}
if (trendingRes.ok) {
data = await trendingRes.json()
if (!data.data?.length && pos === 0) {
console.log("Trending returned no results, falling back to default search")
const fallbackUrl = `${GIPHY_BASE}/search?api_key=${GIPHY_API_KEY}&q=funny&limit=${limit}&offset=${pos}&rating=g`
const fallbackRes = await fetch(fallbackUrl, { signal: AbortSignal.timeout(8000) })
if (!fallbackRes.ok) {
const errBody = await fallbackRes.text()
console.error("GIPHY fallback search error:", fallbackRes.status, errBody)
return NextResponse.json({ results: [], error: `GIPHY error: ${errBody}` }, { status: 502 })
}
data = await fallbackRes.json()
}
} else {
const errBody = await trendingRes.text()
console.error("GIPHY trending error:", trendingRes.status, errBody)
console.log("Trending failed, falling back to default search")
const fallbackUrl = `${GIPHY_BASE}/search?api_key=${GIPHY_API_KEY}&q=funny&limit=${limit}&offset=${pos}&rating=g`
const fallbackRes = await fetch(fallbackUrl, { signal: AbortSignal.timeout(8000) })
if (!fallbackRes.ok) {
const fallbackErr = await fallbackRes.text()
console.error("GIPHY fallback search error:", fallbackRes.status, fallbackErr)
return NextResponse.json({ results: [], error: `GIPHY error: ${fallbackErr}` }, { status: 502 })
}
data = await fallbackRes.json()
}
}
const results = (data.data || []).map((item: any) => {
const dims = item.images?.original
return {
id: item.id,
title: item.title || "",
url: media.url || "",
previewUrl: preview.url || "",
width: media.dims?.[0] || 200,
height: media.dims?.[1] || 200,
url: dims?.url || "",
previewUrl: item.images?.fixed_width?.url || "",
width: dims?.width ? parseInt(dims.width, 10) : 200,
height: dims?.height ? parseInt(dims.height, 10) : 200,
}
})
return NextResponse.json({ results, next: data.next || "" })
} catch (error) {
console.error("GIF API error:", error)
return NextResponse.json({ results: [], error: "Failed to fetch GIFs" }, { status: 500 })
const nextOffset = pos + results.length
const total = data.pagination?.total_count || 0
const hasMore = total ? nextOffset < total : results.length === limit
const nextPos = hasMore ? String(nextOffset) : ""
return NextResponse.json({ results, next: nextPos })
} catch (error: any) {
console.error("GIF proxy error:", error)
const message = error?.message === "Failed to fetch"
? "Could not reach the GIF service."
: "Failed to fetch GIFs."
return NextResponse.json({ results: [], error: message }, { status: 500 })
}
}
+70 -62
View File
@@ -2,6 +2,7 @@
import { useState, useRef, useEffect, Fragment, forwardRef, useImperativeHandle, useCallback } from "react"
import { Bot, Terminal } from "lucide-react"
import { GifPicker } from "./gif-picker"
function linkifyText(text: string) {
const urlRegex = /(https?:\/\/[^\s<]+[^\s<.,;:!?)\]}>])/
@@ -35,27 +36,17 @@ function formatContent(text: string) {
interface ChatMessage {
role: "user" | "assistant"
content: string
gif?: {
url: string
previewUrl: string
title: string
}
}
interface AIChatProps {
onMessageSent?: (msg: string) => void
}
const quickActions = [
{ icon: "✉️", iconBg: "bg-primary/10", iconColor: "text-primary", title: "Cold Email Template", desc: "Generate targeted outreach emails", prompt: "Write a cold email template for a Software Developer" },
{ icon: "🛡️", iconBg: "bg-[#3b82f6]/10", iconColor: "text-[#3b82f6]", title: "Handle Objections", desc: "Get scripts for common objections", prompt: "Give me objection handling scripts for sales" },
{ icon: "🎯", iconBg: "bg-[#8b5cf6]/10", iconColor: "text-[#8b5cf6]", title: "Target Industry", desc: "Find leads in specific industries", prompt: "How do I target leads in the tech industry" },
{ icon: "📋", iconBg: "bg-[#22c55e]/10", iconColor: "text-[#22c55e]", title: "Build Lead List", desc: "Strategies to grow your pipeline", prompt: "Help me build a lead list strategy" },
{ icon: "📞", iconBg: "bg-primary/10", iconColor: "text-primary", title: "Call Scripts", desc: "Proven phone sales scripts", prompt: "Give me a cold call script for outreach" },
{ icon: "📊", iconBg: "bg-[#ec4899]/10", iconColor: "text-[#ec4899]", title: "Sales Strategy", desc: "Industry specific sales tactics", prompt: "What sales strategies work best per industry" },
]
const commandPills = [
{ icon: "📋", label: "Lists", prompt: "lists" },
{ icon: "👥", label: "Leads", prompt: "leads" },
{ icon: "💡", label: "Tips", prompt: "Give me some sales tips" },
{ icon: "✉️", label: "Templates", prompt: "Show me email templates" },
]
export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatProps>(({ onMessageSent }, ref) => {
const [messages, setMessages] = useState<ChatMessage[]>([])
@@ -63,9 +54,12 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
const [loading, setLoading] = useState(false)
const [error, setError] = useState("")
const [bootState, setBootState] = useState<"booting" | "ready" | "error">("booting")
const [showGifPicker, setShowGifPicker] = useState(false)
const messagesEndRef = useRef<HTMLDivElement>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const hasUserMessage = messages.some(m => m.role === "user")
const loadedFromStorage = useRef(false)
useImperativeHandle(ref, () => ({
fillInput(text: string) {
@@ -74,6 +68,44 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
},
}), [])
const handleGifSelect = useCallback((gif: { url: string; previewUrl: string; title: string }) => {
setMessages((prev) => [...prev, { role: "user", content: gif.title || "Sent a GIF", gif }])
setShowGifPicker(false)
}, [])
useEffect(() => {
if (showGifPicker) {
const handler = (e: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setShowGifPicker(false)
}
}
document.addEventListener("mousedown", handler)
return () => document.removeEventListener("mousedown", handler)
}
}, [showGifPicker])
useEffect(() => {
const saved = localStorage.getItem("ai-chat-messages")
if (saved) {
try {
const parsed = JSON.parse(saved)
if (Array.isArray(parsed) && parsed.length > 0) {
setMessages(parsed)
loadedFromStorage.current = true
}
} catch {}
} else {
loadedFromStorage.current = false
}
}, [])
useEffect(() => {
if (messages.length > 0) {
localStorage.setItem("ai-chat-messages", JSON.stringify(messages))
}
}, [messages])
const checkServer = useCallback(async () => {
try {
const res = await fetch("/api/ai/chat", {
@@ -92,6 +124,7 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
}, [])
useEffect(() => {
if (loadedFromStorage.current) return
fetch("/api/ai/jobs")
.then((r) => r.json())
.then((data) => {
@@ -176,16 +209,6 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
t.style.height = t.scrollHeight + "px"
}, [])
const handleQuickAction = useCallback((prompt: string) => {
setInput(prompt)
setTimeout(() => sendMessage(prompt), 50)
}, [sendMessage])
const handleCommandPill = useCallback((prompt: string) => {
setInput(prompt)
setTimeout(() => sendMessage(prompt), 50)
}, [sendMessage])
if (bootState === "booting") {
return (
<div className="flex items-center justify-center h-full">
@@ -216,46 +239,21 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
return (
<div className="flex-1 flex flex-col overflow-y-auto" style={{ backgroundImage: "radial-gradient(circle, hsl(var(--border)) 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
<div className="flex-1 flex items-center justify-center">
<div className="max-w-lg mx-auto pt-12 pb-6 px-4">
<div className="max-w-lg mx-auto px-4">
<div className="float-in">
<div className="w-16 h-16 rounded-2xl mx-auto mb-6 bg-gradient-to-br from-primary to-primary flex items-center justify-center shadow-[0_0_40px_hsl(var(--primary)_/_0.3)]">
<Bot className="h-8 w-8 text-white" />
</div>
<h2 className="text-foreground font-bold text-2xl text-center mb-2">What can I help you with?</h2>
<p className="text-muted-foreground text-sm text-center mb-8 leading-relaxed">Your AI sales assistant is ready. Choose a quick action or type your question below.</p>
</div>
<div className="grid grid-cols-2 gap-3">
{quickActions.map((action, i) => (
<div
key={i}
onClick={() => handleQuickAction(action.prompt)}
className="float-in bg-card hover:bg-card/80 rounded-xl p-4 border border-border hover:border-primary/30 cursor-pointer transition-all duration-200 hover:shadow-[0_4px_20px_hsl(var(--primary)_/_0.1)] hover:-translate-y-0.5"
style={{ animationDelay: `${0.1 + i * 0.05}s` }}
>
<div className={`w-9 h-9 rounded-lg ${action.iconBg} ${action.iconColor} flex items-center justify-center text-lg`}>{action.icon}</div>
<h3 className="text-foreground text-sm font-medium mt-3">{action.title}</h3>
<p className="text-muted-foreground text-xs mt-1">{action.desc}</p>
</div>
))}
</div>
<div className="flex gap-2 justify-center mt-6 flex-wrap">
{commandPills.map((pill, i) => (
<div
key={i}
onClick={() => handleCommandPill(pill.prompt)}
className="bg-card border border-border hover:border-primary/40 hover:bg-card/80 rounded-full px-4 py-2 text-xs text-muted-foreground hover:text-primary transition-all duration-200 cursor-pointer flex items-center gap-1.5"
>
<span>{pill.icon}</span>
<span>{pill.label}</span>
</div>
))}
<p className="text-muted-foreground text-sm text-center leading-relaxed">Your AI sales assistant is ready. Choose a quick action or type your question below.</p>
</div>
</div>
</div>
<div className="sticky bottom-0 bg-background/95 backdrop-blur-md px-4 py-4">
<div className="max-w-3xl mx-auto">
<div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_rgba(249,115,22,0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3">
<button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-lg">📎</button>
<div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_hsl(var(--primary)_/_0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3 relative" ref={containerRef}>
<button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-[11px] font-semibold tracking-wide" onClick={() => setShowGifPicker((v) => !v)}>GIF</button>
{showGifPicker && <GifPicker onSelect={handleGifSelect} onClose={() => setShowGifPicker(false)} />}
<textarea
ref={textareaRef}
value={input}
@@ -270,7 +268,7 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
type="button"
onClick={() => sendMessage()}
disabled={!input.trim()}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_rgba(249,115,22,0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_hsl(var(--primary)_/_0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
>
</button>
@@ -307,7 +305,16 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
<div className="flex gap-3 items-start flex-row-reverse">
<div className="flex-1 min-w-0 flex justify-end">
<div className="bg-gradient-to-br from-primary to-primary rounded-2xl rounded-tr-sm px-5 py-4 max-w-[75%]">
{msg.gif ? (
<img
src={msg.gif.url}
alt={msg.gif.title || "GIF"}
className="w-full rounded-lg max-h-64 object-cover"
loading="lazy"
/>
) : (
<div className="text-white text-sm leading-7 whitespace-pre-wrap">{msg.content}</div>
)}
</div>
</div>
</div>
@@ -320,9 +327,9 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
<Bot className="h-4 w-4" />
</div>
<div className="bg-card rounded-2xl rounded-tl-sm border border-border border-l-2 border-l-primary px-5 py-4 inline-flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full bg-[#f97316] dot-1" />
<span className="w-2 h-2 rounded-full bg-[#f97316] dot-2" />
<span className="w-2 h-2 rounded-full bg-[#f97316] dot-3" />
<span className="w-2 h-2 rounded-full bg-primary dot-1" />
<span className="w-2 h-2 rounded-full bg-primary dot-2" />
<span className="w-2 h-2 rounded-full bg-primary dot-3" />
</div>
</div>
)}
@@ -337,8 +344,9 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
{error}
</div>
)}
<div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_rgba(249,115,22,0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3">
<button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-lg">📎</button>
<div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_hsl(var(--primary)_/_0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3 relative" ref={containerRef}>
<button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-[11px] font-semibold tracking-wide" onClick={() => setShowGifPicker((v) => !v)}>GIF</button>
{showGifPicker && <GifPicker onSelect={handleGifSelect} onClose={() => setShowGifPicker(false)} />}
<textarea
ref={textareaRef}
value={input}
@@ -353,7 +361,7 @@ export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatPr
type="button"
onClick={() => sendMessage()}
disabled={!input.trim()}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_rgba(249,115,22,0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_hsl(var(--primary)_/_0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
>
</button>
+193
View File
@@ -0,0 +1,193 @@
"use client"
import { useState, useRef, useEffect, useCallback } from "react"
import { Search, Loader2, ImageIcon } from "lucide-react"
interface GifResult {
id: string
title: string
url: string
previewUrl: string
previewHeight: number
width: number
height: number
}
interface GifPickerProps {
onSelect: (gif: { url: string; previewUrl: string; title: string }) => void
onClose: () => void
}
const SEARCH_CACHE = new Map<string, GifResult[]>()
export function GifPicker({ onSelect, onClose }: GifPickerProps) {
const [gifs, setGifs] = useState<GifResult[]>([])
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [hasMore, setHasMore] = useState(true)
const [error, setError] = useState("")
const sentinelRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const searchTimeoutRef = useRef<ReturnType<typeof setTimeout>>()
const fetchGifs = useCallback(async (q: string, off: number, append: boolean) => {
if (off === 0) {
const cacheKey = q || "__trending__"
const cached = SEARCH_CACHE.get(cacheKey)
if (cached) {
setGifs(cached)
setLoading(false)
setHasMore(true)
setOffset(cached.length)
return
}
}
try {
if (!append) setLoading(true)
else setLoadingMore(true)
setError("")
const params = new URLSearchParams()
if (q) {
params.set("type", "search")
params.set("q", q)
}
params.set("offset", String(off))
params.set("limit", "20")
const res = await fetch(`/api/ai/giphy?${params}`)
if (!res.ok) {
const data = await res.json()
throw new Error(data.error || "Failed to fetch GIFs")
}
const data = await res.json()
const newGifs: GifResult[] = data.gifs || []
if (append) {
setGifs((prev) => [...prev, ...newGifs])
} else {
setGifs(newGifs)
if (off === 0 && !q) {
SEARCH_CACHE.set("__trending__", newGifs)
}
if (q) {
SEARCH_CACHE.set(q, newGifs)
}
}
setOffset(off + newGifs.length)
setHasMore(newGifs.length === 20)
} catch (err: any) {
setError(err.message || "Failed to load GIFs")
} finally {
setLoading(false)
setLoadingMore(false)
}
}, [])
useEffect(() => {
fetchGifs("", 0, false)
}, [fetchGifs])
useEffect(() => {
inputRef.current?.focus()
}, [])
useEffect(() => {
if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current)
if (!search.trim()) {
fetchGifs("", 0, false)
return
}
searchTimeoutRef.current = setTimeout(() => {
fetchGifs(search.trim(), 0, false)
}, 400)
return () => {
if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current)
}
}, [search, fetchGifs])
useEffect(() => {
const sentinel = sentinelRef.current
if (!sentinel) return
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !loadingMore && !loading) {
fetchGifs(search.trim(), offset, true)
}
},
{ rootMargin: "200px" }
)
observer.observe(sentinel)
return () => observer.disconnect()
}, [hasMore, loadingMore, loading, offset, search, fetchGifs])
return (
<div className="absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-2xl shadow-xl shadow-black/20 overflow-hidden z-50">
<div className="p-3 border-b border-border">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<input
ref={inputRef}
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search GIFs..."
className="w-full bg-muted/50 text-foreground text-sm rounded-xl pl-9 pr-4 py-2.5 outline-none focus:ring-2 focus:ring-primary/30 placeholder:text-muted-foreground/60"
/>
</div>
</div>
<div className="overflow-y-auto" style={{ maxHeight: "360px" }}>
{loading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-6 w-6 animate-spin text-primary" />
</div>
) : error ? (
<div className="flex flex-col items-center justify-center py-16 px-4 text-center">
<ImageIcon className="h-8 w-8 text-muted-foreground mb-2" />
<p className="text-sm text-muted-foreground">{error}</p>
</div>
) : gifs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 px-4 text-center">
<ImageIcon className="h-8 w-8 text-muted-foreground mb-2" />
<p className="text-sm text-muted-foreground">No GIFs found.</p>
</div>
) : (
<>
<div className="grid grid-cols-2 gap-2 p-3">
{gifs.map((gif) => (
<button
key={gif.id}
type="button"
onClick={() => onSelect({ url: gif.url, previewUrl: gif.previewUrl, title: gif.title })}
className="relative rounded-xl overflow-hidden bg-muted/30 hover:ring-2 hover:ring-primary/50 transition-all duration-200 aspect-video"
title={gif.title}
>
<img
src={gif.previewUrl}
alt={gif.title || "GIF"}
loading="lazy"
className="w-full h-full object-cover"
/>
</button>
))}
</div>
{loadingMore && (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
</div>
)}
{hasMore && <div ref={sentinelRef} className="h-4" />}
</>
)}
</div>
</div>
)
}
+18 -2
View File
@@ -57,7 +57,13 @@ export default function MediaPicker({ onEmojiSelect, onMediaSelect, onClose, the
return () => document.removeEventListener("mousedown", handleClick)
}, [onClose])
useEffect(() => { setRecentGifs(getRecent(RECENT_GIFS_KEY)) }, [])
useEffect(() => {
setRecentGifs(getRecent(RECENT_GIFS_KEY))
if (!navigator.onLine) {
console.warn("[GIF Picker] Browser is offline — GIF service may be unavailable")
}
}, [])
useEffect(() => { setRecentStickers(getRecent(RECENT_STICKERS_KEY)) }, [])
const fetchGifs = useCallback(async (query: string, pos = "") => {
@@ -76,6 +82,7 @@ export default function MediaPicker({ onEmojiSelect, onMediaSelect, onClose, the
const res = await fetch(`/api/gifs?${params}`)
const data = await res.json()
if (data.noKey) {
console.error("[GIF Picker] GIPHY_API_KEY is not configured on the server. Add GIPHY_API_KEY to .env.local and restart the dev server.")
setGifUnavailable(true)
setGifResults([])
} else if (data.results) {
@@ -103,6 +110,15 @@ export default function MediaPicker({ onEmojiSelect, onMediaSelect, onClose, the
return () => { if (searchTimer.current) clearTimeout(searchTimer.current) }
}, [tab, gifQuery, fetchGifs])
useEffect(() => {
if (tab !== "gif" || !gifError) return
const interval = setInterval(() => {
if (gifUnavailable) return
fetchGifs(gifQuery.trim())
}, 15000)
return () => clearInterval(interval)
}, [tab, gifError, gifUnavailable, gifQuery, fetchGifs])
const handleGifSelect = (gif: any) => {
const content = JSON.stringify({ gif: gif.url, w: gif.width, h: gif.height })
addRecent(RECENT_GIFS_KEY, gif.id)
@@ -208,7 +224,7 @@ export default function MediaPicker({ onEmojiSelect, onMediaSelect, onClose, the
) : gifUnavailable ? (
<div className="flex flex-col items-center justify-center h-48 text-muted-foreground text-sm gap-2">
<Image className="h-8 w-8 opacity-40" />
<span>GIFs are temporarily unavailable.</span>
<span>GIF service not configured.</span>
</div>
) : gifError ? (
<div className="flex flex-col items-center justify-center h-48 text-muted-foreground text-sm gap-2">