The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
add realtime chat example (#34514)
Jordi Enricdaa33f472316
diff --git a/apps/ui-library/__registry__/index.tsx b/apps/ui-library/__registry__/index.tsxindex d094b8047a0..99400b2c1a6 100644--- a/apps/ui-library/__registry__/index.tsx+++ b/apps/ui-library/__registry__/index.tsx@@ -247,6 +247,54 @@ export const Index: Record<string, any> = {chunks: []},+ "realtime-chat-nextjs": {+ name: "realtime-chat-nextjs",+ type: "registry:component",+ registryDependencies: ["input","button"],+ component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),+ source: "",+ files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ }+ ,+ "realtime-chat-react": {+ name: "realtime-chat-react",+ type: "registry:component",+ registryDependencies: ["input","button"],+ component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),+ source: "",+ files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/react/lib/supabase/client.ts"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ }+ ,+ "realtime-chat-react-router": {+ name: "realtime-chat-react-router",+ type: "registry:component",+ registryDependencies: ["input","button"],+ component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),+ source: "",+ files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ }+ ,+ "realtime-chat-tanstack": {+ name: "realtime-chat-tanstack",+ type: "registry:component",+ registryDependencies: ["input","button"],+ component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),+ source: "",+ files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],+ category: "undefined",+ subcategory: "undefined",+ chunks: []+ }+ ,"supabase-client-nextjs": {name: "supabase-client-nextjs",type: "registry:lib",diff --git a/apps/ui-library/app/example/realtime-chat/layout.tsx b/apps/ui-library/app/example/realtime-chat/layout.tsxnew file mode 100644index 00000000000..f4413161db8--- /dev/null+++ b/apps/ui-library/app/example/realtime-chat/layout.tsx@@ -0,0 +1,19 @@+import { Metadata } from 'next'+import { BaseInjector } from './../base-injector'++export const metadata: Metadata = {+ title: 'Realtime Chat Example',+}++export default function RootLayout({ children }: { children: React.ReactNode }) {+ return (+ <>+ <BaseInjector />+ <div className="flex w-full items-center justify-center p-6 md:p-10 preview bg-surface-100 h-screen">+ <div className="w-full max-w-sm flex flex-col gap-4 justify-center items-center">+ {children}+ </div>+ </div>+ </>+ )+}diff --git a/apps/ui-library/app/example/realtime-chat/page.tsx b/apps/ui-library/app/example/realtime-chat/page.tsxnew file mode 100644index 00000000000..9be00d34458--- /dev/null+++ b/apps/ui-library/app/example/realtime-chat/page.tsx@@ -0,0 +1,9 @@+'use client'++import Demo from '@/registry/default/examples/realtime-chat-demo'++const RealtimeChatPage = () => {+ return <Demo />+}++export default RealtimeChatPagediff --git a/apps/ui-library/config/docs.ts b/apps/ui-library/config/docs.tsindex eaff6135dac..94a6ecc4a15 100644--- a/apps/ui-library/config/docs.ts+++ b/apps/ui-library/config/docs.ts@@ -95,6 +95,12 @@ export const componentPages: Record<commandItemLabel: 'Realtime Avatar Stack',href: '/docs/nextjs/realtime-avatar-stack',},+ 'realtime-chat': {+ title: 'Realtime Chat',+ supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react'],+ commandItemLabel: 'Realtime Chat',+ href: '/docs/nextjs/realtime-chat',+ },}export const COMMAND_ITEMS = [diff --git a/apps/ui-library/content/docs/nextjs/realtime-chat.mdx b/apps/ui-library/content/docs/nextjs/realtime-chat.mdxnew file mode 100644index 00000000000..cf97ba02566--- /dev/null+++ b/apps/ui-library/content/docs/nextjs/realtime-chat.mdx@@ -0,0 +1,98 @@+---+title: Realtime Chat+description: Real-time chat component for collaborative applications+---++<div className="flex flex-row -space-x-px w-full">+ <BlockPreview name="realtime-chat" isPair />+ <BlockPreview name="realtime-chat" isPair />+</div>++## Installation++<BlockItem+ name="realtime-chat-nextjs"+ description="Renders a real-time chat interface for users in a shared room."+/>++## Folder structure++<RegistryBlock itemName="realtime-chat-nextjs" />++## Introduction++The Realtime Chat component provides a complete chat interface that enables users to exchange messages in real-time within a shared room.++## Usage++### Basic usage++```tsx+import { RealtimeChat } from '@/components/realtime-chat'++export default function ChatPage() {+ return <RealtimeChat roomName="my-chat-room" username="john_doe" />+}+```++### With initial messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()++ return <RealtimeChat roomName="my-chat-room" username="john_doe" messages={messages} />+}+```++### Storing messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'+import { storeMessages } from '@/lib/store-messages'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()+ const handleMessage = (messages: ChatMessage[]) => {+ // Store messages in your database+ await storeMessages(messages)+ }++ return <RealtimeChat roomName="my-chat-room" username="john_doe" onMessage={handleMessage} />+}+```++## Features++- Real-time message synchronization+- Message persistence support with `onMessage` and `messages` props+- Customizable message appearance+- Automatic scroll-to-bottom on new messages+- Room-based isolation for scoped conversations+- Low-latency updates using Supabase Realtime++## Props++| Prop | Type | Description |+| ------------ | ----------------------------------- | ------------------------------------------------------------- |+| `roomName` | `string` | Unique identifier for the shared chat room. |+| `username` | `string` | Name of the current user; used to identify message senders. |+| `onMessage?` | `(messages: ChatMessage[]) => void` | Optional callback to handle messages, useful for persistence. |+| `messages?` | `ChatMessage[]` | Optional initial messages to display in the chat. |++### ChatMessage Type++```typescript+interface ChatMessage {+ id: string+ content: string+ user: {+ name: string+ }+ createdAt: string+}+```diff --git a/apps/ui-library/content/docs/react-router/realtime-chat.mdx b/apps/ui-library/content/docs/react-router/realtime-chat.mdxnew file mode 100644index 00000000000..cf97ba02566--- /dev/null+++ b/apps/ui-library/content/docs/react-router/realtime-chat.mdx@@ -0,0 +1,98 @@+---+title: Realtime Chat+description: Real-time chat component for collaborative applications+---++<div className="flex flex-row -space-x-px w-full">+ <BlockPreview name="realtime-chat" isPair />+ <BlockPreview name="realtime-chat" isPair />+</div>++## Installation++<BlockItem+ name="realtime-chat-nextjs"+ description="Renders a real-time chat interface for users in a shared room."+/>++## Folder structure++<RegistryBlock itemName="realtime-chat-nextjs" />++## Introduction++The Realtime Chat component provides a complete chat interface that enables users to exchange messages in real-time within a shared room.++## Usage++### Basic usage++```tsx+import { RealtimeChat } from '@/components/realtime-chat'++export default function ChatPage() {+ return <RealtimeChat roomName="my-chat-room" username="john_doe" />+}+```++### With initial messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()++ return <RealtimeChat roomName="my-chat-room" username="john_doe" messages={messages} />+}+```++### Storing messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'+import { storeMessages } from '@/lib/store-messages'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()+ const handleMessage = (messages: ChatMessage[]) => {+ // Store messages in your database+ await storeMessages(messages)+ }++ return <RealtimeChat roomName="my-chat-room" username="john_doe" onMessage={handleMessage} />+}+```++## Features++- Real-time message synchronization+- Message persistence support with `onMessage` and `messages` props+- Customizable message appearance+- Automatic scroll-to-bottom on new messages+- Room-based isolation for scoped conversations+- Low-latency updates using Supabase Realtime++## Props++| Prop | Type | Description |+| ------------ | ----------------------------------- | ------------------------------------------------------------- |+| `roomName` | `string` | Unique identifier for the shared chat room. |+| `username` | `string` | Name of the current user; used to identify message senders. |+| `onMessage?` | `(messages: ChatMessage[]) => void` | Optional callback to handle messages, useful for persistence. |+| `messages?` | `ChatMessage[]` | Optional initial messages to display in the chat. |++### ChatMessage Type++```typescript+interface ChatMessage {+ id: string+ content: string+ user: {+ name: string+ }+ createdAt: string+}+```diff --git a/apps/ui-library/content/docs/react/realtime-chat.mdx b/apps/ui-library/content/docs/react/realtime-chat.mdxnew file mode 100644index 00000000000..cf97ba02566--- /dev/null+++ b/apps/ui-library/content/docs/react/realtime-chat.mdx@@ -0,0 +1,98 @@+---+title: Realtime Chat+description: Real-time chat component for collaborative applications+---++<div className="flex flex-row -space-x-px w-full">+ <BlockPreview name="realtime-chat" isPair />+ <BlockPreview name="realtime-chat" isPair />+</div>++## Installation++<BlockItem+ name="realtime-chat-nextjs"+ description="Renders a real-time chat interface for users in a shared room."+/>++## Folder structure++<RegistryBlock itemName="realtime-chat-nextjs" />++## Introduction++The Realtime Chat component provides a complete chat interface that enables users to exchange messages in real-time within a shared room.++## Usage++### Basic usage++```tsx+import { RealtimeChat } from '@/components/realtime-chat'++export default function ChatPage() {+ return <RealtimeChat roomName="my-chat-room" username="john_doe" />+}+```++### With initial messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()++ return <RealtimeChat roomName="my-chat-room" username="john_doe" messages={messages} />+}+```++### Storing messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'+import { storeMessages } from '@/lib/store-messages'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()+ const handleMessage = (messages: ChatMessage[]) => {+ // Store messages in your database+ await storeMessages(messages)+ }++ return <RealtimeChat roomName="my-chat-room" username="john_doe" onMessage={handleMessage} />+}+```++## Features++- Real-time message synchronization+- Message persistence support with `onMessage` and `messages` props+- Customizable message appearance+- Automatic scroll-to-bottom on new messages+- Room-based isolation for scoped conversations+- Low-latency updates using Supabase Realtime++## Props++| Prop | Type | Description |+| ------------ | ----------------------------------- | ------------------------------------------------------------- |+| `roomName` | `string` | Unique identifier for the shared chat room. |+| `username` | `string` | Name of the current user; used to identify message senders. |+| `onMessage?` | `(messages: ChatMessage[]) => void` | Optional callback to handle messages, useful for persistence. |+| `messages?` | `ChatMessage[]` | Optional initial messages to display in the chat. |++### ChatMessage Type++```typescript+interface ChatMessage {+ id: string+ content: string+ user: {+ name: string+ }+ createdAt: string+}+```diff --git a/apps/ui-library/content/docs/tanstack/realtime-chat.mdx b/apps/ui-library/content/docs/tanstack/realtime-chat.mdxnew file mode 100644index 00000000000..cf97ba02566--- /dev/null+++ b/apps/ui-library/content/docs/tanstack/realtime-chat.mdx@@ -0,0 +1,98 @@+---+title: Realtime Chat+description: Real-time chat component for collaborative applications+---++<div className="flex flex-row -space-x-px w-full">+ <BlockPreview name="realtime-chat" isPair />+ <BlockPreview name="realtime-chat" isPair />+</div>++## Installation++<BlockItem+ name="realtime-chat-nextjs"+ description="Renders a real-time chat interface for users in a shared room."+/>++## Folder structure++<RegistryBlock itemName="realtime-chat-nextjs" />++## Introduction++The Realtime Chat component provides a complete chat interface that enables users to exchange messages in real-time within a shared room.++## Usage++### Basic usage++```tsx+import { RealtimeChat } from '@/components/realtime-chat'++export default function ChatPage() {+ return <RealtimeChat roomName="my-chat-room" username="john_doe" />+}+```++### With initial messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()++ return <RealtimeChat roomName="my-chat-room" username="john_doe" messages={messages} />+}+```++### Storing messages++```tsx+import { RealtimeChat } from '@/components/realtime-chat'+import { useMessagesQuery } from '@/hooks/use-messages-query'+import { storeMessages } from '@/lib/store-messages'++export default function ChatPage() {+ const { data: messages } = useMessagesQuery()+ const handleMessage = (messages: ChatMessage[]) => {+ // Store messages in your database+ await storeMessages(messages)+ }++ return <RealtimeChat roomName="my-chat-room" username="john_doe" onMessage={handleMessage} />+}+```++## Features++- Real-time message synchronization+- Message persistence support with `onMessage` and `messages` props+- Customizable message appearance+- Automatic scroll-to-bottom on new messages+- Room-based isolation for scoped conversations+- Low-latency updates using Supabase Realtime++## Props++| Prop | Type | Description |+| ------------ | ----------------------------------- | ------------------------------------------------------------- |+| `roomName` | `string` | Unique identifier for the shared chat room. |+| `username` | `string` | Name of the current user; used to identify message senders. |+| `onMessage?` | `(messages: ChatMessage[]) => void` | Optional callback to handle messages, useful for persistence. |+| `messages?` | `ChatMessage[]` | Optional initial messages to display in the chat. |++### ChatMessage Type++```typescript+interface ChatMessage {+ id: string+ content: string+ user: {+ name: string+ }+ createdAt: string+}+```diff --git a/apps/ui-library/public/r/realtime-chat-nextjs.json b/apps/ui-library/public/r/realtime-chat-nextjs.jsonnew file mode 100644index 00000000000..8955c4bfee0--- /dev/null+++ b/apps/ui-library/public/r/realtime-chat-nextjs.json@@ -0,0 +1,52 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-nextjs",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "dependencies": [+ "lucide-react",+ "@supabase/ssr@latest"+ ],+ "registryDependencies": [+ "input",+ "button"+ ],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "content": "import { cn } from '@/lib/utils'\nimport type { ChatMessage } from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\n\ninterface ChatMessageItemProps {\n message: ChatMessage\n isOwnMessage: boolean\n showHeader: boolean\n}\n\nexport const ChatMessageItem = ({ message, isOwnMessage, showHeader }: ChatMessageItemProps) => {\n return (\n <div className={`flex mt-2 ${isOwnMessage ? 'justify-end' : 'justify-start'}`}>\n <div\n className={cn('max-w-[70%] w-fit flex flex-col gap-1', {\n 'items-end': isOwnMessage,\n })}\n >\n {showHeader && (\n <div className=\"flex items-center gap-2 text-xs\">\n <span className={'font-medium'}>{message.user.name}</span>\n <span className=\"text-foreground/50 text-xs\">\n {new Date(message.createdAt).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n })}\n </span>\n </div>\n )}\n <div\n className={cn(\n 'py-1 px-2 rounded-xl text-sm w-fit',\n isOwnMessage ? 'bg-accent-foreground text-background' : 'bg-secondary text-foreground'\n )}\n >\n {message.content}\n </div>\n </div>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { ChatMessageItem } from '@/registry/default/blocks/realtime-chat/components/chat-message'\nimport { useChatScroll } from '@/registry/default/blocks/realtime-chat/hooks/use-chat-scroll'\nimport {\n ChatMessage,\n useRealtimeChat,\n} from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Send } from 'lucide-react'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface RealtimeChatProps {\n roomName: string\n username: string\n onMessage?: (messages: ChatMessage[]) => void\n messages?: ChatMessage[]\n}\n\n/**\n * Realtime chat component\n * @param roomName - The name of the room to join. Each room is a unique chat.\n * @param username - The username of the user\n * @param onMessage - The callback function to handle the messages. Useful if you want to store the messages in a database.\n * @param messages - The messages to display in the chat. Useful if you want to display messages from a database.\n * @returns The chat component\n */\nexport const RealtimeChat = ({\n roomName,\n username,\n onMessage,\n messages: initialMessages = [],\n}: RealtimeChatProps) => {\n const { containerRef, scrollToBottom } = useChatScroll()\n const [allMessages, setAllMessages] = useState<ChatMessage[]>(initialMessages)\n\n const {\n messages: realtimeMessages,\n sendMessage,\n isConnected,\n } = useRealtimeChat({\n roomName,\n username,\n })\n const [newMessage, setNewMessage] = useState('')\n\n // Merge realtime messages with initial messages\n useEffect(() => {\n const mergedMessages = [...initialMessages, ...realtimeMessages]\n // Remove duplicates based on message id\n const uniqueMessages = mergedMessages.filter(\n (message, index, self) => index === self.findIndex((m) => m.id === message.id)\n )\n // Sort by creation date\n const sortedMessages = uniqueMessages.sort(\n (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()\n )\n setAllMessages(sortedMessages)\n }, [initialMessages, realtimeMessages])\n\n useEffect(() => {\n if (onMessage) {\n onMessage(allMessages)\n }\n }, [allMessages, onMessage])\n\n useEffect(() => {\n // Scroll to bottom whenever messages change\n scrollToBottom()\n }, [allMessages, scrollToBottom])\n\n const handleSendMessage = useCallback(\n (e: React.FormEvent) => {\n e.preventDefault()\n if (!newMessage.trim() || !isConnected) return\n\n sendMessage(newMessage)\n setNewMessage('')\n },\n [newMessage, isConnected, sendMessage]\n )\n\n return (\n <div className=\"flex flex-col h-full w-full bg-background text-foreground antialiased\">\n {/* Messages */}\n <div ref={containerRef} className=\"flex-1 overflow-y-auto p-4 space-y-4\">\n {allMessages.length === 0 ? (\n <div className=\"text-center text-sm text-muted-foreground\">\n No messages yet. Start the conversation!\n </div>\n ) : null}\n <div className=\"space-y-1\">\n {allMessages.map((message, index) => {\n const prevMessage = index > 0 ? allMessages[index - 1] : null\n const showHeader = !prevMessage || prevMessage.user.name !== message.user.name\n\n return (\n <div\n key={message.id}\n className=\"animate-in fade-in slide-in-from-bottom-4 duration-300\"\n >\n <ChatMessageItem\n message={message}\n isOwnMessage={message.user.name === username}\n showHeader={showHeader}\n />\n </div>\n )\n })}\n </div>\n </div>\n\n <form onSubmit={handleSendMessage} className=\"flex w-full gap-2 border-t border-border p-4\">\n <Input\n className={cn(\n 'rounded-full bg-background text-sm transition-all duration-300',\n isConnected && newMessage.trim() ? 'w-[calc(100%-36px)]' : 'w-full'\n )}\n type=\"text\"\n value={newMessage}\n onChange={(e) => setNewMessage(e.target.value)}\n placeholder=\"Type a message...\"\n disabled={!isConnected}\n />\n {isConnected && newMessage.trim() && (\n <Button\n className=\"aspect-square rounded-full animate-in fade-in slide-in-from-right-4 duration-300\"\n type=\"submit\"\n disabled={!isConnected}\n >\n <Send className=\"size-4\" />\n </Button>\n )}\n </form>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "content": "'use client'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "content": "import { useCallback, useRef } from 'react'\n\nexport function useChatScroll() {\n const containerRef = useRef<HTMLDivElement>(null)\n\n const scrollToBottom = useCallback(() => {\n if (!containerRef.current) return\n\n const container = containerRef.current\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'smooth',\n })\n }, [])\n\n return { containerRef, scrollToBottom }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/nextjs/lib/supabase/client.ts",+ "content": "import { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!\n )\n}\n",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/nextjs/lib/supabase/middleware.ts",+ "content": "import { createServerClient } from '@supabase/ssr'\nimport { NextResponse, type NextRequest } from 'next/server'\n\nexport async function updateSession(request: NextRequest) {\n let supabaseResponse = NextResponse.next({\n request,\n })\n\n const supabase = createServerClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,\n {\n cookies: {\n getAll() {\n return request.cookies.getAll()\n },\n setAll(cookiesToSet) {\n cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))\n supabaseResponse = NextResponse.next({\n request,\n })\n cookiesToSet.forEach(({ name, value, options }) =>\n supabaseResponse.cookies.set(name, value, options)\n )\n },\n },\n }\n )\n\n // Do not run code between createServerClient and\n // supabase.auth.getUser(). A simple mistake could make it very hard to debug\n // issues with users being randomly logged out.\n\n // IMPORTANT: DO NOT REMOVE auth.getUser()\n\n const {\n data: { user },\n } = await supabase.auth.getUser()\n\n if (\n !user &&\n !request.nextUrl.pathname.startsWith('/login') &&\n !request.nextUrl.pathname.startsWith('/auth')\n ) {\n // no user, potentially respond by redirecting the user to the login page\n const url = request.nextUrl.clone()\n url.pathname = '/login'\n return NextResponse.redirect(url)\n }\n\n // IMPORTANT: You *must* return the supabaseResponse object as it is.\n // If you're creating a new response object with NextResponse.next() make sure to:\n // 1. Pass the request in it, like so:\n // const myNewResponse = NextResponse.next({ request })\n // 2. Copy over the cookies, like so:\n // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())\n // 3. Change the myNewResponse object to fit your needs, but avoid changing\n // the cookies!\n // 4. Finally:\n // return myNewResponse\n // If this is not done, you may be causing the browser and server to go out\n // of sync and terminate the user's session prematurely!\n\n return supabaseResponse\n}\n",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/nextjs/lib/supabase/server.ts",+ "content": "import { createServerClient } from '@supabase/ssr'\nimport { cookies } from 'next/headers'\n\nexport async function createClient() {\n const cookieStore = await cookies()\n\n return createServerClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,\n {\n cookies: {\n getAll() {\n return cookieStore.getAll()\n },\n setAll(cookiesToSet) {\n try {\n cookiesToSet.forEach(({ name, value, options }) =>\n cookieStore.set(name, value, options)\n )\n } catch {\n // The `setAll` method was called from a Server Component.\n // This can be ignored if you have middleware refreshing\n // user sessions.\n }\n },\n },\n }\n )\n}\n",+ "type": "registry:lib"+ }+ ]+}\ No newline at end of filediff --git a/apps/ui-library/public/r/realtime-chat-react-router.json b/apps/ui-library/public/r/realtime-chat-react-router.jsonnew file mode 100644index 00000000000..e78474c33d3--- /dev/null+++ b/apps/ui-library/public/r/realtime-chat-react-router.json@@ -0,0 +1,48 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-react-router",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "dependencies": [+ "lucide-react",+ "@supabase/ssr@latest",+ "@supabase/supabase-js@latest"+ ],+ "registryDependencies": [+ "input",+ "button"+ ],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "content": "import { cn } from '@/lib/utils'\nimport type { ChatMessage } from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\n\ninterface ChatMessageItemProps {\n message: ChatMessage\n isOwnMessage: boolean\n showHeader: boolean\n}\n\nexport const ChatMessageItem = ({ message, isOwnMessage, showHeader }: ChatMessageItemProps) => {\n return (\n <div className={`flex mt-2 ${isOwnMessage ? 'justify-end' : 'justify-start'}`}>\n <div\n className={cn('max-w-[70%] w-fit flex flex-col gap-1', {\n 'items-end': isOwnMessage,\n })}\n >\n {showHeader && (\n <div className=\"flex items-center gap-2 text-xs\">\n <span className={'font-medium'}>{message.user.name}</span>\n <span className=\"text-foreground/50 text-xs\">\n {new Date(message.createdAt).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n })}\n </span>\n </div>\n )}\n <div\n className={cn(\n 'py-1 px-2 rounded-xl text-sm w-fit',\n isOwnMessage ? 'bg-accent-foreground text-background' : 'bg-secondary text-foreground'\n )}\n >\n {message.content}\n </div>\n </div>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { ChatMessageItem } from '@/registry/default/blocks/realtime-chat/components/chat-message'\nimport { useChatScroll } from '@/registry/default/blocks/realtime-chat/hooks/use-chat-scroll'\nimport {\n ChatMessage,\n useRealtimeChat,\n} from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Send } from 'lucide-react'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface RealtimeChatProps {\n roomName: string\n username: string\n onMessage?: (messages: ChatMessage[]) => void\n messages?: ChatMessage[]\n}\n\n/**\n * Realtime chat component\n * @param roomName - The name of the room to join. Each room is a unique chat.\n * @param username - The username of the user\n * @param onMessage - The callback function to handle the messages. Useful if you want to store the messages in a database.\n * @param messages - The messages to display in the chat. Useful if you want to display messages from a database.\n * @returns The chat component\n */\nexport const RealtimeChat = ({\n roomName,\n username,\n onMessage,\n messages: initialMessages = [],\n}: RealtimeChatProps) => {\n const { containerRef, scrollToBottom } = useChatScroll()\n const [allMessages, setAllMessages] = useState<ChatMessage[]>(initialMessages)\n\n const {\n messages: realtimeMessages,\n sendMessage,\n isConnected,\n } = useRealtimeChat({\n roomName,\n username,\n })\n const [newMessage, setNewMessage] = useState('')\n\n // Merge realtime messages with initial messages\n useEffect(() => {\n const mergedMessages = [...initialMessages, ...realtimeMessages]\n // Remove duplicates based on message id\n const uniqueMessages = mergedMessages.filter(\n (message, index, self) => index === self.findIndex((m) => m.id === message.id)\n )\n // Sort by creation date\n const sortedMessages = uniqueMessages.sort(\n (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()\n )\n setAllMessages(sortedMessages)\n }, [initialMessages, realtimeMessages])\n\n useEffect(() => {\n if (onMessage) {\n onMessage(allMessages)\n }\n }, [allMessages, onMessage])\n\n useEffect(() => {\n // Scroll to bottom whenever messages change\n scrollToBottom()\n }, [allMessages, scrollToBottom])\n\n const handleSendMessage = useCallback(\n (e: React.FormEvent) => {\n e.preventDefault()\n if (!newMessage.trim() || !isConnected) return\n\n sendMessage(newMessage)\n setNewMessage('')\n },\n [newMessage, isConnected, sendMessage]\n )\n\n return (\n <div className=\"flex flex-col h-full w-full bg-background text-foreground antialiased\">\n {/* Messages */}\n <div ref={containerRef} className=\"flex-1 overflow-y-auto p-4 space-y-4\">\n {allMessages.length === 0 ? (\n <div className=\"text-center text-sm text-muted-foreground\">\n No messages yet. Start the conversation!\n </div>\n ) : null}\n <div className=\"space-y-1\">\n {allMessages.map((message, index) => {\n const prevMessage = index > 0 ? allMessages[index - 1] : null\n const showHeader = !prevMessage || prevMessage.user.name !== message.user.name\n\n return (\n <div\n key={message.id}\n className=\"animate-in fade-in slide-in-from-bottom-4 duration-300\"\n >\n <ChatMessageItem\n message={message}\n isOwnMessage={message.user.name === username}\n showHeader={showHeader}\n />\n </div>\n )\n })}\n </div>\n </div>\n\n <form onSubmit={handleSendMessage} className=\"flex w-full gap-2 border-t border-border p-4\">\n <Input\n className={cn(\n 'rounded-full bg-background text-sm transition-all duration-300',\n isConnected && newMessage.trim() ? 'w-[calc(100%-36px)]' : 'w-full'\n )}\n type=\"text\"\n value={newMessage}\n onChange={(e) => setNewMessage(e.target.value)}\n placeholder=\"Type a message...\"\n disabled={!isConnected}\n />\n {isConnected && newMessage.trim() && (\n <Button\n className=\"aspect-square rounded-full animate-in fade-in slide-in-from-right-4 duration-300\"\n type=\"submit\"\n disabled={!isConnected}\n >\n <Send className=\"size-4\" />\n </Button>\n )}\n </form>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "content": "'use client'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "content": "import { useCallback, useRef } from 'react'\n\nexport function useChatScroll() {\n const containerRef = useRef<HTMLDivElement>(null)\n\n const scrollToBottom = useCallback(() => {\n if (!containerRef.current) return\n\n const container = containerRef.current\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'smooth',\n })\n }, [])\n\n return { containerRef, scrollToBottom }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/react-router/lib/supabase/client.ts",+ "content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_ANON_KEY!\n )\n}\n",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/react-router/lib/supabase/server.ts",+ "content": "import { createServerClient, parseCookieHeader, serializeCookieHeader } from '@supabase/ssr'\n\nexport function createClient(request: Request) {\n const headers = new Headers()\n\n const supabase = createServerClient(\n process.env.VITE_SUPABASE_URL!,\n process.env.VITE_SUPABASE_ANON_KEY!,\n {\n cookies: {\n getAll() {\n return parseCookieHeader(request.headers.get('Cookie') ?? '') as {\n name: string\n value: string\n }[]\n },\n setAll(cookiesToSet) {\n cookiesToSet.forEach(({ name, value, options }) =>\n headers.append('Set-Cookie', serializeCookieHeader(name, value, options))\n )\n },\n },\n }\n )\n\n return { supabase, headers }\n}\n",+ "type": "registry:lib"+ }+ ]+}\ No newline at end of filediff --git a/apps/ui-library/public/r/realtime-chat-react.json b/apps/ui-library/public/r/realtime-chat-react.jsonnew file mode 100644index 00000000000..4498c3dfb65--- /dev/null+++ b/apps/ui-library/public/r/realtime-chat-react.json@@ -0,0 +1,42 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-react",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "dependencies": [+ "lucide-react",+ "@supabase/supabase-js@latest"+ ],+ "registryDependencies": [+ "input",+ "button"+ ],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "content": "import { cn } from '@/lib/utils'\nimport type { ChatMessage } from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\n\ninterface ChatMessageItemProps {\n message: ChatMessage\n isOwnMessage: boolean\n showHeader: boolean\n}\n\nexport const ChatMessageItem = ({ message, isOwnMessage, showHeader }: ChatMessageItemProps) => {\n return (\n <div className={`flex mt-2 ${isOwnMessage ? 'justify-end' : 'justify-start'}`}>\n <div\n className={cn('max-w-[70%] w-fit flex flex-col gap-1', {\n 'items-end': isOwnMessage,\n })}\n >\n {showHeader && (\n <div className=\"flex items-center gap-2 text-xs\">\n <span className={'font-medium'}>{message.user.name}</span>\n <span className=\"text-foreground/50 text-xs\">\n {new Date(message.createdAt).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n })}\n </span>\n </div>\n )}\n <div\n className={cn(\n 'py-1 px-2 rounded-xl text-sm w-fit',\n isOwnMessage ? 'bg-accent-foreground text-background' : 'bg-secondary text-foreground'\n )}\n >\n {message.content}\n </div>\n </div>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { ChatMessageItem } from '@/registry/default/blocks/realtime-chat/components/chat-message'\nimport { useChatScroll } from '@/registry/default/blocks/realtime-chat/hooks/use-chat-scroll'\nimport {\n ChatMessage,\n useRealtimeChat,\n} from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Send } from 'lucide-react'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface RealtimeChatProps {\n roomName: string\n username: string\n onMessage?: (messages: ChatMessage[]) => void\n messages?: ChatMessage[]\n}\n\n/**\n * Realtime chat component\n * @param roomName - The name of the room to join. Each room is a unique chat.\n * @param username - The username of the user\n * @param onMessage - The callback function to handle the messages. Useful if you want to store the messages in a database.\n * @param messages - The messages to display in the chat. Useful if you want to display messages from a database.\n * @returns The chat component\n */\nexport const RealtimeChat = ({\n roomName,\n username,\n onMessage,\n messages: initialMessages = [],\n}: RealtimeChatProps) => {\n const { containerRef, scrollToBottom } = useChatScroll()\n const [allMessages, setAllMessages] = useState<ChatMessage[]>(initialMessages)\n\n const {\n messages: realtimeMessages,\n sendMessage,\n isConnected,\n } = useRealtimeChat({\n roomName,\n username,\n })\n const [newMessage, setNewMessage] = useState('')\n\n // Merge realtime messages with initial messages\n useEffect(() => {\n const mergedMessages = [...initialMessages, ...realtimeMessages]\n // Remove duplicates based on message id\n const uniqueMessages = mergedMessages.filter(\n (message, index, self) => index === self.findIndex((m) => m.id === message.id)\n )\n // Sort by creation date\n const sortedMessages = uniqueMessages.sort(\n (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()\n )\n setAllMessages(sortedMessages)\n }, [initialMessages, realtimeMessages])\n\n useEffect(() => {\n if (onMessage) {\n onMessage(allMessages)\n }\n }, [allMessages, onMessage])\n\n useEffect(() => {\n // Scroll to bottom whenever messages change\n scrollToBottom()\n }, [allMessages, scrollToBottom])\n\n const handleSendMessage = useCallback(\n (e: React.FormEvent) => {\n e.preventDefault()\n if (!newMessage.trim() || !isConnected) return\n\n sendMessage(newMessage)\n setNewMessage('')\n },\n [newMessage, isConnected, sendMessage]\n )\n\n return (\n <div className=\"flex flex-col h-full w-full bg-background text-foreground antialiased\">\n {/* Messages */}\n <div ref={containerRef} className=\"flex-1 overflow-y-auto p-4 space-y-4\">\n {allMessages.length === 0 ? (\n <div className=\"text-center text-sm text-muted-foreground\">\n No messages yet. Start the conversation!\n </div>\n ) : null}\n <div className=\"space-y-1\">\n {allMessages.map((message, index) => {\n const prevMessage = index > 0 ? allMessages[index - 1] : null\n const showHeader = !prevMessage || prevMessage.user.name !== message.user.name\n\n return (\n <div\n key={message.id}\n className=\"animate-in fade-in slide-in-from-bottom-4 duration-300\"\n >\n <ChatMessageItem\n message={message}\n isOwnMessage={message.user.name === username}\n showHeader={showHeader}\n />\n </div>\n )\n })}\n </div>\n </div>\n\n <form onSubmit={handleSendMessage} className=\"flex w-full gap-2 border-t border-border p-4\">\n <Input\n className={cn(\n 'rounded-full bg-background text-sm transition-all duration-300',\n isConnected && newMessage.trim() ? 'w-[calc(100%-36px)]' : 'w-full'\n )}\n type=\"text\"\n value={newMessage}\n onChange={(e) => setNewMessage(e.target.value)}\n placeholder=\"Type a message...\"\n disabled={!isConnected}\n />\n {isConnected && newMessage.trim() && (\n <Button\n className=\"aspect-square rounded-full animate-in fade-in slide-in-from-right-4 duration-300\"\n type=\"submit\"\n disabled={!isConnected}\n >\n <Send className=\"size-4\" />\n </Button>\n )}\n </form>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "content": "'use client'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "content": "import { useCallback, useRef } from 'react'\n\nexport function useChatScroll() {\n const containerRef = useRef<HTMLDivElement>(null)\n\n const scrollToBottom = useCallback(() => {\n if (!containerRef.current) return\n\n const container = containerRef.current\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'smooth',\n })\n }, [])\n\n return { containerRef, scrollToBottom }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/react/lib/supabase/client.ts",+ "content": "import { createClient as createSupabaseClient } from '@supabase/supabase-js'\n\nexport function createClient() {\n return createSupabaseClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_ANON_KEY!\n )\n}\n",+ "type": "registry:lib"+ }+ ]+}\ No newline at end of filediff --git a/apps/ui-library/public/r/realtime-chat-tanstack.json b/apps/ui-library/public/r/realtime-chat-tanstack.jsonnew file mode 100644index 00000000000..60434de3acd--- /dev/null+++ b/apps/ui-library/public/r/realtime-chat-tanstack.json@@ -0,0 +1,48 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-tanstack",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "dependencies": [+ "lucide-react",+ "@supabase/ssr@latest",+ "@supabase/supabase-js@latest"+ ],+ "registryDependencies": [+ "input",+ "button"+ ],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "content": "import { cn } from '@/lib/utils'\nimport type { ChatMessage } from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\n\ninterface ChatMessageItemProps {\n message: ChatMessage\n isOwnMessage: boolean\n showHeader: boolean\n}\n\nexport const ChatMessageItem = ({ message, isOwnMessage, showHeader }: ChatMessageItemProps) => {\n return (\n <div className={`flex mt-2 ${isOwnMessage ? 'justify-end' : 'justify-start'}`}>\n <div\n className={cn('max-w-[70%] w-fit flex flex-col gap-1', {\n 'items-end': isOwnMessage,\n })}\n >\n {showHeader && (\n <div className=\"flex items-center gap-2 text-xs\">\n <span className={'font-medium'}>{message.user.name}</span>\n <span className=\"text-foreground/50 text-xs\">\n {new Date(message.createdAt).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n })}\n </span>\n </div>\n )}\n <div\n className={cn(\n 'py-1 px-2 rounded-xl text-sm w-fit',\n isOwnMessage ? 'bg-accent-foreground text-background' : 'bg-secondary text-foreground'\n )}\n >\n {message.content}\n </div>\n </div>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "content": "'use client'\n\nimport { cn } from '@/lib/utils'\nimport { ChatMessageItem } from '@/registry/default/blocks/realtime-chat/components/chat-message'\nimport { useChatScroll } from '@/registry/default/blocks/realtime-chat/hooks/use-chat-scroll'\nimport {\n ChatMessage,\n useRealtimeChat,\n} from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'\nimport { Button } from '@/registry/default/components/ui/button'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Send } from 'lucide-react'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface RealtimeChatProps {\n roomName: string\n username: string\n onMessage?: (messages: ChatMessage[]) => void\n messages?: ChatMessage[]\n}\n\n/**\n * Realtime chat component\n * @param roomName - The name of the room to join. Each room is a unique chat.\n * @param username - The username of the user\n * @param onMessage - The callback function to handle the messages. Useful if you want to store the messages in a database.\n * @param messages - The messages to display in the chat. Useful if you want to display messages from a database.\n * @returns The chat component\n */\nexport const RealtimeChat = ({\n roomName,\n username,\n onMessage,\n messages: initialMessages = [],\n}: RealtimeChatProps) => {\n const { containerRef, scrollToBottom } = useChatScroll()\n const [allMessages, setAllMessages] = useState<ChatMessage[]>(initialMessages)\n\n const {\n messages: realtimeMessages,\n sendMessage,\n isConnected,\n } = useRealtimeChat({\n roomName,\n username,\n })\n const [newMessage, setNewMessage] = useState('')\n\n // Merge realtime messages with initial messages\n useEffect(() => {\n const mergedMessages = [...initialMessages, ...realtimeMessages]\n // Remove duplicates based on message id\n const uniqueMessages = mergedMessages.filter(\n (message, index, self) => index === self.findIndex((m) => m.id === message.id)\n )\n // Sort by creation date\n const sortedMessages = uniqueMessages.sort(\n (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()\n )\n setAllMessages(sortedMessages)\n }, [initialMessages, realtimeMessages])\n\n useEffect(() => {\n if (onMessage) {\n onMessage(allMessages)\n }\n }, [allMessages, onMessage])\n\n useEffect(() => {\n // Scroll to bottom whenever messages change\n scrollToBottom()\n }, [allMessages, scrollToBottom])\n\n const handleSendMessage = useCallback(\n (e: React.FormEvent) => {\n e.preventDefault()\n if (!newMessage.trim() || !isConnected) return\n\n sendMessage(newMessage)\n setNewMessage('')\n },\n [newMessage, isConnected, sendMessage]\n )\n\n return (\n <div className=\"flex flex-col h-full w-full bg-background text-foreground antialiased\">\n {/* Messages */}\n <div ref={containerRef} className=\"flex-1 overflow-y-auto p-4 space-y-4\">\n {allMessages.length === 0 ? (\n <div className=\"text-center text-sm text-muted-foreground\">\n No messages yet. Start the conversation!\n </div>\n ) : null}\n <div className=\"space-y-1\">\n {allMessages.map((message, index) => {\n const prevMessage = index > 0 ? allMessages[index - 1] : null\n const showHeader = !prevMessage || prevMessage.user.name !== message.user.name\n\n return (\n <div\n key={message.id}\n className=\"animate-in fade-in slide-in-from-bottom-4 duration-300\"\n >\n <ChatMessageItem\n message={message}\n isOwnMessage={message.user.name === username}\n showHeader={showHeader}\n />\n </div>\n )\n })}\n </div>\n </div>\n\n <form onSubmit={handleSendMessage} className=\"flex w-full gap-2 border-t border-border p-4\">\n <Input\n className={cn(\n 'rounded-full bg-background text-sm transition-all duration-300',\n isConnected && newMessage.trim() ? 'w-[calc(100%-36px)]' : 'w-full'\n )}\n type=\"text\"\n value={newMessage}\n onChange={(e) => setNewMessage(e.target.value)}\n placeholder=\"Type a message...\"\n disabled={!isConnected}\n />\n {isConnected && newMessage.trim() && (\n <Button\n className=\"aspect-square rounded-full animate-in fade-in slide-in-from-right-4 duration-300\"\n type=\"submit\"\n disabled={!isConnected}\n >\n <Send className=\"size-4\" />\n </Button>\n )}\n </form>\n </div>\n )\n}\n",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "content": "'use client'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { useCallback, useEffect, useState } from 'react'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "content": "import { useCallback, useRef } from 'react'\n\nexport function useChatScroll() {\n const containerRef = useRef<HTMLDivElement>(null)\n\n const scrollToBottom = useCallback(() => {\n if (!containerRef.current) return\n\n const container = containerRef.current\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'smooth',\n })\n }, [])\n\n return { containerRef, scrollToBottom }\n}\n",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/tanstack/lib/supabase/client.ts",+ "content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_ANON_KEY!\n )\n}\n",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/tanstack/lib/supabase/server.ts",+ "content": "import { createServerClient } from '@supabase/ssr'\nimport { parseCookies, setCookie } from '@tanstack/react-start/server'\n\nexport function createClient() {\n return createServerClient(process.env.VITE_SUPABASE_URL!, process.env.VITE_SUPABASE_ANON_KEY!, {\n cookies: {\n getAll() {\n return Object.entries(parseCookies()).map(\n ([name, value]) =>\n ({\n name,\n value,\n }) as { name: string; value: string }\n )\n },\n setAll(cookies) {\n cookies.forEach((cookie) => {\n setCookie(cookie.name, cookie.value)\n })\n },\n },\n })\n}\n",+ "type": "registry:lib"+ }+ ]+}\ No newline at end of filediff --git a/apps/ui-library/registry.json b/apps/ui-library/registry.jsonindex d4cfe3690f7..921e075f6fc 100644--- a/apps/ui-library/registry.json+++ b/apps/ui-library/registry.json@@ -793,6 +793,146 @@}]},+ {+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-nextjs",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "registryDependencies": ["input", "button"],+ "dependencies": ["lucide-react", "@supabase/ssr@latest"],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/nextjs/lib/supabase/client.ts",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/nextjs/lib/supabase/middleware.ts",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/nextjs/lib/supabase/server.ts",+ "type": "registry:lib"+ }+ ]+ },+ {+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-react",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "registryDependencies": ["input", "button"],+ "dependencies": ["lucide-react", "@supabase/supabase-js@latest"],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/react/lib/supabase/client.ts",+ "type": "registry:lib"+ }+ ]+ },+ {+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-react-router",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "registryDependencies": ["input", "button"],+ "dependencies": ["lucide-react", "@supabase/ssr@latest", "@supabase/supabase-js@latest"],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/react-router/lib/supabase/client.ts",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/react-router/lib/supabase/server.ts",+ "type": "registry:lib"+ }+ ]+ },+ {+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat-tanstack",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "registryDependencies": ["input", "button"],+ "dependencies": ["lucide-react", "@supabase/ssr@latest", "@supabase/supabase-js@latest"],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/clients/tanstack/lib/supabase/client.ts",+ "type": "registry:lib"+ },+ {+ "path": "registry/default/clients/tanstack/lib/supabase/server.ts",+ "type": "registry:lib"+ }+ ]+ },{"$schema": "https://ui.shadcn.com/schema/registry-item.json","name": "supabase-client-nextjs",diff --git a/apps/ui-library/registry/blocks.ts b/apps/ui-library/registry/blocks.tsindex 2b010e1f3d7..7b23c527dfe 100644--- a/apps/ui-library/registry/blocks.ts+++ b/apps/ui-library/registry/blocks.ts@@ -8,6 +8,7 @@ import passwordBasedAuthReact from './default/blocks/password-based-auth-react/rimport passwordBasedAuthTanstack from './default/blocks/password-based-auth-tanstack/registry-item.json' assert { type: 'json' }import realtimeAvatarStack from './default/blocks/realtime-avatar-stack/registry-item.json' assert { type: 'json' }+import realtimeChat from './default/blocks/realtime-chat/registry-item.json' assert { type: 'json' }import realtimeCursor from './default/blocks/realtime-cursor/registry-item.json' assert { type: 'json' }import { registryItemAppend } from './utils'@@ -37,4 +38,5 @@ export const blocks = [...combine(realtimeCursor as RegistryItem),...combine(currentUserAvatar as RegistryItem),...combine(realtimeAvatarStack as RegistryItem),+ ...combine(realtimeChat as RegistryItem),] as Registry['items']diff --git a/apps/ui-library/registry/default/blocks/realtime-chat/components/chat-message.tsx b/apps/ui-library/registry/default/blocks/realtime-chat/components/chat-message.tsxnew file mode 100644index 00000000000..4a52e4e75db--- /dev/null+++ b/apps/ui-library/registry/default/blocks/realtime-chat/components/chat-message.tsx@@ -0,0 +1,40 @@+import { cn } from '@/lib/utils'+import type { ChatMessage } from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'++interface ChatMessageItemProps {+ message: ChatMessage+ isOwnMessage: boolean+ showHeader: boolean+}++export const ChatMessageItem = ({ message, isOwnMessage, showHeader }: ChatMessageItemProps) => {+ return (+ <div className={`flex mt-2 ${isOwnMessage ? 'justify-end' : 'justify-start'}`}>+ <div+ className={cn('max-w-[70%] w-fit flex flex-col gap-1', {+ 'items-end': isOwnMessage,+ })}+ >+ {showHeader && (+ <div className="flex items-center gap-2 text-xs">+ <span className={'font-medium'}>{message.user.name}</span>+ <span className="text-foreground/50 text-xs">+ {new Date(message.createdAt).toLocaleTimeString([], {+ hour: '2-digit',+ minute: '2-digit',+ })}+ </span>+ </div>+ )}+ <div+ className={cn(+ 'py-1 px-2 rounded-xl text-sm w-fit',+ isOwnMessage ? 'bg-accent-foreground text-background' : 'bg-secondary text-foreground'+ )}+ >+ {message.content}+ </div>+ </div>+ </div>+ )+}diff --git a/apps/ui-library/registry/default/blocks/realtime-chat/components/realtime-chat.tsx b/apps/ui-library/registry/default/blocks/realtime-chat/components/realtime-chat.tsxnew file mode 100644index 00000000000..a71bbaa7fd6--- /dev/null+++ b/apps/ui-library/registry/default/blocks/realtime-chat/components/realtime-chat.tsx@@ -0,0 +1,137 @@+'use client'++import { cn } from '@/lib/utils'+import { ChatMessageItem } from '@/registry/default/blocks/realtime-chat/components/chat-message'+import { useChatScroll } from '@/registry/default/blocks/realtime-chat/hooks/use-chat-scroll'+import {+ ChatMessage,+ useRealtimeChat,+} from '@/registry/default/blocks/realtime-chat/hooks/use-realtime-chat'+import { Button } from '@/registry/default/components/ui/button'+import { Input } from '@/registry/default/components/ui/input'+import { Send } from 'lucide-react'+import { useCallback, useEffect, useMemo, useState } from 'react'++interface RealtimeChatProps {+ roomName: string+ username: string+ onMessage?: (messages: ChatMessage[]) => void+ messages?: ChatMessage[]+}++/**+ * Realtime chat component+ * @param roomName - The name of the room to join. Each room is a unique chat.+ * @param username - The username of the user+ * @param onMessage - The callback function to handle the messages. Useful if you want to store the messages in a database.+ * @param messages - The messages to display in the chat. Useful if you want to display messages from a database.+ * @returns The chat component+ */+export const RealtimeChat = ({+ roomName,+ username,+ onMessage,+ messages: initialMessages = [],+}: RealtimeChatProps) => {+ const { containerRef, scrollToBottom } = useChatScroll()++ const {+ messages: realtimeMessages,+ sendMessage,+ isConnected,+ } = useRealtimeChat({+ roomName,+ username,+ })+ const [newMessage, setNewMessage] = useState('')++ // Merge realtime messages with initial messages+ const allMessages = useMemo(() => {+ const mergedMessages = [...initialMessages, ...realtimeMessages]+ // Remove duplicates based on message id+ const uniqueMessages = mergedMessages.filter(+ (message, index, self) => index === self.findIndex((m) => m.id === message.id)+ )+ // Sort by creation date+ const sortedMessages = uniqueMessages.sort((a, b) => a.createdAt.localeCompare(b.createdAt))++ return sortedMessages+ }, [initialMessages, realtimeMessages])++ useEffect(() => {+ if (onMessage) {+ onMessage(allMessages)+ }+ }, [allMessages, onMessage])++ useEffect(() => {+ // Scroll to bottom whenever messages change+ scrollToBottom()+ }, [allMessages, scrollToBottom])++ const handleSendMessage = useCallback(+ (e: React.FormEvent) => {+ e.preventDefault()+ if (!newMessage.trim() || !isConnected) return++ sendMessage(newMessage)+ setNewMessage('')+ },+ [newMessage, isConnected, sendMessage]+ )++ return (+ <div className="flex flex-col h-full w-full bg-background text-foreground antialiased">+ {/* Messages */}+ <div ref={containerRef} className="flex-1 overflow-y-auto p-4 space-y-4">+ {allMessages.length === 0 ? (+ <div className="text-center text-sm text-muted-foreground">+ No messages yet. Start the conversation!+ </div>+ ) : null}+ <div className="space-y-1">+ {allMessages.map((message, index) => {+ const prevMessage = index > 0 ? allMessages[index - 1] : null+ const showHeader = !prevMessage || prevMessage.user.name !== message.user.name++ return (+ <div+ key={message.id}+ className="animate-in fade-in slide-in-from-bottom-4 duration-300"+ >+ <ChatMessageItem+ message={message}+ isOwnMessage={message.user.name === username}+ showHeader={showHeader}+ />+ </div>+ )+ })}+ </div>+ </div>++ <form onSubmit={handleSendMessage} className="flex w-full gap-2 border-t border-border p-4">+ <Input+ className={cn(+ 'rounded-full bg-background text-sm transition-all duration-300',+ isConnected && newMessage.trim() ? 'w-[calc(100%-36px)]' : 'w-full'+ )}+ type="text"+ value={newMessage}+ onChange={(e) => setNewMessage(e.target.value)}+ placeholder="Type a message..."+ disabled={!isConnected}+ />+ {isConnected && newMessage.trim() && (+ <Button+ className="aspect-square rounded-full animate-in fade-in slide-in-from-right-4 duration-300"+ type="submit"+ disabled={!isConnected}+ >+ <Send className="size-4" />+ </Button>+ )}+ </form>+ </div>+ )+}diff --git a/apps/ui-library/registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx b/apps/ui-library/registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsxnew file mode 100644index 00000000000..d5013e4e012--- /dev/null+++ b/apps/ui-library/registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx@@ -0,0 +1,17 @@+import { useCallback, useRef } from 'react'++export function useChatScroll() {+ const containerRef = useRef<HTMLDivElement>(null)++ const scrollToBottom = useCallback(() => {+ if (!containerRef.current) return++ const container = containerRef.current+ container.scrollTo({+ top: container.scrollHeight,+ behavior: 'smooth',+ })+ }, [])++ return { containerRef, scrollToBottom }+}diff --git a/apps/ui-library/registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx b/apps/ui-library/registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsxnew file mode 100644index 00000000000..87cced94fda--- /dev/null+++ b/apps/ui-library/registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx@@ -0,0 +1,74 @@+'use client'++import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'+import { useCallback, useEffect, useState } from 'react'++interface UseRealtimeChatProps {+ roomName: string+ username: string+}++export interface ChatMessage {+ id: string+ content: string+ user: {+ name: string+ }+ createdAt: string+}++const EVENT_MESSAGE_TYPE = 'message'++export function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {+ const supabase = createClient()+ const [messages, setMessages] = useState<ChatMessage[]>([])+ const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)+ const [isConnected, setIsConnected] = useState(false)++ useEffect(() => {+ const newChannel = supabase.channel(roomName)++ newChannel+ .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {+ setMessages((current) => [...current, payload.payload as ChatMessage])+ })+ .subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ setIsConnected(true)+ }+ })++ setChannel(newChannel)++ return () => {+ supabase.removeChannel(newChannel)+ }+ }, [roomName, username, supabase])++ const sendMessage = useCallback(+ async (content: string) => {+ if (!channel || !isConnected) return++ const message: ChatMessage = {+ id: crypto.randomUUID(),+ content,+ user: {+ name: username,+ },+ createdAt: new Date().toISOString(),+ }++ // Update local state immediately for the sender+ setMessages((current) => [...current, message])++ await channel.send({+ type: 'broadcast',+ event: EVENT_MESSAGE_TYPE,+ payload: message,+ })+ },+ [channel, isConnected, username]+ )++ return { messages, sendMessage, isConnected }+}diff --git a/apps/ui-library/registry/default/blocks/realtime-chat/registry-item.json b/apps/ui-library/registry/default/blocks/realtime-chat/registry-item.jsonnew file mode 100644index 00000000000..ff24e12c09f--- /dev/null+++ b/apps/ui-library/registry/default/blocks/realtime-chat/registry-item.json@@ -0,0 +1,27 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "realtime-chat",+ "type": "registry:component",+ "title": "Realtime Chat",+ "description": "Component which renders realtime chat messages from other users in a room.",+ "registryDependencies": ["input", "button"],+ "dependencies": ["lucide-react"],+ "files": [+ {+ "path": "registry/default/blocks/realtime-chat/components/chat-message.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/components/realtime-chat.tsx",+ "type": "registry:component"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",+ "type": "registry:hook"+ },+ {+ "path": "registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx",+ "type": "registry:hook"+ }+ ]+}diff --git a/apps/ui-library/registry/default/examples/realtime-chat-demo.tsx b/apps/ui-library/registry/default/examples/realtime-chat-demo.tsxnew file mode 100644index 00000000000..cb8bb61e58c--- /dev/null+++ b/apps/ui-library/registry/default/examples/realtime-chat-demo.tsx@@ -0,0 +1,71 @@+'use client'++import { RealtimeChat } from '@/registry/default/blocks/realtime-chat/components/realtime-chat'+import { Input } from '@/registry/default/components/ui/input'+import { Label } from '@/registry/default/components/ui/label'+import { useEffect, useState } from 'react'++const names = [+ 'Mark S',+ 'Milchick',+ 'Irving',+ 'Gemma',+ 'Dylan',+ 'Helly R',+ 'Harmony',+ 'Terry',+ 'Ivan',+ 'Alaister',+ 'Joshen',+ 'Jordi',+ 'Filipe',+]++const RealtimeChatDemo = () => {+ const [username, setUsername] = useState('')++ useEffect(() => {+ setUsername(names[Math.floor(Math.random() * names.length)])+ }, [])++ const messages = [+ {+ id: '1',+ content: 'Where are you Dylan?',+ user: {+ name: 'Harmony',+ },+ createdAt: new Date().toISOString(),+ },+ {+ id: '2',+ content: 'in the bathroom',+ user: {+ name: 'Dylan',+ },+ createdAt: new Date().toISOString(),+ },+ {+ id: '3',+ content: "Please don't tell us what you're doing in the bathroom",+ user: {+ name: 'Mark S',+ },+ createdAt: new Date().toISOString(),+ },+ ]++ return (+ <div className="flex flex-col w-full h-[600px] p-4">+ <div className="p-4">+ <Label className="text-xs font-medium mb-1 ml-1 text-foreground-light">Username</Label>+ <Input className="text-sm" value={username} onChange={(e) => setUsername(e.target.value)} />+ </div>+ <div className="flex-1 border rounded-lg overflow-hidden">+ <RealtimeChat roomName="chat-demo" username={username} messages={messages} />+ </div>+ </div>+ )+}++export default RealtimeChatDemo