An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Add share button in UserMessage
Yoshiki Miura586e4889bacb
diff --git a/app/actions.tsx b/app/actions.tsxindex 0017b866..28e8525d 100644--- a/app/actions.tsx+++ b/app/actions.tsx@@ -229,6 +229,7 @@ async function submit(formData?: FormData, skip?: boolean) {export type AIState = {messages: AIMessage[]chatId: string+ isShareable?: boolean}export type UIState = {@@ -304,11 +305,19 @@ export const AI = createAI<AIState, UIState>({})export const getUIStateFromAIState = (aiState: Chat) => {+ const chatId = aiState.chatId+ const isShareable = aiState.isShareablereturn aiState.messages- .map(message => {+ .map((message, index) => {const { role, content, id, type, name } = message- if (!type || type === 'end') return null+ if (+ !type ||+ type === 'end' ||+ (!isShareable && type === 'related') ||+ (!isShareable && type === 'followup')+ )+ return nullswitch (role) {case 'user':@@ -319,7 +328,13 @@ export const getUIStateFromAIState = (aiState: Chat) => {const value = type === 'input' ? json.input : json.related_queryreturn {id,- component: <UserMessage message={value} />+ component: (+ <UserMessage+ message={value}+ chatId={chatId}+ showShare={index === 0 && isShareable}+ />+ )}case 'inquiry':return {diff --git a/app/page.tsx b/app/page.tsxindex 9d1edd25..a6ed82d0 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -7,7 +7,7 @@ export const maxDuration = 60export default function Page() {const id = nanoid()return (- <AI initialAIState={{ chatId: id, messages: [] }}>+ <AI initialAIState={{ chatId: id, messages: [], isShareable: true }}><Chat id={id} /></AI>)diff --git a/app/search/[id]/page.tsx b/app/search/[id]/page.tsxindex ac08d9cc..bbe0632a 100644--- a/app/search/[id]/page.tsx+++ b/app/search/[id]/page.tsx@@ -31,7 +31,13 @@ export default async function SearchPage({ params }: SearchPageProps) {}return (- <AI initialAIState={{ chatId: chat.id, messages: chat.messages }}>+ <AI+ initialAIState={{+ chatId: chat.id,+ messages: chat.messages,+ isShareable: true+ }}+ ><Chat id={params.id} /></AI>)diff --git a/app/share/[id]/page.tsx b/app/share/[id]/page.tsxindex 0112f21f..f1df9681 100644--- a/app/share/[id]/page.tsx+++ b/app/share/[id]/page.tsx@@ -1,6 +1,6 @@-import { notFound, redirect } from 'next/navigation'+import { notFound } from 'next/navigation'import { Chat } from '@/components/chat'-import { getChat } from '@/lib/actions/chat'+import { getSharedChat } from '@/lib/actions/chat'import { AI } from '@/app/actions'export const maxDuration = 60@@ -12,21 +12,21 @@ export interface SharePageProps {}export async function generateMetadata({ params }: SharePageProps) {- const chat = await getChat(params.id, 'anonymous')+ const chat = await getSharedChat(params.id)++ if (!chat || !chat.sharePath) {+ return notFound()+ }+return {title: chat?.title.toString().slice(0, 50) || 'Search'}}export default async function SharePage({ params }: SharePageProps) {- const userId = 'anonymous'- const chat = await getChat(params.id, userId)-- if (!chat) {- redirect('/')- }+ const chat = await getSharedChat(params.id)- if (chat?.userId !== userId) {+ if (!chat || !chat.sharePath) {notFound()}diff --git a/components/chat-share.tsx b/components/chat-share.tsxnew file mode 100644index 00000000..407f138a--- /dev/null+++ b/components/chat-share.tsx@@ -0,0 +1,81 @@+'use client'++import { useState, useTransition } from 'react'+import { Button } from './ui/button'+import { Share } from 'lucide-react'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTrigger+} from './ui/dialog'+import { shareChat } from '@/lib/actions/chat'+import { toast } from 'sonner'+import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard'+import { Spinner } from './ui/spinner'+import { DialogDescription, DialogTitle } from '@radix-ui/react-dialog'++interface ChatShareProps {+ chatId: string+ className?: string+}++export function ChatShare({ chatId, className }: ChatShareProps) {+ const [open, setOpen] = useState(false)+ const [pending, startTransition] = useTransition()+ const { copyToClipboard } = useCopyToClipboard({ timeout: 1000 })++ const handleClick = async () => {+ startTransition(async () => {+ const result = await shareChat(chatId)+ if (!result) {+ toast.error('Failed to share chat')+ }++ if (!result?.sharePath) {+ toast.error('Could not copy link to clipboard')+ return+ }++ const url = new URL(result.sharePath, window.location.origin)+ copyToClipboard(url.toString())+ toast.success('Link copied to clipboard')+ })+ }++ return (+ <div className={className}>+ <Dialog+ open={open}+ onOpenChange={open => setOpen(open)}+ aria-labelledby="share-dialog-title"+ aria-describedby="share-dialog-description"+ >+ <DialogTrigger asChild>+ <Button+ className="rounded-full"+ size="icon"+ variant={'ghost'}+ onClick={() => setOpen(true)}+ >+ <Share size={14} />+ </Button>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Share link to search result</DialogTitle>+ <DialogDescription>+ Anyone with the link will be able to view this search result.+ </DialogDescription>+ </DialogHeader>+ <DialogFooter className="items-center">+ <Button onClick={handleClick} disabled={pending} size="sm">+ {pending ? <Spinner /> : 'Copy link'}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}diff --git a/components/chat.tsx b/components/chat.tsxindex 6a7c937a..ed70841a 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -30,7 +30,7 @@ export function Chat({ id }: ChatProps) {}, [aiState, router])return (- <div className="px-8 sm:px-12 pt-6 md:pt-8 pb-14 md:pb-24 max-w-3xl mx-auto flex flex-col space-y-3 md:space-y-4">+ <div className="px-8 sm:px-12 pt-12 md:pt-14 pb-14 md:pb-24 max-w-3xl mx-auto flex flex-col space-y-3 md:space-y-4"><ChatMessages messages={messages} /><ChatPanel messages={messages} /></div>diff --git a/components/collapsible-message.tsx b/components/collapsible-message.tsxindex 028fd31d..a094236a 100644--- a/components/collapsible-message.tsx+++ b/components/collapsible-message.tsx@@ -58,6 +58,7 @@ export const CollapsibleMessage: React.FC<CollapsibleMessageProps> = ({className={cn('-mt-3 rounded-full')}><ChevronDown+ size={14}className={cn(open ? 'rotate-180' : 'rotate-0','h-4 w-4 transition-all'diff --git a/components/user-message.tsx b/components/user-message.tsxindex 678070d4..8ff7000e 100644--- a/components/user-message.tsx+++ b/components/user-message.tsx@@ -1,13 +1,21 @@import React from 'react'+import { ChatShare } from './chat-share'type UserMessageProps = {message: string+ chatId?: string+ showShare?: boolean}-export const UserMessage: React.FC<UserMessageProps> = ({ message }) => {+export const UserMessage: React.FC<UserMessageProps> = ({+ message,+ chatId,+ showShare = false+}) => {return (- <div className="mt-6">- <div className="text-xl">{message}</div>+ <div className="flex items-center w-full space-x-1 mt-2">+ <div className="text-xl flex-1">{message}</div>+ {showShare && chatId && <ChatShare chatId={chatId} />}</div>)}diff --git a/lib/hooks/use-copy-to-clipboard.ts b/lib/hooks/use-copy-to-clipboard.tsnew file mode 100644index 00000000..0d190799--- /dev/null+++ b/lib/hooks/use-copy-to-clipboard.ts@@ -0,0 +1,33 @@+'use client'++import { useState } from 'react'++export interface useCopyToClipboardProps {+ timeout?: number+}++export function useCopyToClipboard({+ timeout = 2000+}: useCopyToClipboardProps) {+ const [isCopied, setIsCopied] = useState<Boolean>(false)++ const copyToClipboard = (value: string) => {+ if (typeof window === 'undefined' || !navigator.clipboard?.writeText) {+ return+ }++ if (!value) {+ return+ }++ navigator.clipboard.writeText(value).then(() => {+ setIsCopied(true)++ setTimeout(() => {+ setIsCopied(false)+ }, timeout)+ })+ }++ return { isCopied, copyToClipboard }+}