The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feat/realtime examples (#34317)
Saxon Fletcher7af346d1851e
diff --git a/apps/www/components/Realtime/example-layout.tsx b/apps/www/components/Realtime/example-layout.tsxnew file mode 100644index 00000000000..1994796698b--- /dev/null+++ b/apps/www/components/Realtime/example-layout.tsx@@ -0,0 +1,112 @@+'use client'+import SandpackWrapper from './sandpack'+import { Button, CodeBlock } from 'ui'+import { useState } from 'react'+import { ChevronLeft, ChevronRight, Code, Eye } from 'lucide-react'++export type ExampleLayoutProps = {+ appJsCode: string+ files: Record<string, string>+ dependencies?: Record<string, string>+ title?: string+ description?: string+ onPrevious?: () => void+ onNext?: () => void+}++export default function ExampleLayout({+ appJsCode,+ files,+ dependencies = {},+ title = 'App.js',+ description = 'This is an example of a realtime app.',+ onPrevious,+ onNext,+}: ExampleLayoutProps) {+ const [viewMode, setViewMode] = useState<'code' | 'preview'>('preview')++ const formattedCode = `// # ${title}+// ${description}++${appJsCode}`++ return (+ <div className="h-full w-full flex flex-col overflow-hidden">+ {/* Header Bar */}+ <div className="grid grid-cols-3 items-center px-2 py-2 border-b border-muted">+ {/* Left side: Code/Preview Toggle */}+ <div>+ <div className="flex w-fit gap-1">+ <Button+ type="text"+ onClick={() => setViewMode('code')}+ icon={<Code size={14} />}+ size="tiny"+ className={`${viewMode === 'code' ? 'bg-surface-200 text-foreground' : ''}`}+ aria-label="Show code"+ >+ <span className="hidden sm:inline">Code</span>+ </Button>+ <Button+ type="text"+ onClick={() => setViewMode('preview')}+ size="tiny"+ icon={<Eye size={14} />}+ className={`${viewMode === 'preview' ? 'bg-surface-200 text-foreground' : ''}`}+ aria-label="Show preview"+ >+ <span className="hidden sm:inline">Preview</span>+ </Button>+ </div>+ </div>+ {/* Center: Title */}+ <div className="text-sm font-medium truncate mx-2 text-center">{title}</div>++ {/* Right: Navigation */}+ <div className="flex gap-1 justify-end">+ <Button+ type="outline"+ onClick={onPrevious}+ disabled={!onPrevious}+ className="p-1 rounded hover:bg-surface-200 text-foreground-light disabled:opacity-50 disabled:cursor-not-allowed"+ aria-label="Previous example"+ >+ <ChevronLeft size={16} />+ </Button>+ <Button+ type="outline"+ onClick={onNext}+ disabled={!onNext}+ className="p-1 rounded hover:bg-surface-200 text-foreground-light disabled:opacity-50 disabled:cursor-not-allowed"+ aria-label="Next example"+ >+ <ChevronRight size={16} />+ </Button>+ </div>+ </div>++ {viewMode === 'preview' ? (+ /* Previews - shown when in preview mode */+ <div className="h-full grid grid-cols-1 lg:grid-cols-2 divide-y lg:divide-y-0 lg:divide-x divide-muted">+ <div className="h-96 lg:h-full">+ <SandpackWrapper files={files} dependencies={dependencies} />+ </div>+ <div className="h-96 lg:h-full">+ <SandpackWrapper files={files} dependencies={dependencies} />+ </div>+ </div>+ ) : (+ /* Code view - shown when in code mode */+ <CodeBlock+ hideLineNumbers+ wrapperClassName="w-full"+ className="!bg-transparent h-[500px] lg:h-full overflow-auto p-8 border-none rounded-none"+ wrapLines+ language="jsx"+ >+ {formattedCode}+ </CodeBlock>+ )}+ </div>+ )+}diff --git a/apps/www/components/Realtime/examples/chat-example.tsx b/apps/www/components/Realtime/examples/chat-example.tsxnew file mode 100644index 00000000000..917dcff28b4--- /dev/null+++ b/apps/www/components/Realtime/examples/chat-example.tsx@@ -0,0 +1,190 @@+'use client'++import type { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Generate a random user ID and avatar+const userId = Math.random().toString(36).substring(2, 15);+const getAvatarUrl = (id) => \`https://api.dicebear.com/7.x/avataaars/svg?seed=\${id}\`;++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'chat-example-${instanceId}';++export default function App() {+ const [messages, setMessages] = useState([]);+ const [newMessage, setNewMessage] = useState('');+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [onlineUsers, setOnlineUsers] = useState([]);++ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Subscribe to broadcast channel+ const channel = supabase.channel(CHANNEL);++ // Track presence state+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const presenceList = [];++ // Convert presence state to array+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presenceList.push(...presences);+ });++ setOnlineUsers(presenceList);+ });++ channel+ .on('broadcast', { event: 'message' }, (payload) => {+ setMessages((prev) => [...prev, payload.payload]);+ })+ .subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track({+ user_id: userId,+ username: randomName,+ avatar: getAvatarUrl(userId),+ online_at: new Date().getTime(),+ });+ setIsConnected(true);+ }+ });++ return () => {+ channel.unsubscribe();+ };+ }, []);++ const handleSendMessage = (e) => {+ e.preventDefault();+ if (!newMessage.trim() || !isConnected) return;++ const message = {+ id: Math.random().toString(36).substring(2, 15),+ user_id: userId,+ username,+ avatar: getAvatarUrl(userId),+ text: newMessage.trim(),+ created_at: Date.now(),+ };++ // Broadcast the message+ supabase.channel(CHANNEL).send({+ type: 'broadcast',+ event: 'message',+ payload: message,+ });++ setNewMessage('');+ };++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-white antialiased">+ {/* Header */}+ <div className="flex gap-2 flex-wrap absolute top-4 right-4 z-10">+ {onlineUsers.map((user) => (+ <div+ key={user.user_id}+ className="flex items-center text-xs justify-center rounded-full w-8 h-8 bg-neutral-700 text-neutral-300"+ title={user.username}+ >+ <span>{user.username[0]}</span>+ </div>+ ))}+ </div>++ {/* Main content */}+ <div className="flex-1 p-6">+ <div className="h-full flex flex-col max-w-3xl mx-auto">+ <div className="flex-1 overflow-y-auto">+ {messages.length === 0 ? (+ <div className="flex h-full items-center justify-center text-neutral-500">+ No messages yet. Start the conversation!+ </div>+ ) : (+ messages.map((msg, index) => {+ const prevMsg = index > 0 ? messages[index - 1] : null;+ const showHeader = !prevMsg || prevMsg.user_id !== msg.user_id;++ return (+ <div+ key={msg.id}+ >+ <div className="max-w-[70%] w-fit">+ {showHeader && (+ <div className="flex items-center gap-2 text-xs mb-2 mt-4">+ <span className={\`font-medium \${msg.user_id === userId ? 'text-neutral-300' : 'text-neutral-400'}\`}>+ {msg.username}+ </span>+ <span className="text-neutral-500">+ {new Date(msg.created_at).toLocaleTimeString()}+ </span>+ </div>+ )}+ <div className={\`text-neutral-100 py-2 px-3 rounded-xl text-sm mb-1 w-fit \${+ msg.user_id === userId+ ? 'bg-blue-500 text-blue-50'+ : 'bg-neutral-800 text-neutral-100'+ }\`}>{msg.text}</div>+ </div>+ </div>+ );+ })+ )}+ </div>++ <form onSubmit={handleSendMessage} className="flex w-full gap-2">+ <input+ type="text"+ value={newMessage}+ onChange={(e) => setNewMessage(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleSendMessage(e);+ }+ }}+ placeholder="Type a message..."+ disabled={!isConnected}+ className="flex-1 px-4 py-2 bg-neutral-800 text-neutral-100 border-none rounded-full focus:outline-none focus:ring-2 focus:ring-neutral-600 focus:border-transparent placeholder-neutral-500"+ />+ </form>+ </div>+ </div>+ </div>+ );+}`++const chatFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: chatFiles,+ title: 'Chat Example',+ description:+ "A real-time chat application that uses Supabase Realtime's broadcast and presence features to enable instant messaging and show online users.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/collaborative-editor-example.tsx b/apps/www/components/Realtime/examples/collaborative-editor-example.tsxnew file mode 100644index 00000000000..429ed7592a1--- /dev/null+++ b/apps/www/components/Realtime/examples/collaborative-editor-example.tsx@@ -0,0 +1,239 @@+'use client'++import type { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import * as Y from 'yjs';+import Quill from 'quill';+import 'quill/dist/quill.bubble.css'; // Using bubble theme without toolbar++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'editor-example-${instanceId}';++export default function App() {+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [activeUsers, setActiveUsers] = useState([]);+ const editorRef = useRef(null);+ const quillRef = useRef(null);+ const ydocRef = useRef(null);+ const channelRef = useRef(null);+ const isLocalChangeRef = useRef(false);++ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Wait for the editor element to be available+ if (!editorRef.current) return;++ // Initialize Quill without toolbar+ const quill = new Quill(editorRef.current, {+ placeholder: 'Start typing to collaborate...',+ theme: 'bubble', // Using bubble theme which has no toolbar+ formats: [], // Disable all formatting+ modules: {+ clipboard: true,+ toolbar: false+ }+ });++ // Apply dark theme styles to Quill editor+ editorRef.current.style.color = 'rgb(229, 229, 229)'; // text-neutral-200+ const editor = editorRef.current.querySelector('.ql-editor');+ if (editor) {+ editor.style.cssText = \`+ height: 100%;+ font-size: 16px;+ padding: 1rem;+ font-family: 'Inter', sans-serif;+ \`;+ }++ // Set initial empty content+ quill.setText('');++ quillRef.current = quill;++ // Create a YJS document+ const ydoc = new Y.Doc();+ ydocRef.current = ydoc;++ // Create a shared text type+ const ytext = ydoc.getText('quill');++ // Set up Supabase channel+ const channel = supabase.channel(CHANNEL);+ channelRef.current = channel;++ // Handle presence for user list+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const users = [];++ Object.keys(state).forEach(key => {+ const presences = state[key];+ users.push(...presences);+ });++ setActiveUsers(users);+ });++ // Handle document updates+ channel.on('broadcast', { event: 'document-update' }, (payload) => {+ // Skip if this is our own update+ if (payload.payload.sender === ydoc.clientID) return;++ // Apply YJS update+ const update = new Uint8Array(Object.values(payload.payload.update));++ // Set flag to prevent echo+ isLocalChangeRef.current = true;++ // Apply update to YJS document+ Y.applyUpdate(ydoc, update);++ // Update Quill with the new content+ const newContent = ytext.toString();+ const currentContent = quill.getText();++ if (newContent !== currentContent) {+ quill.setText(newContent);+ }++ isLocalChangeRef.current = false;+ });++ // Subscribe to channel+ channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track({+ user_id: ydoc.clientID,+ username: randomName,+ online_at: new Date().getTime()+ });++ setIsConnected(true);+ }+ });++ // Listen for Quill text changes+ quill.on('text-change', (delta, oldDelta, source) => {+ if (source !== 'user' || isLocalChangeRef.current) return;++ // Update YJS document+ ytext.delete(0, ytext.length);+ ytext.insert(0, quill.getText());++ // Broadcast update+ const update = Y.encodeStateAsUpdate(ydoc);++ // Convert to object for JSON serialization+ const updateObj = {};+ update.forEach((value, index) => {+ updateObj[index] = value;+ });++ // Send update via Supabase+ channel.send({+ type: 'broadcast',+ event: 'document-update',+ payload: {+ update: updateObj,+ sender: ydoc.clientID+ }+ });+ });++ // Clean up+ return () => {+ if (channel) {+ channel.unsubscribe();+ }+ };+ }, []);++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-white antialiased">+ {/* Header */}+ <div className="flex gap-2 flex-wrap absolute top-4 right-4">+ {activeUsers.map((user, index) => (+ <div+ key={index}+ className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-neutral-900 text-neutral-300 text-xs"+ >+ <div className="w-1 h-1 rounded-full bg-green-400"></div>+ <span>{user.username}</span>+ </div>+ ))}+ </div>++ {/* Main content */}+ <div className="flex-1 overflow-hidden p-12">+ <div className="max-w-4xl mx-auto h-full">+ <div className="h-full text-neutral-200 overflow-hidden">+ <div ref={editorRef} className="h-full"></div>+ </div>+ </div>+ </div>+ </div>+ );+}`++const editorFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */++/* Override Quill styles for dark theme */+.ql-editor.ql-blank::before {+ color: rgb(115, 115, 115) !important;+ font-style: normal !important;+ content: attr(data-placeholder) !important;+ left: 1rem !important;+ right: 1rem !important;+ pointer-events: none !important;+}++.ql-bubble {+ border: none !important;+}++.ql-editor {+ caret-color: rgb(229, 229, 229) !important;+}++.ql-editor p {+ color: rgb(200, 200, 200) !important;+ line-height: 1.6 !important;+ font-family: 'Inter', sans-serif !important;+}`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: editorFiles,+ dependencies: {+ yjs: 'latest',+ quill: 'latest',+ },+ title: 'Collaborative Editor',+ description:+ "A real-time collaborative text editor that uses Supabase Realtime's broadcast channel to sync document changes between users via YJS CRDT.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/cursor-tracking-example.tsx b/apps/www/components/Realtime/examples/cursor-tracking-example.tsxnew file mode 100644index 00000000000..cd002a20b42--- /dev/null+++ b/apps/www/components/Realtime/examples/cursor-tracking-example.tsx@@ -0,0 +1,321 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef, useCallback } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import { MousePointer2 } from 'lucide-react';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'cursor-tracking-${instanceId}';++export default function App() {+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [userCursors, setUserCursors] = useState({});+ const [localCursorPosition, setLocalCursorPosition] = useState({ x: 0, y: 0 });++ const userId = useRef(Math.random().toString(36).substring(2, 15));+ const userColor = useRef(getRandomColor());+ const containerRef = useRef(null);+ const channelRef = useRef(null);+ const isInitialSetup = useRef(true);++ // Generate a random color for the user+ function getRandomColor() {+ const colors = [+ '#FF5F5F', '#5F9EFF', '#5FFF8F', '#FF5FE0', '#FFC55F', '#AC5FFF',+ '#FF9F5F', '#5FFFA7', '#5FCAFF', '#D25FFF', '#FFA75F', '#5FFFED'+ ];+ return colors[Math.floor(Math.random() * colors.length)];+ }++ // Set up Supabase channel+ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Subscribe to channel+ const channel = supabase.channel(CHANNEL);+ channelRef.current = channel;++ // Handle presence for user information (not cursor positions)+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();++ // Update user information in state+ const updatedUserInfo = {};+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presences.forEach(presence => {+ // Skip our own user info+ if (presence.user_id === userId.current) return;++ // Store user info (but not cursor position)+ updatedUserInfo[presence.user_id] = {+ username: presence.username,+ color: presence.color,+ // Initialize position if it doesn't exist+ position:+ userCursors[presence.user_id]?.position || { x: 0, y: 0 },+ online_at: presence.online_at+ };+ });+ });++ // Remove users who are no longer present+ setUserCursors(prevCursors => {+ const newCursors = { ...prevCursors };++ // Add/update users from presence+ Object.keys(updatedUserInfo).forEach(id => {+ newCursors[id] = {+ ...newCursors[id],+ ...updatedUserInfo[id]+ };+ });++ // Remove users no longer in presence+ Object.keys(newCursors).forEach(id => {+ const userExists = Object.values(state).some(+ presences => presences.some(presence => presence.user_id === id)+ );++ if (!userExists) {+ delete newCursors[id];+ }+ });++ return newCursors;+ });+ });++ // Handle cursor movement broadcasts for immediate updates+ channel.on('broadcast', { event: 'cursor_move' }, (payload) => {+ if (payload.payload.userId === userId.current) return;++ const { userId: cursorUserId, x, y } = payload.payload;++ // Update cursor position in state, preserving other user info+ setUserCursors(prevCursors => {+ if (!prevCursors[cursorUserId]) return prevCursors;++ return {+ ...prevCursors,+ [cursorUserId]: {+ ...prevCursors[cursorUserId],+ position: { x, y }+ }+ };+ });+ });++ // Initial subscription+ channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Initial presence tracking with user info (without cursor position)+ await channel.track({+ user_id: userId.current,+ username: randomName,+ color: userColor.current,+ online_at: new Date().getTime()+ });++ setIsConnected(true);+ isInitialSetup.current = false;+ }+ });++ // Clean up on unmount+ return () => {+ channel.unsubscribe();+ };+ }, []);++ // Broadcast cursor position immediately on mouse move+ const broadcastCursorPosition = useCallback((position) => {+ if (!channelRef.current || !isConnected || isInitialSetup.current) return;++ // Send cursor position as broadcast for immediate updates+ channelRef.current.send({+ type: 'broadcast',+ event: 'cursor_move',+ payload: {+ userId: userId.current,+ x: position.x,+ y: position.y+ }+ });+ }, [isConnected]);++ // Track and broadcast mouse movement+ const handleMouseMove = useCallback((e) => {+ if (!containerRef.current) return;++ // Get container bounds+ const rect = containerRef.current.getBoundingClientRect();++ // Calculate relative position within container (as percentage)+ const relativeX = ((e.clientX - rect.left) / rect.width) * 100;+ const relativeY = ((e.clientY - rect.top) / rect.height) * 100;++ const newPosition = { x: relativeX, y: relativeY };++ // Update local cursor position+ setLocalCursorPosition(newPosition);++ // Broadcast position to other users+ broadcastCursorPosition(newPosition);+ }, [broadcastCursorPosition]);++ return (+ <div+ className="flex flex-col h-screen bg-neutral-900 text-white antialiased"+ onMouseMove={handleMouseMove}+ ref={containerRef}+ style={{ cursor: 'none' }} // Hide the native cursor+ >+ {/* Main tracking area with grid background */}+ <div className="flex-1 overflow-hidden relative">+ <div+ className="w-full h-full bg-neutral-800 relative"+ style={{+ backgroundImage: 'linear-gradient(to right, rgba(75, 85, 99, 0.1) 1px, transparent 1px), linear-gradient(to bottom, rgba(75, 85, 99, 0.1) 1px, transparent 1px)',+ backgroundSize: '40px 40px'+ }}+ >+ {/* Local cursor icon (replacing native cursor) */}+ <div+ className="absolute pointer-events-none flex flex-col items-start"+ style={{+ left: \`\${localCursorPosition.x}%\`,+ top: \`\${localCursorPosition.y}%\`,+ zIndex: 110, // Higher than other cursors+ transform: 'translate(-50%, -50%)'+ }}+ >+ {/* Local cursor trail effect */}+ <div+ className="absolute w-3 h-3 rounded-full opacity-30"+ style={{+ backgroundColor: userColor.current,+ transform: 'translate(-50%, -50%)',+ filter: 'blur(2px)'+ }}+ />++ <div style={{ color: userColor.current }}>+ <MousePointer2 strokeWidth={1.5} size={24} className="drop-shadow-md" />+ </div>+ </div>++ {/* Render other users' cursors */}+ {Object.entries(userCursors).map(([id, { position, username, color }]) => (+ <div+ key={id}+ className="absolute pointer-events-none flex flex-col items-start"+ style={{+ left: \`\${position.x}%\`,+ top: \`\${position.y}%\`,+ zIndex: 100,+ transform: 'translate(-50%, -50%)'+ }}+ >+ {/* Cursor trail effect */}+ <div+ className="absolute w-3 h-3 rounded-full opacity-40"+ style={{+ backgroundColor: color,+ transform: 'translate(-50%, -50%)',+ filter: 'blur(3px)'+ }}+ />++ {/* Cursor icon */}+ <div style={{ color }}>+ <MousePointer2 strokeWidth={1.5} size={24} className="drop-shadow-md" />+ </div>++ {/* Username label */}+ <div+ className="mt-2 px-2 py-1 rounded text-xs whitespace-nowrap"+ style={{+ backgroundColor: color,+ color: '#fff',+ fontWeight: 500,+ boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)'+ }}+ >+ {username}+ </div>+ </div>+ ))}+ </div>+ </div>+++ {/* Connection status */}+ {!isConnected && (+ <div className="absolute top-16 left-0 right-0 flex justify-center">+ <div className="bg-red-500/80 text-white px-4 py-2 rounded-full text-sm">+ Connecting to Supabase Realtime...+ </div>+ </div>+ )}++ {/* Active users list */}+ <div className="absolute top-4 right-4 flex gap-2 flex-wrap justify-end">+ {Object.entries(userCursors).map(([id, { username, color }]) => (+ <div+ key={id}+ className="flex items-center gap-2 p-1.5 pl-2 pr-3 rounded-full bg-neutral-800 text-neutral-200 text-xs font-medium"+ >+ <div+ className="w-2 h-2 rounded-full"+ style={{ backgroundColor: color }}+ ></div>+ {username}+ </div>+ ))}+ {/* Include yourself in the list */}+ <div+ className="flex items-center gap-2 p-1.5 pl-2 pr-3 rounded-full bg-neutral-800 text-neutral-200 text-xs font-medium"+ >+ <div+ className="w-2 h-2 rounded-full"+ style={{ backgroundColor: userColor.current }}+ ></div>+ {username} (you)+ </div>+ </div>+ </div>+ );+}`++const cursorTrackingFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: cursorTrackingFiles,+ title: 'Cursor Tracking',+ description:+ "A multi-user cursor tracking application that uses Supabase Realtime's broadcast and presence features to show real-time cursor movements of all connected users.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/emoji-picker-example.tsx b/apps/www/components/Realtime/examples/emoji-picker-example.tsxnew file mode 100644index 00000000000..0f8667bfae2--- /dev/null+++ b/apps/www/components/Realtime/examples/emoji-picker-example.tsx@@ -0,0 +1,231 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import { createClient } from '@supabase/supabase-js';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'emoji-example-${instanceId}';++// List of emojis for the picker+const EMOJIS = ['👍', '❤️', '😂', '🎉', '🔥', '👏', '🚀', '✨', '🌈', '🦄'];++export default function App() {+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [activeUsers, setActiveUsers] = useState([]);+ const [animatingEmojis, setAnimatingEmojis] = useState([]);++ const userId = useRef(Math.random().toString(36).substring(2, 15));+ const channelRef = useRef(null);+ const containerRef = useRef(null);++ // Set up Supabase channel+ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Subscribe to channel+ const channel = supabase.channel(CHANNEL, {+ config: {+ presence: {+ key: userId.current,+ },+ },+ });++ channelRef.current = channel;++ // Handle presence for user list+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const users = [];++ // Convert presence state to array+ Object.keys(state).forEach(key => {+ const presences = state[key];+ users.push(...presences);+ });++ setActiveUsers(users);+ });++ // Handle emoji click events+ channel.on('broadcast', { event: 'emoji_click' }, (payload) => {+ const { emoji, position, senderId } = payload.payload;++ // Don't animate our own emoji clicks (we already did that)+ if (senderId === userId.current) return;++ // Create a new animating emoji+ createAnimatingEmoji(emoji, position);+ });++ // Subscribe to channel+ channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track({+ userId: userId.current,+ username: randomName,+ online_at: new Date().getTime()+ });++ setIsConnected(true);+ }+ });++ return () => {+ channel.unsubscribe();+ };+ }, []);++ // Clean up finished animations+ useEffect(() => {+ if (animatingEmojis.length > 0) {+ const timer = setTimeout(() => {+ setAnimatingEmojis(emojis => emojis.filter(e => Date.now() - e.timestamp < 2000));+ }, 2000);++ return () => clearTimeout(timer);+ }+ }, [animatingEmojis]);++ // Handle emoji click+ const handleEmojiClick = (emoji, event) => {+ if (!isConnected) return;++ // Get the position of the clicked emoji relative to the container+ const rect = event.currentTarget.getBoundingClientRect();+ const containerRect = containerRef.current.getBoundingClientRect();++ const position = {+ x: rect.left + rect.width / 2 - containerRect.left,+ y: rect.top - containerRect.top+ };++ // Create a new animating emoji locally+ createAnimatingEmoji(emoji, position);++ // Broadcast the emoji click to other clients+ channelRef.current.send({+ type: 'broadcast',+ event: 'emoji_click',+ payload: {+ emoji,+ position,+ senderId: userId.current+ }+ });+ };++ // Create a new animating emoji+ const createAnimatingEmoji = (emoji, position) => {+ const newEmoji = {+ id: Date.now() + Math.random(),+ emoji,+ position,+ timestamp: Date.now()+ };++ setAnimatingEmojis(emojis => [...emojis, newEmoji]);+ };++ return (+ <div className="h-screen flex flex-col bg-neutral-800 text-white relative overflow-hidden antialiased" ref={containerRef}>+ {/* Toolbar */}+ <div className="flex flex-wrap gap-2 absolute top-4 right-4">+ {activeUsers.map((user, index) => (+ <div+ key={index}+ className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-neutral-900 text-neutral-300 text-xs"+ >+ <div className="w-1 h-1 rounded-full bg-green-400"></div>+ <span>{user.username}</span>+ </div>+ ))}+ </div>++ {/* Main content */}+ <div className="flex-1 relative overflow-hidden">+ <div className="absolute inset-0">+ {/* Animating emojis */}+ {animatingEmojis.map((emojiObj) => (+ <div+ key={emojiObj.id}+ className="absolute text-2xl pointer-events-none animate-float-up"+ style={{+ left: \`\${emojiObj.position.x}px\`,+ top: \`\${emojiObj.position.y}px\`,+ transform: 'translate(-50%, -50%)',+ animation: 'float-up 2s ease-out forwards'+ }}+ >+ {emojiObj.emoji}+ </div>+ ))}++ {/* Instructions */}+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center">+ <h2 className="font-medium text-neutral-300 mb-2">Click an emoji below to send a reaction!</h2>+ <p className="text-neutral-400">All connected users will see your reactions in real-time.</p>+ </div>+ </div>+ </div>++ {/* Emoji picker bar */}+ <div className="flex justify-center items-center p-4 border-t border-neutral-700/50 z-10">+ {EMOJIS.map((emoji) => (+ <button+ key={emoji}+ className="text-2xl flex justify-center items-center w-16 h-16 rounded-full hover:bg-neutral-800 active:scale-90 transition-all duration-200"+ onClick={(e) => handleEmojiClick(emoji, e)}+ >+ {emoji}+ </button>+ ))}+ </div>+ </div>+ );+}`++const emojiPickerFiles = {+ '/App.js': appJsCode,+ '/styles.css': `@keyframes float-up {+ 0% {+ opacity: 1;+ transform: translate(-50%, -50%) scale(1);+ }+ 100% {+ opacity: 0;+ transform: translate(-50%, -300px) scale(1.5);+ }+}++.animate-float-up {+ animation: float-up 2s ease-out forwards;+}`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: emojiPickerFiles,+ title: 'Emoji Picker',+ description:+ "An interactive emoji reaction system that uses Supabase Realtime's broadcast channel to sync emoji reactions across multiple users in real-time.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/form-presence-example.tsx b/apps/www/components/Realtime/examples/form-presence-example.tsxnew file mode 100644index 00000000000..a6c1284f9dc--- /dev/null+++ b/apps/www/components/Realtime/examples/form-presence-example.tsx@@ -0,0 +1,476 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import { useForm, Controller } from 'react-hook-form';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Generate a random user ID and name+const userId = Math.random().toString(36).substring(2, 15);+const getRandomColor = () => {+ const colors = ['#FF5F5F', '#5F9EFF', '#5FFF8F', '#FF5FE0', '#FFC55F', '#AC5FFF'];+ return colors[Math.floor(Math.random() * colors.length)];+};+const userColor = getRandomColor();++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'form-presence-${instanceId}';+const FORM_BROADCAST = 'form_data';+const FOCUS_BROADCAST = 'field_focus';+const SUBMIT_BROADCAST = 'form_submit';++export default function App() {+ const [activeUsers, setActiveUsers] = useState({});+ const [focusedFields, setFocusedFields] = useState({});+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [userCount, setUserCount] = useState(0);+ const [formSubmitted, setFormSubmitted] = useState(false);+ const [submittedBy, setSubmittedBy] = useState(null);+ const [submittedData, setSubmittedData] = useState(null);+ const localFormUpdateRef = useRef(false);+ const channelRef = useRef(null);+ const previousFormValues = useRef({});++ const { control, handleSubmit, setValue, watch, formState: { errors } } = useForm({+ defaultValues: {+ title: '',+ subtitle: '',+ url: '',+ description: '',+ }+ });++ const formValues = watch();++ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Save initial form values+ previousFormValues.current = { ...formValues };++ // Subscribe to presence channel+ const channel = supabase.channel(CHANNEL);+ channelRef.current = channel;++ // Track presence state+ channel+ .on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const userMap = {};+ let count = 0;++ // Convert presence state to map+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presences.forEach(presence => {+ userMap[presence.user_id] = {+ username: presence.username,+ color: presence.color,+ online_at: presence.online_at,+ };+ count++;+ });+ });++ setActiveUsers(userMap);+ setUserCount(count);+ })+ .on('broadcast', { event: FOCUS_BROADCAST }, (payload) => {+ // Update which fields are being focused by other users+ if (payload.payload.user_id !== userId) {+ setFocusedFields(prev => ({+ ...prev,+ [payload.payload.field]: payload.payload.isFocused ? {+ user_id: payload.payload.user_id,+ username: payload.payload.username,+ color: payload.payload.color+ } : null+ }));+ }+ })+ .on('broadcast', { event: FORM_BROADCAST }, (payload) => {+ // Update form data when received from other users+ if (payload.payload.user_id !== userId) {+ // Set flag to indicate this update is from remote+ localFormUpdateRef.current = true;++ // Update only changed fields+ Object.entries(payload.payload.formData).forEach(([field, value]) => {+ // Only update if the value actually changed+ if (value !== formValues[field]) {+ setValue(field, value);+ }+ });++ // Update previous form values+ previousFormValues.current = { ...payload.payload.formData };++ // Clear flag after a small delay to ensure React has processed the update+ setTimeout(() => {+ localFormUpdateRef.current = false;+ }, 50);+ }+ })+ .on('broadcast', { event: SUBMIT_BROADCAST }, (payload) => {+ // Update form submission status for all clients+ setFormSubmitted(true);+ setSubmittedBy(payload.payload.username);+ setSubmittedData(payload.payload.formData);+ })+ .subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Send presence state when subscribed+ await channel.track({+ user_id: userId,+ username: randomName,+ color: userColor,+ online_at: new Date().getTime(),+ });+ setIsConnected(true);++ // Broadcast initial form state+ channel.send({+ type: 'broadcast',+ event: FORM_BROADCAST,+ payload: {+ user_id: userId,+ formData: formValues+ }+ });+ }+ });++ return () => {+ // Clean up subscription+ channel.unsubscribe();+ };+ }, []);++ // Watch for form changes and broadcast them+ useEffect(() => {+ // Only broadcast changes that came from the local user and if values actually changed+ if (isConnected && !localFormUpdateRef.current && channelRef.current) {+ // Check if any values have changed+ let hasChanges = false;++ for (const key in formValues) {+ if (formValues[key] !== previousFormValues.current[key]) {+ hasChanges = true;+ break;+ }+ }++ if (hasChanges) {+ // Update previous values to prevent redundant broadcasts+ previousFormValues.current = { ...formValues };++ channelRef.current.send({+ type: 'broadcast',+ event: FORM_BROADCAST,+ payload: {+ user_id: userId,+ formData: formValues+ }+ });+ }+ }+ }, [formValues, isConnected]);++ const handleFieldFocus = (fieldName, isFocused) => {+ if (isConnected && channelRef.current) {+ channelRef.current.send({+ type: 'broadcast',+ event: FOCUS_BROADCAST,+ payload: {+ user_id: userId,+ username,+ color: userColor,+ field: fieldName,+ isFocused+ }+ });+ }+ };++ // Check if a field is locked (being edited by another user)+ const isFieldLocked = (fieldName) => {+ return focusedFields[fieldName] && focusedFields[fieldName].user_id !== userId;+ };++ const renderUserBadge = (fieldName) => {+ if (!focusedFields[fieldName]) return null;++ const user = focusedFields[fieldName];+ return (+ <div+ className="absolute right-0 top-1 transform -translate-y-1/2 px-2 py-1 rounded-full text-xs text-white"+ style={{ backgroundColor: user.color }}+ >+ {user.username}+ </div>+ );+ };++ const handleFormSubmit = (e) => {+ e.preventDefault();++ if (isConnected && channelRef.current) {+ // Broadcast form submission to all clients+ channelRef.current.send({+ type: 'broadcast',+ event: SUBMIT_BROADCAST,+ payload: {+ user_id: userId,+ username,+ formData: formValues,+ submittedAt: new Date().toISOString()+ }+ });++ // Update local state+ setFormSubmitted(true);+ setSubmittedBy(username);+ setSubmittedData(formValues);+ }+ };++ if (formSubmitted) {+ return (+ <div className="p-8 flex flex-col min-h-screen bg-neutral-900 text-neutral-100 antialiased">+ <header className="mb-8">+ <div className="max-w-3xl mx-auto flex justify-between items-center">+ <h1 className="text-xl font-medium">Collaborative Form</h1>+ <div className="flex items-center gap-2">+ <div+ className="w-3 h-3 rounded-full bg-green-400"+ title={isConnected ? 'Connected' : 'Disconnected'}+ ></div>+ <span className="text-sm text-neutral-400">+ {userCount} {userCount === 1 ? 'user' : 'users'} online+ </span>+ </div>+ </div>+ </header>++ <main className="flex-1 overflow-auto">+ <div className="max-w-3xl mx-auto bg-neutral-800 rounded-lg p-6 border-neutral-600">+ <div className="flex items-center mb-4">+ <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center">+ <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />+ </svg>+ </div>+ <div className="ml-4">+ <h2 className="text-md font-medium text-white mb-1">Form Submitted Successfully!</h2>+ <p className="text-neutral-400 text-sm">Submitted by {submittedBy}</p>+ </div>+ </div>++ <div className="space-y-3 my-6 text-sm">+ {submittedData && Object.entries(submittedData).map(([key, value]) => (+ <div key={key}>+ <div className="text-sm text-neutral-400 capitalize mb-1">{key}</div>+ <div className="text-white">{value || <em className="text-neutral-500">Empty</em>}</div>+ </div>+ ))}+ </div>+ </div>+ </main>+ </div>+ );+ }++ return (+ <div className="min-h-screen p-8 flex flex-col bg-neutral-900 text-white antialiased">+ <header className="mb-8">+ <div className="max-w-3xl mx-auto flex justify-between items-center">+ <h1 className="text-xl font-medium">Collaborative Form</h1>+ <div className="flex items-center gap-2">+ <div+ className="w-2 h-2 rounded-full bg-green-400"+ title={isConnected ? 'Connected' : 'Disconnected'}+ ></div>+ <span className="text-sm text-neutral-400">+ {userCount} {userCount === 1 ? 'user' : 'users'} editing+ </span>+ </div>+ </div>+ </header>++ <main className="flex-1">+ <form className="max-w-3xl mx-auto space-y-4">+ <div className="relative">+ {renderUserBadge('title')}+ <label className="block text-sm font-medium text-neutral-400 mb-2">+ Title+ </label>+ <Controller+ name="title"+ control={control}+ render={({ field }) => (+ <input+ {...field}+ className={\`w-full p-2 rounded-md bg-neutral-800 border text-sm \${+ isFieldLocked('title')+ ? 'border-red-500 opacity-70'+ : field.value+ ? 'border-neutral-600'+ : 'border-neutral-700'+ }\`}+ disabled={isFieldLocked('title')}+ style={{+ borderColor: isFieldLocked('title') ? focusedFields['title'].color : '',+ boxShadow: isFieldLocked('title') ? \`0 0 0 1px \${focusedFields['title'].color}\` : ''+ }}+ placeholder="Enter title"+ onFocus={() => handleFieldFocus('title', true)}+ onBlur={() => handleFieldFocus('title', false)}+ />+ )}+ />+ </div>++ <div className="relative">+ {renderUserBadge('subtitle')}+ <label className="block text-sm font-medium text-neutral-400 mb-2">+ Subtitle+ </label>+ <Controller+ name="subtitle"+ control={control}+ render={({ field }) => (+ <input+ {...field}+ className={\`w-full p-2 rounded-md bg-neutral-800 border text-sm \${+ isFieldLocked('subtitle')+ ? 'border-red-500 opacity-70'+ : field.value+ ? 'border-neutral-600'+ : 'border-neutral-700'+ }\`}+ disabled={isFieldLocked('subtitle')}+ style={{+ borderColor: isFieldLocked('subtitle') ? focusedFields['subtitle'].color : '',+ boxShadow: isFieldLocked('subtitle') ? \`0 0 0 1px \${focusedFields['subtitle'].color}\` : ''+ }}+ placeholder="Enter subtitle"+ onFocus={() => handleFieldFocus('subtitle', true)}+ onBlur={() => handleFieldFocus('subtitle', false)}+ />+ )}+ />+ </div>++ <div className="relative">+ {renderUserBadge('url')}+ <div className="flex justify-between items-center mb-1">+ <label className="block text-sm font-medium text-neutral-400">+ URL+ </label>+ </div>+ <Controller+ name="url"+ control={control}+ render={({ field }) => (+ <input+ {...field}+ className={\`w-full p-2 rounded-md bg-neutral-800 border text-sm \${+ isFieldLocked('url')+ ? 'border-red-500 opacity-70'+ : field.value+ ? 'border-neutral-600'+ : 'border-neutral-700'+ }\`}+ disabled={isFieldLocked('url')}+ style={{+ borderColor: isFieldLocked('url') ? focusedFields['url'].color : '',+ boxShadow: isFieldLocked('url') ? \`0 0 0 1px \${focusedFields['url'].color}\` : ''+ }}+ placeholder="Enter URL"+ onFocus={() => handleFieldFocus('url', true)}+ onBlur={() => handleFieldFocus('url', false)}+ />+ )}+ />+ </div>++ <div className="relative">+ {renderUserBadge('description')}+ <label className="block text-sm font-medium text-neutral-400 mb-2">+ Description+ </label>+ <Controller+ name="description"+ control={control}+ render={({ field }) => (+ <textarea+ {...field}+ rows={4}+ className={\`w-full p-2 rounded-md bg-neutral-800 border text-sm \${+ isFieldLocked('description')+ ? 'border-red-500 opacity-70'+ : field.value+ ? 'border-neutral-600'+ : 'border-neutral-700'+ }\`}+ disabled={isFieldLocked('description')}+ style={{+ borderColor: isFieldLocked('description') ? focusedFields['description'].color : '',+ boxShadow: isFieldLocked('description') ? \`0 0 0 1px \${focusedFields['description'].color}\` : ''+ }}+ placeholder="Enter description"+ onFocus={() => handleFieldFocus('description', true)}+ onBlur={() => handleFieldFocus('description', false)}+ />+ )}+ />+ </div>++ <div className="pt-4">+ <button+ type="submit"+ className="w-full py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md font-medium"+ onClick={handleFormSubmit}+ >+ Submit Form+ </button>+ </div>+ </form>+ </main>+ </div>+ );+}`++const formPresenceFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: formPresenceFiles,+ title: 'Form Presence',+ dependencies: {+ 'react-hook-form': 'latest',+ },+ description:+ "A multi-user form that uses Supabase Realtime's presence feature to show which fields are currently being edited by other users in real-time.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/iframe-annotation-example.tsx b/apps/www/components/Realtime/examples/iframe-annotation-example.tsxnew file mode 100644index 00000000000..76a0c82f8c9--- /dev/null+++ b/apps/www/components/Realtime/examples/iframe-annotation-example.tsx@@ -0,0 +1,353 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import { X } from 'lucide-react';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'image-annotation-example-${instanceId}';++export default function App() {+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [activeUsers, setActiveUsers] = useState([]);+ const [comments, setComments] = useState([]);+ const [newComment, setNewComment] = useState('');+ const [commentPosition, setCommentPosition] = useState(null);+ const [imageLoaded, setImageLoaded] = useState(false);++ const userId = useRef(Math.random().toString(36).substring(2, 15));+ const imageRef = useRef(null);+ const containerRef = useRef(null);+ const channelRef = useRef(null);++ // Specific Unsplash image URL+ const imageUrl = "https://images.unsplash.com/photo-1600695580162-cb0fa319067a?q=80&w=3764&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D";++ // Initialize connection+ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Set up Supabase channel+ const channel = supabase.channel(CHANNEL);+ channelRef.current = channel;++ // Handle presence for user list+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const presenceList = [];++ // Convert presence state to array+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presenceList.push(...presences);+ });++ setActiveUsers(presenceList);+ });++ // Handle new comments+ channel.on('broadcast', { event: 'new_comment' }, (payload) => {+ const newComment = payload.payload;++ setComments(prevComments => {+ // Check if comment already exists (avoid duplicates)+ const exists = prevComments.some(comment => comment.id === newComment.id);+ if (exists) return prevComments;++ return [...prevComments, newComment];+ });+ });++ // Handle comment deletion+ channel.on('broadcast', { event: 'delete_comment' }, (payload) => {+ const { commentId } = payload.payload;++ setComments(prevComments =>+ prevComments.filter(comment => comment.id !== commentId)+ );+ });++ // Subscribe to channel+ channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track({+ user_id: userId.current,+ username: randomName,+ online_at: new Date().getTime(),+ });++ setIsConnected(true);+ }+ });++ // Clean up+ return () => {+ if (channel) {+ channel.unsubscribe();+ }+ };+ }, []);++ // Handle image load+ const handleImageLoad = () => {+ setImageLoaded(true);+ };++ // Handle click on the image+ const handleImageClick = (e) => {+ if (!isConnected || !imageRef.current) return;++ // Don't process clicks on existing comments or the input form+ if (+ e.target.closest('[data-comment]') ||+ e.target.closest('[data-comment-bubble]') ||+ e.target.closest('[data-comment-input]')+ ) {+ return;+ }++ // Calculate relative position (%)+ const rect = imageRef.current.getBoundingClientRect();++ const xPercent = ((e.clientX - rect.left) / rect.width) * 100;+ const yPercent = ((e.clientY - rect.top) / rect.height) * 100;++ // Set position for new comment+ setCommentPosition({+ x: xPercent,+ y: yPercent+ });++ // Focus on input (will be created in render)+ setTimeout(() => {+ const input = document.getElementById('new-comment-input');+ if (input) input.focus();+ }, 10);+ };++ // Handle comment submission+ const handleCommentSubmit = (e) => {+ e.preventDefault();++ if (!newComment.trim() || !commentPosition || !isConnected) {+ // Reset state if invalid+ setCommentPosition(null);+ setNewComment('');+ return;+ }++ // Create new comment+ const comment = {+ id: \`\${userId.current}-\${Date.now()}\`,+ text: newComment.trim(),+ position: commentPosition,+ user_id: userId.current,+ username,+ created_at: Date.now(),+ };++ // Add to local state+ setComments(prevComments => [...prevComments, comment]);++ // Broadcast to other clients+ channelRef.current.send({+ type: 'broadcast',+ event: 'new_comment',+ payload: comment,+ });++ // Reset state+ setCommentPosition(null);+ setNewComment('');+ };++ // Handle comment deletion+ const handleDeleteComment = (commentId) => {+ // Remove from local state+ setComments(prevComments =>+ prevComments.filter(comment => comment.id !== commentId)+ );++ // Broadcast deletion+ channelRef.current.send({+ type: 'broadcast',+ event: 'delete_comment',+ payload: { commentId },+ });+ };++ // Cancel new comment+ const handleCancelComment = () => {+ setCommentPosition(null);+ setNewComment('');+ };++ // Handle input change+ const handleInputChange = (e) => {+ setNewComment(e.target.value);+ };++ // Handle keydown in input+ const handleInputKeyDown = (e) => {+ if (e.key === 'Escape') {+ handleCancelComment();+ }+ };++ return (+ <div className="flex flex-col h-screen bg-neutral-800 text-white antialiased">+ <div className="flex gap-2 flex-wrap absolute top-4 right-4 z-10">+ {activeUsers.map((user) => (+ <div+ key={user.user_id}+ className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-neutral-900 text-neutral-300 text-xs"+ >+ <div className="w-1 h-1 rounded-full bg-green-400"></div>+ <span>{user.username}</span>+ </div>+ ))}+ </div>++ {/* Main content */}+ <div className="flex-1 overflow-hidden">+ <div className="max-w-6xl mx-auto h-full">+ <div className="relative h-full bg-neutral-800 overflow-hidden" ref={containerRef}>+ {/* Loading indicator */}+ {!imageLoaded && (+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-neutral-900/80 z-10">+ <div className="w-10 h-10 border-4 border-neutral-700 border-t-neutral-200 rounded-full animate-spin mb-2"></div>+ <p className="text-neutral-400 text-sm">Loading image...</p>+ </div>+ )}++ {/* The image to annotate */}+ <img+ ref={imageRef}+ src={imageUrl}+ alt="Annotatable image"+ className="w-full h-full object-cover cursor-crosshair"+ onClick={handleImageClick}+ onLoad={handleImageLoad}+ />++ {/* Comments overlay */}+ <div className="absolute inset-0 pointer-events-none">+ {comments.map((comment) => (+ <div+ key={comment.id}+ data-comment+ className="absolute pointer-events-auto"+ style={{+ left: \`\${comment.position.x}%\`,+ top: \`\${comment.position.y}%\`,+ transform: 'translate(-50%, -100%)',+ }}+ >+ <div+ data-comment-bubble+ className="max-w-[400px] min-w-32 bg-neutral-800 rounded shadow p-3 pt-2 mb-2"+ >+ <div className="flex justify-between items-center mb-1">+ <span className="text-xs text-neutral-400">{comment.username}</span>+ <button+ onClick={() => handleDeleteComment(comment.id)}+ className="w-5 h-5 flex items-center justify-center rounded-full hover:bg-neutral-800 text-neutral-500 hover:text-red-400"+ aria-label="Delete comment"+ >+ <X strokeWidth={1.5} size={14} />+ </button>+ </div>+ <div className="text-xs text-neutral-200 break-words">{comment.text}</div>+ </div>+ <div className="w-0 h-0 border-l-[8px] border-l-transparent border-r-[8px] border-r-transparent border-t-[8px] border-t-neutral-900/90 mx-auto"></div>+ </div>+ ))}++ {/* New comment input */}+ {commentPosition && (+ <div+ data-comment+ className="absolute pointer-events-auto"+ style={{+ left: \`\${commentPosition.x}%\`,+ top: \`\${commentPosition.y}%\`,+ transform: 'translate(-50%, -100%)',+ }}+ onClick={(e) => e.stopPropagation()}+ >+ <div+ data-comment-bubble+ className="bg-neutral-800 rounded shadow p-2 mb-2 w-64"+ >+ <form onSubmit={handleCommentSubmit}>+ <input+ id="new-comment-input"+ type="text"+ value={newComment}+ onChange={handleInputChange}+ onKeyDown={handleInputKeyDown}+ placeholder="Type your comment..."+ data-comment-input+ className="w-full px-2 py-1.5 bg-neutral-800 border border-neutral-700 rounded text-xs text-neutral-200 placeholder-neutral-500 mb-2"+ autoFocus+ />+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={handleCancelComment}+ className="px-3 py-1 text-xs bg-neutral-800 text-neutral-300 rounded hover:bg-neutral-700"+ >+ Cancel+ </button>+ <button+ type="submit"+ className="px-3 py-1 text-xs bg-neutral-300 text-neutral-900 rounded hover:bg-neutral-200 disabled:opacity-50 disabled:cursor-not-allowed"+ disabled={!newComment.trim()}+ >+ Add+ </button>+ </div>+ </form>+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}`++const imageAnnotationFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: imageAnnotationFiles,+ title: 'IFrame Annotation',+ description:+ "A collaborative annotation tool that uses Supabase Realtime's broadcast channel to synchronize annotations and comments on embedded web content across multiple users.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/log-viewer-example.tsx b/apps/www/components/Realtime/examples/log-viewer-example.tsxnew file mode 100644index 00000000000..c563486d5c4--- /dev/null+++ b/apps/www/components/Realtime/examples/log-viewer-example.tsx@@ -0,0 +1,415 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const appJsCode = `import { useEffect, useState, useCallback, useRef } from 'react';+import { createClient } from '@supabase/supabase-js';+import { AutoSizer, Table, Column, InfiniteLoader } from 'react-virtualized';+import 'react-virtualized/styles.css';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Constants+const PAGE_SIZE = 50;+const TABLE_NAME = 'logging_data';++// Log level colors+const LOG_LEVEL_COLORS = {+ ERROR: 'bg-red-800',+ WARN: 'bg-amber-800',+ INFO: 'bg-green-800',+ DEBUG: 'bg-blue-800'+};++export default function App() {+ // Instance ID for channel+ const instanceId = useRef(Math.random().toString(36).substring(2, 9)).current;++ // Log viewer state+ const [logs, setLogs] = useState([]);+ const [totalCount, setTotalCount] = useState(0);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState(null);+ const [isAtTop, setIsAtTop] = useState(true);+ const [logCountAtScroll, setLogCountAtScroll] = useState(0);++ // Refs+ const tableRef = useRef(null);+ const gridRef = useRef(null);+ const newLogsRef = useRef([]);++ // Function to load rows from Supabase+ const loadMoreRows = async ({ startIndex, stopIndex }) => {+ try {+ setIsLoading(true);+ setError(null);++ console.log(\`Loading rows from \${startIndex} to \${stopIndex}\`);++ // Calculate the range for the query+ const from = startIndex;+ const to = stopIndex;++ // Query Supabase for the range of rows+ const { data, error, count } = await supabase+ .from(TABLE_NAME)+ .select('*', { count: 'exact' })+ .range(from, to)+ .order('created_at', { ascending: false });++ if (error) throw error;++ // Update total count if we got it+ if (count !== null) {+ setTotalCount(count);+ }++ // Update logs with the fetched data+ setLogs(prevLogs => {+ // Create a new array with the same length as before+ const newLogs = [...prevLogs];++ // Insert the fetched logs at their correct positions+ data.forEach((log, index) => {+ newLogs[startIndex + index] = log;+ });++ return newLogs;+ });++ return data;+ } catch (err) {+ console.error('Error loading logs:', err);+ setError(err.message);+ return [];+ } finally {+ setIsLoading(false);+ }+ };++ // Function to determine if a row is loaded+ const isRowLoaded = ({ index }) => {+ return Boolean(logs[index]);+ };++ // Cell data getters+ const cellDataGetter = ({ dataKey, rowData }) => {+ return rowData ? rowData[dataKey] : null;+ };++ // Cell renderers+ const idCellRenderer = ({ cellData }) => {+ return <div className="p-2 overflow-hidden text-ellipsis whitespace-nowrap text-neutral-300">#{cellData || ''}</div>;+ };++ const messageCellRenderer = ({ cellData }) => {+ return (+ <div className="p-2 overflow-hidden whitespace-pre-wrap text-neutral-300 leading-relaxed">+ {cellData || ''}+ </div>+ );+ };++ const levelCellRenderer = ({ cellData }) => {+ if (!cellData) return <div className="p-2"></div>;++ const level = cellData;+ const colorClass = LOG_LEVEL_COLORS[level] || 'bg-neutral-700';++ return (+ <div+ className={\`p-2 inline-block rounded px-2 py-1 font-medium text-neutral-100/50 text-center min-w-[60px] text-white \${colorClass}\`}+ >+ {level}+ </div>+ );+ };++ const timestampCellRenderer = ({ cellData }) => {+ if (!cellData) return <div className="p-2"></div>;++ const date = new Date(cellData);+ const formatted = date.toLocaleString();++ return <div className="p-2 text-neutral-400">{formatted}</div>;+ };++ // Header renderer for all columns+ const headerRenderer = ({ label }) => {+ return <div className="font-medium p-2">{label}</div>;+ };++ // Function to scroll to top+ const scrollToTop = () => {+ if (gridRef.current) {+ gridRef.current.scrollToPosition({ scrollTop: 0 });++ // Apply new logs to the main logs array+ if (newLogsRef.current.length > 0) {+ setLogs(prevLogs => {+ // Create a new array with new logs at the beginning+ const updatedLogs = [...newLogsRef.current, ...prevLogs];+ // Reset new logs reference+ newLogsRef.current = [];+ return updatedLogs;+ });++ // Update total count+ setTotalCount(prev => prev + newLogsRef.current.length);+ }++ setIsAtTop(true);+ setLogCountAtScroll(0); // Reset the log count at scroll+ }+ };++ // Handle scroll events to detect if at top and capture log count+ const handleScroll = ({ scrollTop }) => {+ const wasAtTop = isAtTop;+ setIsAtTop(scrollTop === 0);++ // If we just started scrolling, capture the current log count+ if (wasAtTop && scrollTop > 0) {+ setLogCountAtScroll(totalCount);+ }++ // If scrolled back to top, apply new logs and reset counter+ if (scrollTop === 0 && newLogsRef.current.length > 0) {+ // Apply new logs to the main logs array+ setLogs(prevLogs => {+ // Create a new array with new logs at the beginning+ const updatedLogs = [...newLogsRef.current, ...prevLogs];+ // Reset new logs reference+ newLogsRef.current = [];+ return updatedLogs;+ });++ // Update total count+ setTotalCount(prev => prev + newLogsRef.current.length);+ setLogCountAtScroll(0); // Reset the log count at scroll+ }+ };++ // Load initial data when component mounts+ useEffect(() => {+ const loadInitialData = async () => {+ try {+ console.log('Loading initial log data');+ setIsLoading(true);+ setError(null);++ // Query Supabase for the first page of logs+ const { data, error, count } = await supabase+ .from(TABLE_NAME)+ .select('*', { count: 'exact' })+ .order('created_at', { ascending: false })+ .limit(PAGE_SIZE);++ if (error) throw error;++ console.log(\`Loaded \${data?.length || 0} initial logs, total count: \${count}\`);++ // Update total count if we got it+ if (count !== null) {+ setTotalCount(count);+ }++ // Set the initial logs+ setLogs(data || []);+ } catch (err) {+ console.error('Error loading initial logs:', err);+ setError(err.message);+ } finally {+ setIsLoading(false);+ }+ };++ loadInitialData();+ }, []);++ // Subscribe to real-time updates+ useEffect(() => {+ // Set up the channel for real-time updates+ const channel = supabase+ .channel('logs', { config: { private: true } })+ .on('broadcast', { event: 'INSERT' }, (payload) => {+ console.log('New log entry received:', payload);++ // If we're at the top, add the new log to the beginning of the list+ if (isAtTop) {+ setLogs(prevLogs => [payload.payload.record, ...prevLogs]);+ setTotalCount(prev => prev + 1);+ } else {+ // Otherwise, store it in the newLogsRef and increment the counter+ newLogsRef.current = [payload.payload.record, ...newLogsRef.current];+ setTotalCount(prev => prev + 1);+ }+ })+ .subscribe(status => console.log("status:", status));++ console.log('Real-time subscription set up successfully');++ return () => {+ console.log('Cleaning up real-time subscription');+ channel.unsubscribe();+ };+ }, []); // Only run once on mount++ // Add a separate effect to handle isAtTop changes+ useEffect(() => {+ console.log('isAtTop changed:', isAtTop);++ // If we're back at the top and have new logs, apply them+ if (isAtTop && newLogsRef.current.length > 0) {+ console.log('Applying new logs at top:', newLogsRef.current.length);++ setLogs(prevLogs => {+ // Create a new array with new logs at the beginning+ const updatedLogs = [...newLogsRef.current, ...prevLogs];+ // Reset new logs reference+ newLogsRef.current = [];+ return updatedLogs;+ });++ // Update total count and reset counter+ setTotalCount(prev => prev + newLogsRef.current.length);+ setLogCountAtScroll(0); // Reset the log count at scroll+ }+ }, [isAtTop]);++ // Save grid reference when table is rendered+ const onTableRendered = useCallback(({ registerChild }) => {+ return (ref) => {+ registerChild(ref);+ tableRef.current = ref;++ // Get the Grid component from the Table+ if (ref) {+ gridRef.current = ref.Grid;+ }+ };+ }, []);++ // Calculate if we should show the new logs notification+ const shouldShowNotification = !isAtTop && logCountAtScroll > 0 && totalCount > logCountAtScroll;++ return (+ <div className="text-sm flex flex-col h-screen bg-neutral-900 text-white relative antialiased">+ {/* Header */}+ <div className="flex justify-between items-center px-4 py-3 border-b border-neutral-800">+ <h1 className="font-medium">Log Viewer</h1>+ <div className="flex gap-4 items-center">+ {isLoading && <span className="text-neutral-400">Loading...</span>}+ <span className="text-neutral-500">Total Logs: {totalCount}</span>+ </div>+ </div>++ {/* Error message */}+ {error && (+ <div className="p-4 bg-red-500 text-white m-4 rounded">+ Error: {error}+ </div>+ )}++ {/* New logs badge */}+ {shouldShowNotification && (+ <div+ className="text-xs fixed top-24 left-1/2 transform -translate-x-1/2 bg-neutral-700 text-white px-4 py-2 rounded-full font-medium shadow-lg cursor-pointer z-50 hover:bg-neutral-600 flex items-center justify-center"+ onClick={scrollToTop}+ >+ {totalCount - logCountAtScroll} new log{totalCount - logCountAtScroll === 1 ? '' : 's'}+ </div>+ )}++ {/* Main content */}+ <div className="flex-1 font-mono text-xs">+ <div className="h-full relative">+ <div className="h-32 w-full z-10 absolute left-0 right-0 bottom-0 bg-gradient-to-t from-neutral-900 to-transparent" />+ <AutoSizer>+ {({ width, height }) => (+ <InfiniteLoader+ isRowLoaded={isRowLoaded}+ loadMoreRows={loadMoreRows}+ rowCount={totalCount}+ minimumBatchSize={PAGE_SIZE}+ threshold={20}+ >+ {({ onRowsRendered, registerChild }) => (+ <Table+ ref={onTableRendered({ registerChild })}+ width={width}+ height={height}+ headerHeight={40}+ rowHeight={48}+ rowCount={totalCount}+ rowGetter={({ index }) => logs[index] || {}}+ onRowsRendered={onRowsRendered}+ onScroll={handleScroll}+ overscanRowCount={10}+ className="w-full"+ headerClassName="text-xs uppercase text-neutral-500"+ gridClassName="w-full"+ rowClassName="border-b border-neutral-800 hover:bg-neutral-800 w-full"+ >+ <Column+ label="ID"+ dataKey="id"+ width={100}+ cellDataGetter={cellDataGetter}+ cellRenderer={idCellRenderer}+ headerRenderer={headerRenderer}+ />+ <Column+ label="Message"+ dataKey="log_message"+ flexGrow={1}+ width={400}+ cellDataGetter={cellDataGetter}+ cellRenderer={messageCellRenderer}+ headerRenderer={headerRenderer}+ />+ <Column+ label="Level"+ dataKey="log_level"+ cellDataGetter={cellDataGetter}+ cellRenderer={levelCellRenderer}+ headerRenderer={headerRenderer}+ />+ <Column+ label="Timestamp"+ dataKey="created_at"+ cellDataGetter={cellDataGetter}+ cellRenderer={timestampCellRenderer}+ headerRenderer={headerRenderer}+ />+ </Table>+ )}+ </InfiniteLoader>+ )}+ </AutoSizer>+ </div>+ </div>+ </div>+ );+}`++const logViewerFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: logViewerFiles,+ dependencies: {+ 'react-virtualized': 'latest',+ },+ title: 'Log Viewer',+ description:+ "A real-time log viewer that uses Supabase Realtime's broadcast channel to stream and display log entries as they occur across multiple instances.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/platformer-3d-example.tsx b/apps/www/components/Realtime/examples/platformer-3d-example.tsxnew file mode 100644index 00000000000..3653a346992--- /dev/null+++ b/apps/www/components/Realtime/examples/platformer-3d-example.tsx@@ -0,0 +1,1067 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import { Canvas, useFrame } from '@react-three/fiber';+import { Physics, useBox, usePlane } from '@react-three/cannon';+import { OrbitControls } from '@react-three/drei';+import { Vector3, MathUtils } from 'three';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'platformer-3d-example-${instanceId}';++// Game constants+const MOVE_SPEED = 5;+const GROUND_MOVE_SPEED = 10; // Increased movement speed on ground+const JUMP_FORCE = 8; // Strong jump force+const PLAYER_SIZE = [1, 1, 1]; // Width, height, depth+const GRAVITY = -12; // Stronger gravity for more responsive falling+const BROADCAST_THROTTLE = 50; // ms between broadcasts (20 updates per second)+const INTERPOLATION_SPEED = 15; // Higher values = faster interpolation+const PROJECTILE_SPEED = 12; // Reduced speed for better collision detection+const PROJECTILE_SIZE = 0.2; // Smaller projectile size+const SHOOT_COOLDOWN = 500; // Cooldown between shots in ms+const COLLISION_OFFSET = 0.05; // Small offset to prevent clipping+const GROUND_CHECK_THRESHOLD = 0.3; // Threshold for ground detection++// Character colors - vibrant neon colors+const COLORS = [+ '#ff00ff', // Neon pink+ '#00ffff', // Neon cyan+ '#ffff00', // Neon yellow+ '#00ff00', // Neon green+ '#ff9900', // Neon orange+ '#ff0099' // Neon magenta+];++// Spawn positions - safe places to teleport to+const SPAWN_POSITIONS = [+ [0, 1, 0], // Above ground+ [-3, 2, 0], // Above left platform+ [3, 3, 0], // Above right platform+ [0, 4, 0] // Above center platform+];++export default function App() {+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [players, setPlayers] = useState([]);+ const [localPlayer, setLocalPlayer] = useState(null);+ const [projectiles, setProjectiles] = useState([]);+ const [gameOverMessage, setGameOverMessage] = useState('');++ const userId = useRef(Math.random().toString(36).substring(2, 15));+ const channelRef = useRef(null);+ const keysPressed = useRef({});+ const lastShootTime = useRef(0);+ const canShoot = useRef(true);+ const isGameOver = useRef(false);++ // Use a ref to track the current localPlayer state to avoid closure issues+ const localPlayerRef = useRef(null);++ // Keep the ref in sync with the state+ useEffect(() => {+ localPlayerRef.current = localPlayer;+ }, [localPlayer]);++ // Initialize game+ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Assign a random color+ const playerColor = COLORS[Math.floor(Math.random() * COLORS.length)];++ // Create initial player state+ const initialPlayerState = {+ id: userId.current,+ username: randomName,+ position: [Math.random() * 8 - 4, 5, 0], // Higher Y position (5 instead of 3)+ color: playerColor,+ lastUpdated: Date.now(),+ isAlive: true,+ direction: [1, 0, 0] // Default direction (facing right)+ };++ setLocalPlayer(initialPlayerState);+ localPlayerRef.current = initialPlayerState; // Also set the ref directly++ // Set up Supabase channel+ const channel = supabase.channel(CHANNEL, {+ config: {+ presence: {+ key: userId.current,+ },+ },+ });++ channelRef.current = channel;++ // Handle presence for player list+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const presenceList = [];++ // Convert presence state to array+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presenceList.push(...presences);+ });++ // Update players list, but keep local player's state+ setPlayers(prevPlayers => {+ const updatedPlayers = presenceList.map(presence => {+ // If this is our local player, use our local state+ if (presence.id === userId.current) {+ return localPlayerRef.current || presence;+ }++ // For other players, find their previous state or use presence data+ const existingPlayer = prevPlayers.find(p => p.id === presence.id);++ if (existingPlayer) {+ // If player already exists, keep their interpolation data+ return {+ ...existingPlayer,+ // Update any new properties from presence+ ...presence,+ // But keep position and interpolation data+ position: existingPlayer.position,+ currentPosition: existingPlayer.currentPosition,+ targetPosition: existingPlayer.targetPosition,+ interpolating: existingPlayer.interpolating+ };+ } else {+ // For new players, initialize interpolation data+ return {+ ...presence,+ // Add interpolation properties+ currentPosition: [...presence.position],+ targetPosition: [...presence.position],+ interpolating: false,+ isAlive: presence.isAlive !== false, // Default to alive if not specified+ direction: presence.direction || [1, 0, 0] // Default direction+ };+ }+ });++ return updatedPlayers;+ });+ });++ // Handle player position updates+ channel.on('broadcast', { event: 'player_update' }, (payload) => {+ const updatedPlayer = payload.payload;++ // Don't update our own player (we manage that locally)+ if (updatedPlayer.id === userId.current) return;++ // Update the player in our list+ setPlayers(prevPlayers => {+ return prevPlayers.map(player => {+ if (player.id === updatedPlayer.id) {+ // Only update if the incoming data is newer+ if (!player.lastUpdated || updatedPlayer.lastUpdated > player.lastUpdated) {+ // Calculate distance between current and new position+ const currentPos = player.position || [0, 0, 0];+ const newPos = updatedPlayer.position;+ const distance = Math.sqrt(+ Math.pow(newPos[0] - currentPos[0], 2) ++ Math.pow(newPos[1] - currentPos[1], 2) ++ Math.pow(newPos[2] - currentPos[2], 2)+ );++ // For large position changes (teleports), skip interpolation+ const skipInterpolation = distance > 10;++ return {+ ...player,+ // Update direction+ direction: updatedPlayer.direction || player.direction,+ // Update alive status+ isAlive: updatedPlayer.isAlive !== undefined ? updatedPlayer.isAlive : player.isAlive,+ // If skipping interpolation, directly set position+ ...(skipInterpolation ? {+ position: [...newPos],+ currentPosition: [...newPos],+ targetPosition: [...newPos],+ interpolating: false+ } : {+ // Keep the current position for interpolation+ currentPosition: player.currentPosition || player.position,+ // Set the new target position+ targetPosition: newPos,+ // Update the canonical position+ position: player.position,+ // Mark as interpolating+ interpolating: true+ }),+ // Update timestamp+ lastUpdated: updatedPlayer.lastUpdated+ };+ }+ }+ return player;+ });+ });+ });++ // Handle projectile creation+ channel.on('broadcast', { event: 'projectile_fired' }, (payload) => {+ const projectileData = payload.payload;++ // Don't process our own projectiles (we already added them)+ if (projectileData.ownerId === userId.current) return;++ // Add the projectile to our list+ setProjectiles(prev => {+ return [+ ...prev,+ {+ ...projectileData,+ position: [...projectileData.position],+ createdAt: Date.now()+ }+ ];+ });+ });++ // Handle player hit events+ channel.on('broadcast', { event: 'player_hit' }, (payload) => {+ const hitData = payload.payload;++ // If we were hit+ if (hitData.playerId === userId.current) {+ // Show game over message+ setGameOverMessage(\`You were eliminated by \${hitData.shooterName}!\`);+ isGameOver.current = true;++ // Update our local player state+ setLocalPlayer(prev => {+ const updated = {+ ...prev,+ isAlive: false+ };+ localPlayerRef.current = updated; // Update ref too+ return updated;+ });++ // After 3 seconds, respawn+ setTimeout(() => {+ respawnPlayer();+ }, 3000);+ }++ // Update the hit player in our list+ setPlayers(prevPlayers => {+ return prevPlayers.map(player => {+ if (player.id === hitData.playerId) {+ return {+ ...player,+ isAlive: false+ };+ }+ return player;+ });+ });+ });++ // Subscribe to channel+ channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track(initialPlayerState);+ setIsConnected(true);+ }+ });++ // Set up keyboard event listeners+ window.addEventListener('keydown', handleKeyDown);+ window.addEventListener('keyup', handleKeyUp);++ // Clean up+ return () => {+ window.removeEventListener('keydown', handleKeyDown);+ window.removeEventListener('keyup', handleKeyUp);++ if (channel) {+ channel.unsubscribe();+ }+ };+ }, []);++ // Broadcast player position when it changes+ useEffect(() => {+ if (!localPlayer || !channelRef.current || !isConnected) return;++ // Broadcast our updated position+ channelRef.current.send({+ type: 'broadcast',+ event: 'player_update',+ payload: localPlayer+ });++ // Update our presence data+ channelRef.current.track(localPlayer);++ }, [localPlayer, isConnected]);++ // Periodic position broadcast to ensure consistency+ useEffect(() => {+ if (!localPlayer || !channelRef.current || !isConnected) return;++ // Broadcast position every 2 seconds regardless of movement+ const interval = setInterval(() => {+ // Update timestamp for the broadcast+ const updatedPlayer = {+ ...localPlayer,+ lastUpdated: Date.now()+ };++ // Broadcast position+ channelRef.current.send({+ type: 'broadcast',+ event: 'player_update',+ payload: updatedPlayer+ });++ // Update presence data+ channelRef.current.track(updatedPlayer);+ }, 2000);++ return () => clearInterval(interval);+ }, [localPlayer, isConnected]);++ // Handle key down events+ const handleKeyDown = (e) => {+ // Prevent default behavior for arrow keys and WASD to disable scrolling+ if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'KeyW', 'KeyS', 'KeyA', 'KeyD'].includes(e.code)) {+ e.preventDefault();+ }++ // Simply update the keysPressed object+ keysPressed.current[e.code] = true;++ // Shoot when Enter is pressed+ if (e.code === 'Enter' || e.code === 'NumpadEnter') {+ if (canShoot.current && !isGameOver.current && localPlayerRef.current?.isAlive !== false) {+ shootProjectile();+ }+ }+ };++ // Handle key up events+ const handleKeyUp = (e) => {+ keysPressed.current[e.code] = false;+ };++ // Function to shoot a projectile+ const shootProjectile = () => {+ // Use the ref instead of the state+ const player = localPlayerRef.current;++ if (!player) {+ return;+ }++ const now = Date.now();++ // Check cooldown+ if (now - lastShootTime.current < SHOOT_COOLDOWN) {+ return;+ }++ lastShootTime.current = now;+ canShoot.current = false;++ // Reset cooldown after delay+ setTimeout(() => {+ canShoot.current = true;+ }, SHOOT_COOLDOWN);++ // Create projectile data with better positioning+ const projectileData = {+ id: \`\${userId.current}-\${now}\`,+ ownerId: userId.current,+ ownerName: player.username,+ position: [+ player.position[0] + player.direction[0] * 1.0, // Increased offset from player+ player.position[1] + 0.5, // Slightly above center+ player.position[2] + player.direction[2] * 1.0+ ],+ direction: [...player.direction],+ color: player.color,+ createdAt: now+ };++ try {+ // Add to local projectiles+ setProjectiles(prev => {+ const newProjectiles = [...prev, projectileData];+ return newProjectiles;+ });++ // Broadcast projectile creation+ channelRef.current.send({+ type: 'broadcast',+ event: 'projectile_fired',+ payload: projectileData+ });+ } catch (error) {+ console.error('Error creating projectile:', error);+ }+ };++ // Function to handle player hit+ const handlePlayerHit = (playerId, shooterId, shooterName) => {+ // Don't process hits for dead players+ const hitPlayer = players.find(p => p.id === playerId);+ if (!hitPlayer || hitPlayer.isAlive === false) return;++ // Broadcast hit+ channelRef.current.send({+ type: 'broadcast',+ event: 'player_hit',+ payload: {+ playerId,+ shooterId,+ shooterName+ }+ });++ // If we hit someone else+ if (playerId !== userId.current && shooterId === userId.current) {+ // Show elimination message+ setGameOverMessage(\`You eliminated \${hitPlayer.username}!\`);++ // Clear message after 3 seconds+ setTimeout(() => {+ setGameOverMessage('');+ }, 3000);+ }+ };++ // Function to respawn player+ const respawnPlayer = () => {+ if (!localPlayerRef.current) return;++ // Get a random spawn position+ const spawnPos = SPAWN_POSITIONS[Math.floor(Math.random() * SPAWN_POSITIONS.length)];++ // Update local player position and state+ setLocalPlayer(prev => {+ if (!prev) return prev;++ const updated = {+ ...prev,+ position: [...spawnPos],+ isAlive: true,+ lastUpdated: Date.now()+ };++ // Update ref too+ localPlayerRef.current = updated;++ return updated;+ });++ // Clear game over message+ setGameOverMessage('');+ isGameOver.current = false;+ };++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-neutral-300 font-sans">+ {/* Toolbar */}+ <div className="flex gap-2 flex-wrap absolute top-4 right-4 z-10">+ {players.map((user, index) => (+ <div+ key={index}+ className={\`flex items-center gap-2 px-3 py-1.5 rounded-full bg-neutral-800 text-xs\`}+ >+ <div className={\`w-1 h-1 rounded-full \${+ user.isAlive === false ? 'bg-neutral-500' : 'bg-green-400'+ }\`}></div>+ <span>{user.username}</span>+ </div>+ ))}+ </div>++ {/* Main content */}+ <div className="flex-1 relative overflow-hidden">+ <Canvas shadows camera={{ position: [0, 4.5, 8], fov: 80 }}>+ <color attach="background" args={['#000000']} />+ <fog attach="fog" args={['#000000', 15, 25]} />++ {/* Three-point lighting setup */}+ <ambientLight intensity={0.5} />++ {/* Key light - main light source */}+ <directionalLight+ color="#ffc9f9"+ intensity={1.5}+ position={[-5, 8, 5]}+ castShadow+ shadow-mapSize-width={2048}+ shadow-mapSize-height={2048}+ />++ {/* Fill light - fills in shadows */}+ <directionalLight+ color="#bdefff"+ intensity={0.8}+ position={[5, 5, 3]}+ castShadow={false}+ />++ {/* Rim light - creates separation */}+ <directionalLight+ color="#ffffff"+ intensity={0.6}+ position={[0, 6, -2]}+ castShadow={false}+ />++ {/* Additional spot light for dramatic effect */}+ <spotLight+ position={[0, 15, 0]}+ angle={0.3}+ penumbra={0.8}+ intensity={1}+ castShadow+ shadow-mapSize-width={2048}+ shadow-mapSize-height={2048}+ />++ <Physics gravity={[0, GRAVITY, 0]}>+ {/* Ground */}+ <Ground position={[0, -0.5, 0]} />++ {/* Platforms */}+ <Platform position={[-3, 1, 0]} size={[2, 0.5, 2]} />+ <Platform position={[3, 2, 0]} size={[2, 0.5, 2]} />+ <Platform position={[0, 3, 0]} size={[2, 0.5, 2]} />++ {/* Players */}+ {players.map((player) => (+ <Player+ key={player.id}+ player={player}+ isLocal={player.id === userId.current}+ keysPressed={keysPressed.current}+ setLocalPlayer={setLocalPlayer}+ />+ ))}+ </Physics>++ {/* Projectiles - now managed by ProjectileManager */}+ {projectiles.length > 0 && (+ <ProjectileManager+ projectiles={projectiles}+ setProjectiles={setProjectiles}+ players={players}+ handlePlayerHit={handlePlayerHit}+ />+ )}++ {/* Interpolation manager - handles smooth transitions for remote players */}+ <InterpolationManager+ players={players}+ setPlayers={setPlayers}+ localPlayerId={userId.current}+ />++ <OrbitControls+ enableZoom={false}+ enablePan={false}+ enableRotate={true}+ target={[0, 0, 0]}+ maxPolarAngle={Math.PI / 2}+ />+ </Canvas>++ {/* Game over message */}+ {gameOverMessage && (+ <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-black/80 text-neutral-300 px-8 py-6 rounded-lg font-bold text-2xl text-center border border-neutral-700">+ {gameOverMessage}+ </div>+ )}+ </div>+ </div>+ );+}++// Projectile component - simplified version without physics+function Projectile({ position, color }) {+ // Add ref to track mounting+ const ref = useRef();++ return (+ <mesh+ position={position}+ castShadow+ ref={ref}+ >+ <sphereGeometry args={[PROJECTILE_SIZE]} />+ <meshStandardMaterial+ color="#ffffff"+ emissive={color || "#ffffff"}+ emissiveIntensity={2.5}+ metalness={0.9}+ roughness={0.1}+ />+ </mesh>+ );+}++// ProjectileManager component - handles all projectile updates in one place+function ProjectileManager({ projectiles, setProjectiles, players, handlePlayerHit }) {+ // Store hit status for projectiles+ const hitProjectiles = useRef(new Set());++ // Use useFrame for smooth animation that's separate from React's render cycle+ useFrame((state, delta) => {+ if (projectiles.length === 0) return;++ // First, let's handle movement separately from collision detection+ setProjectiles(prev => {+ // Skip processing if nothing to update+ if (prev.length === 0) return prev;++ // Move projectiles+ const updatedProjectiles = prev.map(projectile => {+ // Skip already hit projectiles+ if (hitProjectiles.current.has(projectile.id)) return projectile;++ // Calculate new position+ const newPosition = [+ projectile.position[0] + projectile.direction[0] * PROJECTILE_SPEED * delta,+ projectile.position[1] - 0.02, // Reduced gravity effect+ projectile.position[2] + projectile.direction[2] * PROJECTILE_SPEED * delta+ ];++ return {+ ...projectile,+ position: newPosition+ };+ });++ // Only update if something changed+ return updatedProjectiles;+ });++ // Now handle collisions as a separate process+ // This prevents complex state updates and race conditions+ const currentProjectiles = projectiles.filter(p => !hitProjectiles.current.has(p.id));+ const alivePlayers = players.filter(p => p.isAlive !== false);++ // Process collisions+ currentProjectiles.forEach(projectile => {+ // Skip already hit projectiles+ if (hitProjectiles.current.has(projectile.id)) return;++ // Skip projectiles from dead players+ const owner = players.find(p => p.id === projectile.ownerId);+ if (owner && owner.isAlive === false) {+ hitProjectiles.current.add(projectile.id);+ return;+ }++ // Check collision with each alive player+ for (const player of alivePlayers) {+ // Skip collision with projectile owner+ if (player.id === projectile.ownerId) continue;++ // Use a simpler and more generous collision detection+ // Increase collision radius for better hit detection+ const collisionRadius = PLAYER_SIZE[0] * 0.6 + PROJECTILE_SIZE * 1.5;++ // Calculate distance between projectile and player+ const dx = projectile.position[0] - player.position[0];+ const dy = projectile.position[1] - player.position[1];+ const dz = projectile.position[2] - player.position[2];+ const distance = Math.sqrt(dx*dx + dy*dy + dz*dz);++ // If collision detected+ if (distance < collisionRadius) {+ // Mark this projectile as hit+ hitProjectiles.current.add(projectile.id);+ // Handle hit+ handlePlayerHit(player.id, projectile.ownerId, projectile.ownerName);+ // Break the loop since this projectile hit someone+ break;+ }+ }+ });++ // Remove old projectiles and hit projectiles+ setProjectiles(prev => {+ const now = Date.now();+ // Remove projectiles that are:+ // 1. Older than 5 seconds+ // 2. Have hit something+ return prev.filter(p =>+ now - p.createdAt < 5000 && !hitProjectiles.current.has(p.id)+ );+ });+ });++ // Render all projectiles+ return (+ <>+ {projectiles.map((projectile) => (+ <Projectile+ key={projectile.id}+ position={projectile.position}+ color={projectile.color}+ />+ ))}+ </>+ );+}++// Interpolation manager component - must be inside Canvas+function InterpolationManager({ players, setPlayers, localPlayerId }) {+ // Track last update time for each player+ const lastUpdateTimes = useRef({});++ // Run on every frame+ useFrame((state, delta) => {+ // Skip if no players+ if (players.length === 0) return;++ const now = Date.now();++ // Update players with interpolation+ setPlayers(prevPlayers => {+ // Check if any players need interpolation+ let needsUpdate = false;++ const updatedPlayers = prevPlayers.map(player => {+ // Skip local player+ if (player.id === localPlayerId) return player;++ // Skip if not interpolating+ if (!player.interpolating) return player;++ // Update last activity time+ lastUpdateTimes.current[player.id] = now;++ // Calculate interpolation step (faster for bigger distances)+ const distance = Math.sqrt(+ Math.pow(player.targetPosition[0] - player.currentPosition[0], 2) ++ Math.pow(player.targetPosition[1] - player.currentPosition[1], 2) ++ Math.pow(player.targetPosition[2] - player.currentPosition[2], 2)+ );++ // Adaptive interpolation speed based on distance+ const adaptiveSpeed = INTERPOLATION_SPEED * (1 + Math.min(distance, 5));+ const lerpAmount = Math.min(adaptiveSpeed * delta, 1);++ // Create new interpolated position+ const newPosition = [+ MathUtils.lerp(player.currentPosition[0], player.targetPosition[0], lerpAmount),+ MathUtils.lerp(player.currentPosition[1], player.targetPosition[1], lerpAmount),+ MathUtils.lerp(player.currentPosition[2], player.targetPosition[2], lerpAmount)+ ];++ // Check if we've reached the target+ const reachedTarget =+ Math.abs(newPosition[0] - player.targetPosition[0]) < 0.01 &&+ Math.abs(newPosition[1] - player.targetPosition[1]) < 0.01 &&+ Math.abs(newPosition[2] - player.targetPosition[2]) < 0.01;++ if (reachedTarget) {+ // We've reached the target, stop interpolating+ return {+ ...player,+ position: [...player.targetPosition],+ currentPosition: [...player.targetPosition],+ interpolating: false+ };+ } else {+ // Still interpolating+ needsUpdate = true;+ return {+ ...player,+ position: newPosition,+ currentPosition: newPosition+ };+ }+ });++ // Only update state if something changed+ return needsUpdate ? updatedPlayers : prevPlayers;+ });+ });++ // This component doesn't render anything+ return null;+}++// Ground component+function Ground(props) {+ const [ref] = usePlane(() => ({+ rotation: [-Math.PI / 2, 0, 0],+ ...props,+ type: 'Static',+ material: {+ friction: 0.05, // Low friction for smooth movement+ restitution: 0.0 // No bounce+ }+ }));++ return (+ <mesh ref={ref} receiveShadow>+ <planeGeometry args={[20, 20, 50, 50]} />+ <meshStandardMaterial+ color="#444444"+ metalness={0.4}+ roughness={0.5}+ emissive="#222222"+ emissiveIntensity={0.2}+ />+ </mesh>+ );+}++// Platform component+function Platform({ position, size }) {+ // Add a tiny offset to the platform size to prevent clipping+ const adjustedSize = [+ size[0] + COLLISION_OFFSET,+ size[1] + COLLISION_OFFSET,+ size[2] + COLLISION_OFFSET+ ];++ const [ref] = useBox(() => ({+ position,+ args: adjustedSize, // Use the adjusted size for physics+ type: 'Static',+ material: {+ friction: 0.05, // Low friction for smooth movement+ restitution: 0.0 // No bounce+ }+ }));++ return (+ <mesh ref={ref} castShadow receiveShadow>+ <boxGeometry args={size} />+ <meshStandardMaterial+ color="#666666"+ metalness={0.6}+ roughness={0.3}+ emissive="#333333"+ emissiveIntensity={0.4}+ />+ </mesh>+ );+}++// Player component+function Player({ player, isLocal, keysPressed, setLocalPlayer }) {+ // Adjust the physics body size to be slightly smaller than visual representation+ const physicsSize = [+ PLAYER_SIZE[0] - COLLISION_OFFSET,+ PLAYER_SIZE[1] - COLLISION_OFFSET,+ PLAYER_SIZE[2] - COLLISION_OFFSET+ ];++ // Use physics for local player, but not for remote players+ const [ref, api] = useBox(() => ({+ mass: isLocal ? 1 : 0, // No physics for remote players+ position: player.position,+ args: physicsSize, // Smaller collision box+ allowSleep: false,+ fixedRotation: true,+ type: isLocal ? 'Dynamic' : 'Kinematic', // Kinematic for remote players+ linearDamping: 0.1, // Reduced damping+ material: {+ friction: 0.05, // Low friction+ restitution: 0.1 // Low bounciness+ }+ }));++ const isJumping = useRef(false);+ const positionRef = useRef(player.position);+ const velocityRef = useRef([0, 0, 0]);+ const lastBroadcastRef = useRef(Date.now());+ const lastPositionRef = useRef(player.position);+ const directionRef = useRef(player.direction || [1, 0, 0]);+ const isOnGroundRef = useRef(false);++ // For remote players, directly update position from props+ useEffect(() => {+ if (!isLocal) {+ api.position.set(...player.position);+ positionRef.current = player.position;+ }+ }, [player.position, isLocal, api.position]);++ // Subscribe to position changes+ useEffect(() => {+ const unsubscribe = api.position.subscribe((p) => {+ positionRef.current = p;++ // Only update local player position+ if (isLocal) {+ const now = Date.now();++ // Update player direction based on movement+ if (keysPressed['ArrowLeft'] || keysPressed['KeyA']) {+ directionRef.current = [-1, 0, 0]; // Left+ } else if (keysPressed['ArrowRight'] || keysPressed['KeyD']) {+ directionRef.current = [1, 0, 0]; // Right+ }++ // Update position in state if it changed significantly+ if (now - lastBroadcastRef.current > BROADCAST_THROTTLE) {+ lastBroadcastRef.current = now;++ setLocalPlayer(prev => {+ if (!prev) return prev;++ return {+ ...prev,+ position: [p[0], p[1], p[2]],+ direction: directionRef.current,+ lastUpdated: now+ };+ });+ }+ }+ });++ return () => {+ unsubscribe();+ };+ }, [api, isLocal, setLocalPlayer, keysPressed]);++ // Handle controls for local player+ useEffect(() => {+ if (!isLocal || player.isAlive === false) return;++ // Track velocity and ground state+ const velocityUnsubscribe = api.velocity.subscribe((velocity) => {+ velocityRef.current = velocity;++ // Simple ground detection+ isOnGroundRef.current = Math.abs(velocity[1]) < GROUND_CHECK_THRESHOLD;++ // Allow jumping again when on ground+ if (isOnGroundRef.current) {+ isJumping.current = false;+ }+ });++ // Main game update loop+ const interval = setInterval(() => {+ const velocity = velocityRef.current || [0, 0, 0];++ // Movement speed+ const moveSpeed = isOnGroundRef.current ? GROUND_MOVE_SPEED : MOVE_SPEED;++ // Left/Right movement+ if (keysPressed['ArrowLeft'] || keysPressed['KeyA']) {+ api.velocity.set(-moveSpeed, velocity[1], velocity[2]);+ directionRef.current = [-1, 0, 0];+ }+ else if (keysPressed['ArrowRight'] || keysPressed['KeyD']) {+ api.velocity.set(moveSpeed, velocity[1], velocity[2]);+ directionRef.current = [1, 0, 0];+ }+ else {+ // Apply friction+ api.velocity.set(velocity[0] * 0.8, velocity[1], velocity[2]);+ }++ // Jumping - only if on ground and not already jumping+ if ((keysPressed['ArrowUp'] || keysPressed['KeyW'])+ && isOnGroundRef.current+ && !isJumping.current) {+ api.velocity.set(velocity[0], JUMP_FORCE, velocity[2]);+ isJumping.current = true;+ }+ }, 10);++ return () => {+ clearInterval(interval);+ velocityUnsubscribe();+ };+ }, [api, isLocal, player.isAlive, keysPressed]);++ // Apply visual effects for dead players+ const playerColor = player.isAlive === false ? '#333333' : player.color;+ const playerOpacity = player.isAlive === false ? 0.3 : 1;++ return (+ <group>+ {/* Player cube */}+ <mesh ref={ref} castShadow receiveShadow>+ <boxGeometry args={PLAYER_SIZE} />+ <meshStandardMaterial+ color={playerColor}+ transparent={player.isAlive === false}+ opacity={playerOpacity}+ metalness={0.5}+ roughness={0.4}+ emissive={player.isAlive ? playerColor : "#000000"}+ emissiveIntensity={0.3}+ />+ </mesh>++ </group>+ );+}`++const platformer3DFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */++/* Game-specific styles that can't be handled by Tailwind */+canvas {+ width: 100%;+ height: 100%;+}++.game-over-message {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ z-index: 100;+}+`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: platformer3DFiles,+ dependencies: {+ three: 'latest',+ '@react-three/fiber': 'latest',+ '@react-three/drei': 'latest',+ '@react-three/cannon': 'latest',+ },+ title: '3D Platformer Example',+ description:+ 'An immersive 3D multiplayer platformer game where players navigate a physics-based environment, collect coins, and interact with each other. This advanced example demonstrates real-time position synchronization, 3D physics with jumping and collision detection, projectile shooting mechanics, and player presence with usernames. Built with Three.js and React Three Fiber, it showcases sophisticated game development concepts including interpolated movement, optimized network updates, and responsive controls in a 3D space.',+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/presence-example.tsx b/apps/www/components/Realtime/examples/presence-example.tsxnew file mode 100644index 00000000000..bb5e1ef748c--- /dev/null+++ b/apps/www/components/Realtime/examples/presence-example.tsx@@ -0,0 +1,115 @@+'use client'++import type { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Generate a random user ID and avatar+const userId = Math.random().toString(36).substring(2, 15);+const getAvatarUrl = (id) => \`https://api.dicebear.com/7.x/avataaars/svg?seed=\${id}\`;++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'presence-example-${instanceId}';++export default function App() {+ const [onlineUsers, setOnlineUsers] = useState([]);+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);++ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Subscribe to presence channel+ const channel = supabase.channel(CHANNEL);++ // Track presence state+ channel+ .on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const presenceList = [];++ // Convert presence state to array+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presenceList.push(...presences);+ });++ setOnlineUsers(presenceList);+ })+ .subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Send presence state when subscribed+ await channel.track({+ user_id: userId,+ username: randomName,+ avatar: getAvatarUrl(userId),+ online_at: new Date().getTime(),+ });+ setIsConnected(true);+ }+ });++ return () => {+ // Clean up subscription+ channel.unsubscribe();+ };+ }, []);++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-white antialiased">+ {/* Main content */}+ <div className="flex-1 overflow-hidden p-4">+ <div className="h-full max-w-3xl mx-auto flex flex-col gap-4 items-center justify-center">+ <h2 className="text-lg font-medium text-neutral-300 mb-6">+ Online Users ({onlineUsers.length})+ </h2>+ <div className="flex justify-center sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-6">+ {onlineUsers.map((user) => (+ <div+ key={user.user_id}+ className="flex flex-col items-center gap-3"+ >+ <div className="relative w-16 h-16 rounded-full bg-gradient-to-b from-neutral-700 to-neutral-800 shadow-neutral-900/75 shadow-[inset_0_0_20px_rgba(0,0,0,0.3)]">+ <div className="absolute bottom-0 right-0 w-2 h-2 bg-green-400 rounded-full"></div>+ </div>+ <span className="text-sm text-neutral-400 text-center break-words">+ {user.username}+ </span>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ );+}`++const presenceFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: presenceFiles,+ title: 'Presence',+ description:+ "A demonstration of Supabase Realtime's presence feature that tracks and displays online users in real-time with their avatars and usernames.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/tic-tac-toe-example.tsx b/apps/www/components/Realtime/examples/tic-tac-toe-example.tsxnew file mode 100644index 00000000000..86099171369--- /dev/null+++ b/apps/www/components/Realtime/examples/tic-tac-toe-example.tsx@@ -0,0 +1,347 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import { X, Circle } from 'lucide-react';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'tictactoe-example-${instanceId}';++export default function App() {+ // Game state+ const [board, setBoard] = useState(Array(9).fill(null));+ const [isXNext, setIsXNext] = useState(true);+ const [winner, setWinner] = useState(null);++ // Player state+ const [playerSymbol, setPlayerSymbol] = useState(null);+ const [players, setPlayers] = useState([]);+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);++ // Refs+ const userId = useRef(Math.random().toString(36).substring(2, 15));+ const channelRef = useRef(null);++ // Initialize game+ useEffect(() => {+ console.log('Initializing game...');++ // Generate random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Create and subscribe to channel+ const channel = supabase.channel(CHANNEL, {+ config: {+ presence: {+ key: userId.current,+ },+ },+ });++ channelRef.current = channel;++ // Handle presence changes+ channel.on('presence', { event: 'sync' }, () => {+ console.log('Presence sync event received');++ // Get current state of presence+ const state = channel.presenceState();+ console.log('Presence state:', state);++ // Convert to array of players+ const currentPlayers = [];+ Object.keys(state).forEach(key => {+ const presences = state[key];+ currentPlayers.push(...presences);+ });++ // Sort by join time+ currentPlayers.sort((a, b) => a.joined_at - b.joined_at);+ console.log('Current players:', currentPlayers);++ setPlayers(currentPlayers);++ // Assign symbols based on join order+ if (currentPlayers.length > 0) {+ if (currentPlayers[0].userId === userId.current) {+ console.log('You are player X');+ setPlayerSymbol('X');+ } else if (currentPlayers.length > 1 && currentPlayers[1].userId === userId.current) {+ console.log('You are player O');+ setPlayerSymbol('O');+ } else {+ console.log('You are a spectator');+ setPlayerSymbol(null);+ }+ }+ });++ // Handle game state updates+ channel.on('broadcast', { event: 'game_update' }, (payload) => {+ console.log('Game update received:', payload.payload);+ const { board: newBoard, isXNext: newIsXNext, winner: newWinner } = payload.payload;++ setBoard(newBoard);+ setIsXNext(newIsXNext);+ setWinner(newWinner);+ });++ // Handle game reset+ channel.on('broadcast', { event: 'game_reset' }, () => {+ console.log('Game reset received');+ setBoard(Array(9).fill(null));+ setIsXNext(true);+ setWinner(null);+ });++ // Subscribe to channel+ channel.subscribe(async (status) => {+ console.log('Channel status:', status);++ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track({+ userId: userId.current,+ username: randomName,+ joined_at: new Date().getTime()+ });++ setIsConnected(true);+ console.log('Connected to channel');+ }+ });++ // Cleanup on unmount+ return () => {+ console.log('Cleaning up...');+ channel.unsubscribe();+ };+ }, []);++ // Handle square click+ const handleClick = (index) => {+ // Don't allow moves if:+ // - Not connected+ // - Square already filled+ // - Not player's turn+ // - Game already has a winner+ if (+ !isConnected ||+ board[index] ||+ (isXNext && playerSymbol !== 'X') ||+ (!isXNext && playerSymbol !== 'O') ||+ winner+ ) {+ return;+ }++ console.log('Handling click on square', index);++ const newBoard = [...board];+ newBoard[index] = isXNext ? 'X' : 'O';++ // Check for winner+ const newWinner = calculateWinner(newBoard);++ // Update local state immediately+ setBoard(newBoard);+ setIsXNext(!isXNext);++ if (newWinner) {+ setWinner(newWinner);+ }++ // Broadcast move+ channelRef.current.send({+ type: 'broadcast',+ event: 'game_update',+ payload: {+ board: newBoard,+ isXNext: !isXNext,+ winner: newWinner+ }+ });++ console.log('Move broadcast sent');+ };++ // Reset game+ const resetGame = () => {+ console.log('Resetting game...');++ // Reset local state+ setBoard(Array(9).fill(null));+ setIsXNext(true);+ setWinner(null);++ // Broadcast reset+ channelRef.current.send({+ type: 'broadcast',+ event: 'game_reset',+ payload: {}+ });++ console.log('Reset broadcast sent');+ };++ // Calculate winner+ const calculateWinner = (squares) => {+ const lines = [+ [0, 1, 2],+ [3, 4, 5],+ [6, 7, 8],+ [0, 3, 6],+ [1, 4, 7],+ [2, 5, 8],+ [0, 4, 8],+ [2, 4, 6]+ ];++ for (let i = 0; i < lines.length; i++) {+ const [a, b, c] = lines[i];+ if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {+ return squares[a];+ }+ }++ return null;+ };++ // Get game status message+ const getStatusMessage = () => {+ if (winner) {+ return \`Winner: \${winner}\`;+ } else if (board.every(square => square !== null)) {+ return 'Draw!';+ } else if (players.length < 2) {+ return 'Waiting for another player...';+ } else {+ return \`Next player: \${isXNext ? 'X' : 'O'}\${+ ((isXNext && playerSymbol === 'X') || (!isXNext && playerSymbol === 'O'))+ ? ' (Your turn)'+ : ''+ }\`;+ }+ };++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-white antialiased">+ {/* Main content */}+ <div className="flex-1 overflow-hidden p-4 max-w-2xl mx-auto flex flex-col items-center justify-center">+ <div className="max-w-lg mx-auto flex flex-col items-center">+ {/* Players */}+ <div className="flex gap-2 mb-4 w-full">+ {players.map((player, index) => (+ <div+ key={player.userId}+ className={\`+ flex flex-1 items-center justify-center gap-2 px-4 py-2+ \${(isXNext && index === 0) || (!isXNext && index === 1)+ ? 'bg-neutral-700'+ : 'bg-neutral-800'+ }+ rounded-md w-full text-neutral-300 text-sm transition-all+ \`}+ >+ <span className="truncate">{player.userId === userId.current ? 'You' : player.username}</span>+ <span className={\`\${index === 0 ? 'text-blue-400' : 'text-red-400'}\`}>+ {index === 0 ? (+ <X className="w-4 h-4" />+ ) : (+ <Circle className="w-4 h-4" />+ )}+ </span>+ </div>+ ))}+ </div>++ {/* Game status - only show winner or draw */}+ {(winner || board.every(square => square !== null)) && (+ <div className="mb-6 text-neutral-300 text-lg font-medium">+ {winner ? \`Winner: \${winner}\` : 'Draw!'}+ </div>+ )}++ {/* Game board */}+ <div className="grid grid-cols-3 gap-2 overflow-hidden rounded-lg">+ {board.map((square, index) => (+ <button+ key={index}+ onClick={() => handleClick(index)}+ className={\`+ w-20 h-20 flex items-center justify-center text-4xl font-bold+ bg-neutral-800 hover:bg-neutral-700+ border border-neutral-700+ \${+ ((isXNext && playerSymbol === 'X') || (!isXNext && playerSymbol === 'O')) &&+ !square &&+ !winner+ ? 'cursor-pointer'+ : 'cursor-not-allowed'+ }+ \${square === 'X' ? 'text-blue-400' : square === 'O' ? 'text-red-400' : 'text-neutral-700'}+ \${index === 0 ? 'rounded-tl-lg' : ''}+ \${index === 2 ? 'rounded-tr-lg' : ''}+ \${index === 6 ? 'rounded-bl-lg' : ''}+ \${index === 8 ? 'rounded-br-lg' : ''}+ \`}+ disabled={+ !isConnected ||+ !!square ||+ (isXNext && playerSymbol !== 'X') ||+ (!isXNext && playerSymbol !== 'O') ||+ !!winner+ }+ >+ {square === 'X' ? (+ <X className="w-12 h-12" />+ ) : square === 'O' ? (+ <Circle className="w-12 h-12" />+ ) : null}+ </button>+ ))}+ </div>++ {/* Reset button */}+ <button+ onClick={resetGame}+ className="px-6 mt-4 w-full py-2 bg-neutral-800 hover:bg-neutral-600 text-neutral-100 rounded-md transition-colors"+ >+ Reset Game+ </button>+ </div>+ </div>+ </div>+ );+}`++const ticTacToeFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: ticTacToeFiles,+ title: 'Tic Tac Toe',+ description:+ "A multiplayer Tic Tac Toe game that uses Supabase Realtime's broadcast and presence features to synchronize game state and player turns between opponents.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/todo-example.tsx b/apps/www/components/Realtime/examples/todo-example.tsxnew file mode 100644index 00000000000..9f97423c726--- /dev/null+++ b/apps/www/components/Realtime/examples/todo-example.tsx@@ -0,0 +1,347 @@+'use client'++import type { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Generate a unique instance ID for this session+const instanceId = '${instanceId}';++// Channel name for the todos in this instance+const CHANNEL = \`todos:\${instanceId}\`;+const TABLE = 'todos';++export default function App() {+ const [todos, setTodos] = useState([]);+ const [newTodo, setNewTodo] = useState('');+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [onlineUsers, setOnlineUsers] = useState([]);+ const [user, setUser] = useState(null);+ const [isLoading, setIsLoading] = useState(true);++ // Sign in anonymously and store instanceId in user metadata+ useEffect(() => {+ const signInAnonymously = async () => {+ try {+ const { data, error } = await supabase.auth.signInAnonymously({+ options: {+ data: { instanceId }+ }+ });++ if (error) {+ console.error('Error signing in anonymously:', error.message);+ return;+ }++ setUser(data.user);+ console.log('Signed in anonymously with user ID:', data.user.id);+ } catch (error) {+ console.error('Unexpected error during sign in:', error.message);+ }+ };++ signInAnonymously();+ }, []);++ // Fetch todos from the database when user is authenticated+ useEffect(() => {+ if (!user) return;++ const fetchTodos = async () => {+ try {+ const { data, error } = await supabase+ .from(TABLE)+ .select('*')+ .eq('channel', instanceId)++ if (error) {+ console.error('Error fetching todos:', error.message);+ return;+ }++ setTodos(data || []);+ setIsLoading(false);+ } catch (error) {+ console.error('Unexpected error fetching todos:', error.message);+ }+ };++ fetchTodos();++ const setupRealtimeChannel = async () => {+ await supabase.realtime.setAuth(); // Needed for Realtime Authorization+ const changes = supabase+ .channel(CHANNEL, {+ config: { private: true },+ })+ .on('broadcast', { event: 'INSERT' }, (payload) => {+ const { record: todo } = payload.payload;+ setTodos(prev => [...prev, todo]);+ })+ .on('broadcast', { event: 'UPDATE' }, (payload) => {+ const { record: todo } = payload.payload;+ setTodos(prev =>+ prev.map(t => t.id === todo.id ? todo : t)+ );+ })+ .on('broadcast', { event: 'DELETE' }, (payload) => {+ console.log('DELETE', payload);+ const { old_record: todo } = payload.payload;+ setTodos(prev => prev.filter(t => t.id !== todo.id));+ })+ .subscribe();+ };+ setupRealtimeChannel();++ }, [user, instanceId]);++ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Subscribe to presence channel+ const presenceChannel = supabase.channel(\`presence:\${instanceId}\`);++ // Track presence state+ presenceChannel.on('presence', { event: 'sync' }, () => {+ const state = presenceChannel.presenceState();+ const presenceList = [];++ // Convert presence state to array+ Object.keys(state).forEach(key => {+ const presences = state[key];+ presenceList.push(...presences);+ });++ setOnlineUsers(presenceList);+ });++ presenceChannel+ .subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await presenceChannel.track({+ user_id: user?.id || 'anonymous',+ username: randomName,+ online_at: new Date().getTime(),+ });+ setIsConnected(true);+ }+ });++ return () => {+ presenceChannel.unsubscribe();+ };+ }, [user?.id, instanceId]);++ const handleAddTodo = async (e) => {+ e.preventDefault();+ if (!newTodo.trim() || !isConnected || !user) return;++ try {+ // Insert the todo into the Supabase table+ // The database trigger will handle broadcasting+ const { error } = await supabase+ .from(TABLE)+ .insert({+ text: newTodo.trim(),+ completed: false,+ created_by: user.id,+ channel: instanceId+ });++ if (error) {+ console.error('Error adding todo:', error.message);+ return;+ }++ // Clear the input+ setNewTodo('');+ } catch (error) {+ console.error('Unexpected error adding todo:', error.message);+ }+ };++ const handleToggleTodo = async (todo) => {+ if (!isConnected || !user) return;++ try {+ // Update the todo in the database+ // The database trigger will handle broadcasting+ const { error } = await supabase+ .from(TABLE)+ .update({ completed: !todo.completed })+ .eq('id', todo.id)+ .eq('channel', instanceId);++ if (error) {+ console.error('Error updating todo:', error.message);+ }+ } catch (error) {+ console.error('Unexpected error updating todo:', error.message);+ }+ };++ const handleDeleteTodo = async (todo) => {+ if (!isConnected || !user) return;++ try {+ // Delete the todo from the database+ // The database trigger will handle broadcasting+ const { error } = await supabase+ .from(TABLE)+ .delete()+ .eq('id', todo.id)++ if (error) {+ console.error('Error deleting todo:', error.message);+ }+ } catch (error) {+ console.error('Unexpected error deleting todo:', error.message);+ }+ };++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-white antialiased">+ {/* Header */}+ <div className="flex justify-between items-center px-5 pt-3">+ <h1 className="font-medium text-sm text-neutral-400">+ {user ?+ \`\${todos.filter((todo) => !todo.completed).length} todos to complete\` :+ 'Connecting...'+ }+ </h1>+ <div className="flex gap-2 flex-wrap">+ {onlineUsers.map((user, index) => (+ <div+ key={index}+ className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-neutral-800 text-neutral-300 text-xs"+ >+ <div className="w-2 h-2 rounded-full bg-green-400"></div>+ <span>{user.username}</span>+ </div>+ ))}+ </div>+ </div>++ {/* Main content */}+ <div className="flex-1 overflow-hidden p-4">+ <div className="mx-auto">+ <div className="space-y-1">+ {isLoading ? (+ <div className="text-center py-8 text-neutral-500">+ Loading todos...+ </div>+ ) : (+ todos.map((todo) => (+ <div+ key={todo.id}+ className="flex items-center justify-between p-3 rounded-md bg-neutral-800 border border-neutral-700"+ >+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleToggleTodo(todo)}+ className={\`w-5 h-5 rounded flex items-center justify-center border \${+ todo.completed+ ? 'bg-green-900 border-green-700 text-green-400'+ : 'border-neutral-600'+ }\`}+ >+ {todo.completed && (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <polyline points="20 6 9 17 4 12"></polyline>+ </svg>+ )}+ </button>+ <span className={\`text-sm \${todo.completed ? 'line-through text-neutral-500' : 'text-neutral-200'}\`}>+ {todo.text}+ </span>+ </div>++ <button+ onClick={() => handleDeleteTodo(todo)}+ className="text-neutral-500 hover:text-neutral-300 transition-colors"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <line x1="18" y1="6" x2="6" y2="18"></line>+ <line x1="6" y1="6" x2="18" y2="18"></line>+ </svg>+ </button>+ </div>+ ))+ )}+ </div>++ <form onSubmit={handleAddTodo} className="mt-4 flex gap-2">+ <input+ type="text"+ value={newTodo}+ onChange={(e) => setNewTodo(e.target.value)}+ placeholder="Add a new todo..."+ disabled={!isConnected || !user}+ className="flex-1 px-4 py-2 bg-neutral-800 text-neutral-100 border border-neutral-700 rounded-md focus:outline-none focus:ring-2 focus:ring-neutral-600 focus:border-transparent placeholder-neutral-500"+ />+ <button+ type="submit"+ disabled={!newTodo.trim() || !isConnected || !user}+ className="px-4 py-2 bg-neutral-800 text-neutral-300 border border-neutral-700 rounded-md hover:bg-neutral-700 focus:outline-none disabled:opacity-50 disabled:hover:bg-neutral-800"+ >+ Add+ </button>+ </form>+ </div>+ </div>+ </div>+ );+}`++const todoFiles = {+ '/App.js': appJsCode,+ '/styles.css': `/* No custom CSS needed - using Tailwind */`,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: todoFiles,+ title: 'Todo List',+ description:+ "A collaborative todo list application that lets multiple users manage tasks in real-time. Features include adding, completing, and deleting tasks, all synchronized instantly across devices. This example showcases real-time database changes and presence indicators showing who's online.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/examples/whiteboard-example.tsx b/apps/www/components/Realtime/examples/whiteboard-example.tsxnew file mode 100644index 00000000000..3291a2dc180--- /dev/null+++ b/apps/www/components/Realtime/examples/whiteboard-example.tsx@@ -0,0 +1,419 @@+'use client'++import { ExampleLayoutProps } from '../example-layout'++const instanceId = Math.random().toString(36).substring(2, 9)++const appJsCode = `import { useEffect, useState, useRef } from 'react';+import './styles.css';+import { createClient } from '@supabase/supabase-js';+import { Trash2 } from "lucide-react";++// Initialize Supabase client+const supabaseUrl = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_URL}';+const supabaseKey = '${process.env.NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY}';+const supabase = createClient(supabaseUrl, supabaseKey);++// Channel name - using a unique ID to ensure both instances connect to the same channel+const CHANNEL = 'whiteboard-example-${instanceId}';++export default function App() {+ const [username, setUsername] = useState('');+ const [isConnected, setIsConnected] = useState(false);+ const [activeUsers, setActiveUsers] = useState([]);+ const [isDrawing, setIsDrawing] = useState(false);+ const [currentColor, setCurrentColor] = useState('#3ecf8e');++ const canvasRef = useRef(null);+ const contextRef = useRef(null);+ const userId = useRef(Math.random().toString(36).substring(2, 15));+ const isInitialSetup = useRef(true);+ const pointsBuffer = useRef([]);+ const batchTimerRef = useRef(null);+ const channelRef = useRef(null);+ const currentPathRef = useRef([]);++ // Initialize canvas and context+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;++ // Set canvas dimensions to match container+ const setupCanvas = () => {+ const container = canvas.parentElement;+ if (!container) return;++ // Get the actual dimensions of the container+ const { width, height } = container.getBoundingClientRect();++ // Set canvas dimensions to match container (with pixel density scaling)+ canvas.width = width * 2;+ canvas.height = height * 2;+ canvas.style.width = \`\${width}px\`;+ canvas.style.height = \`\${height}px\`;++ // Get and configure context+ const context = canvas.getContext('2d');+ context.scale(2, 2);+ context.lineCap = 'round';+ context.lineJoin = 'round';+ context.lineWidth = 5;+ context.strokeStyle = currentColor;+ contextRef.current = context;++ // Only clear canvas on initial setup+ if (isInitialSetup.current) {+ context.fillStyle = 'rgba(0,0,0,0)'; // bg-neutral-900+ context.fillRect(0, 0, canvas.width, canvas.height);+ isInitialSetup.current = false;+ }+ };++ // Initial setup+ setupCanvas();++ // Create ResizeObserver to handle container size changes+ const resizeObserver = new ResizeObserver(() => {+ setupCanvas();+ });++ // Observe the container element+ const container = canvas.parentElement;+ if (container) {+ resizeObserver.observe(container);+ }++ // Handle window resize as well+ window.addEventListener('resize', setupCanvas);++ return () => {+ // Clean up observers and event listeners+ resizeObserver.disconnect();+ window.removeEventListener('resize', setupCanvas);+ // Clear any pending batch timer+ if (batchTimerRef.current) {+ clearTimeout(batchTimerRef.current);+ }+ };+ }, []);++ // Update stroke color when currentColor changes+ useEffect(() => {+ if (contextRef.current) {+ contextRef.current.strokeStyle = currentColor;+ }+ }, [currentColor]);++ // Function to send batched points+ const sendBatchedPoints = () => {+ if (pointsBuffer.current.length === 0) return;++ // Send the batch of points+ channelRef.current.send({+ type: 'broadcast',+ event: 'draw_batch',+ payload: {+ userId: userId.current,+ points: [...pointsBuffer.current],+ color: currentColor+ }+ });++ // Clear the buffer+ pointsBuffer.current = [];+ };++ // Set up Supabase channel+ useEffect(() => {+ // Generate a random username+ const adjectives = ['Happy', 'Clever', 'Brave', 'Bright', 'Kind'];+ const nouns = ['Panda', 'Tiger', 'Eagle', 'Dolphin', 'Fox'];+ const randomName = \`\${adjectives[Math.floor(Math.random() * adjectives.length)]}\${+ nouns[Math.floor(Math.random() * nouns.length)]+ }\${Math.floor(Math.random() * 100)}\`;+ setUsername(randomName);++ // Subscribe to channel+ const channel = supabase.channel(CHANNEL);+ channelRef.current = channel;++ // Handle presence for user list+ channel.on('presence', { event: 'sync' }, () => {+ const state = channel.presenceState();+ const users = [];++ Object.keys(state).forEach(key => {+ const presences = state[key];+ users.push(...presences);+ });++ setActiveUsers(users);+ });++ // Handle batched drawing events+ channel.on('broadcast', { event: 'draw_batch' }, (payload) => {+ if (payload.payload.userId === userId.current) return;++ const { points, color } = payload.payload;+ const context = contextRef.current;++ if (!context || points.length === 0) return;++ // Save current stroke style+ const currentStrokeStyle = context.strokeStyle;++ // Set stroke style for this drawing operation+ context.strokeStyle = color;++ let isNewPath = true;++ // Process each point based on its type+ for (let i = 0; i < points.length; i++) {+ const point = points[i];++ if (point.type === 'start' || isNewPath) {+ // Start a new path+ context.beginPath();+ context.moveTo(point.x, point.y);+ isNewPath = false;+ } else if (point.type === 'move') {+ // Continue the path+ context.lineTo(point.x, point.y);+ context.stroke();+ }+ }++ // Restore previous stroke style+ context.strokeStyle = currentStrokeStyle;+ });++ // Handle individual drawing events (legacy support)+ channel.on('broadcast', { event: 'draw' }, (payload) => {+ if (payload.payload.userId === userId.current) return;++ const { x, y, type, color } = payload.payload;+ const context = contextRef.current;++ if (!context) return;++ // Save current stroke style+ const currentStrokeStyle = context.strokeStyle;++ // Set stroke style for this drawing operation+ context.strokeStyle = color;++ if (type === 'start') {+ context.beginPath();+ context.moveTo(x, y);+ } else if (type === 'move') {+ context.lineTo(x, y);+ context.stroke();+ }++ // Restore previous stroke style+ context.strokeStyle = currentStrokeStyle;+ });++ // Handle clear canvas event+ channel.on('broadcast', { event: 'clear' }, () => {+ const canvas = canvasRef.current;+ const context = contextRef.current;++ if (!context || !canvas) return;++ context.clearRect(0, 0, canvas.width, canvas.height);+ });++ // Subscribe to channel+ channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ // Track presence+ await channel.track({+ user_id: userId.current,+ username: randomName,+ online_at: new Date().getTime()+ });++ setIsConnected(true);+ }+ });++ return () => {+ channel.unsubscribe();+ };+ }, []);++ // Drawing handlers+ const startDrawing = ({ nativeEvent }) => {+ const { offsetX, offsetY } = nativeEvent;++ // Start a new path in the canvas+ contextRef.current.beginPath();+ contextRef.current.moveTo(offsetX, offsetY);+ setIsDrawing(true);++ // Reset the current path+ currentPathRef.current = [{ type: 'start', x: offsetX, y: offsetY }];++ // Add to buffer for batched sending with type information+ pointsBuffer.current.push({ type: 'start', x: offsetX, y: offsetY });++ // Start the batch timer if not already started+ if (!batchTimerRef.current) {+ batchTimerRef.current = setInterval(sendBatchedPoints, 10); // Send every 10ms for more frequent updates+ }++ // For backward compatibility, also send individual start event+ channelRef.current.send({+ type: 'broadcast',+ event: 'draw',+ payload: {+ userId: userId.current,+ type: 'start',+ x: offsetX,+ y: offsetY,+ color: currentColor+ }+ });+ };++ const draw = ({ nativeEvent }) => {+ if (!isDrawing) return;++ const { offsetX, offsetY } = nativeEvent;++ // Draw on local canvas+ contextRef.current.lineTo(offsetX, offsetY);+ contextRef.current.stroke();++ // Add to buffer for batched sending with type information+ pointsBuffer.current.push({ type: 'move', x: offsetX, y: offsetY });++ // For backward compatibility, also send individual move event+ // Send every point for maximum smoothness+ channelRef.current.send({+ type: 'broadcast',+ event: 'draw',+ payload: {+ userId: userId.current,+ type: 'move',+ x: offsetX,+ y: offsetY,+ color: currentColor+ }+ });++ // Add to current path+ currentPathRef.current.push({ type: 'move', x: offsetX, y: offsetY });+ };++ const stopDrawing = () => {+ contextRef.current.closePath();+ setIsDrawing(false);++ // Send any remaining points+ sendBatchedPoints();++ // Clear the batch timer+ if (batchTimerRef.current) {+ clearInterval(batchTimerRef.current);+ batchTimerRef.current = null;+ }++ // Reset current path+ currentPathRef.current = [];+ };++ const clearCanvas = () => {+ const canvas = canvasRef.current;+ const context = contextRef.current;++ // Clear the entire canvas+ context.clearRect(0, 0, canvas.width, canvas.height);++ // Broadcast clear event+ channelRef.current.send({+ type: 'broadcast',+ event: 'clear',+ payload: {+ userId: userId.current+ }+ });+ };++ // Color selection+ const colors = ['#3ecf8e', '#f43f5e', '#60a5fa', '#a78bfa', '#ffffff'];++ const selectColor = (color) => {+ setCurrentColor(color);+ };++ return (+ <div className="flex flex-col h-screen bg-neutral-900 text-white antialiased">+ {/* Toolbar */}+ <div className="flex items-center gap-4 absolute top-4 right-4">+ <button+ onClick={clearCanvas}+ className="p-2 hover:bg-neutral-700 text-neutral-400 hover:text-white rounded-full transition-colors"+ title="Clear Canvas"+ >+ <Trash2 strokeWidth={1.5} size={16} />+ </button>+ <div className="flex gap-2">+ {colors.map((color) => (+ <div+ key={color}+ className={\`w-6 h-6 rounded-full cursor-pointer border-2 \${+ color === currentColor ? 'border-neutral-300' : 'border-transparent'+ } hover:scale-110 transition-transform\`}+ style={{ backgroundColor: color }}+ onClick={() => selectColor(color)}+ />+ ))}+ </div>++ <div className="flex gap-2 flex-wrap">+ {activeUsers.map((user, index) => (+ <div+ key={index}+ className="flex items-center gap-2 w-8 h-8 rounded-full bg-neutral-800 text-neutral-200 text-sm font-medium"+ title={user.username}+ >+ <div className="w-full h-full rounded-full flex items-center justify-center text-xs">+ {user.username[0].toUpperCase()}+ </div>+ </div>+ ))}+ </div>+ </div>++ {/* Main content */}+ <div className="flex-1 h-full overflow-hidden">+ <div className="w-full h-full">+ <canvas+ ref={canvasRef}+ onMouseDown={startDrawing}+ onMouseMove={draw}+ onMouseUp={stopDrawing}+ onMouseLeave={stopDrawing}+ className="w-full h-full cursor-crosshair touch-none bg-neutral-900 shrink-0"+ />+ </div>+ </div>+ </div>+ );+}`++const whiteboardFiles = {+ '/App.js': appJsCode,+}++const layoutProps: ExampleLayoutProps = {+ appJsCode,+ files: whiteboardFiles,+ title: 'Whiteboard',+ description:+ "A collaborative whiteboard that uses Supabase Realtime's broadcast channel to synchronize drawing strokes and cursor positions between multiple users in real-time.",+}++export default layoutPropsdiff --git a/apps/www/components/Realtime/realtime-showcase.tsx b/apps/www/components/Realtime/realtime-showcase.tsxnew file mode 100644index 00000000000..7fae08c1cc0--- /dev/null+++ b/apps/www/components/Realtime/realtime-showcase.tsx@@ -0,0 +1,189 @@+'use client'++import presenceExample from './examples/presence-example'+import chatExample from './examples/chat-example'+import todoExample from './examples/todo-example'+import collaborativeEditorExample from './examples/collaborative-editor-example'+import whiteboardExample from './examples/whiteboard-example'+import ticTacToeExample from './examples/tic-tac-toe-example'+import emojiPickerExample from './examples/emoji-picker-example'+import platformer3DExample from './examples/platformer-3d-example'+import iframeAnnotationExample from './examples/iframe-annotation-example'+import logViewerExample from './examples/log-viewer-example'+import formPresenceExample from './examples/form-presence-example'+import cursorTrackingExample from './examples/cursor-tracking-example'+import { Tabs_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_ } from 'ui'+import {+ Users,+ MessageSquare,+ CheckSquare,+ Edit,+ PenTool,+ Hash,+ Smile,+ Gamepad2,+ StickyNote,+ FileText,+ ClipboardList,+ MousePointer,+} from 'lucide-react'+import { useState, useCallback } from 'react'+import ExampleLayout from './example-layout'++// Define the list of examples for easier navigation+const EXAMPLES = [+ {+ value: 'presence',+ label: 'Presence',+ icon: Users,+ props: presenceExample,+ },+ {+ value: 'chat',+ label: 'Chat',+ icon: MessageSquare,+ props: chatExample,+ },+ {+ value: 'todo',+ label: 'Todo List',+ icon: CheckSquare,+ props: todoExample,+ },+ {+ value: 'editor',+ label: 'Editor',+ icon: Edit,+ props: collaborativeEditorExample,+ },+ {+ value: 'formPresence',+ label: 'Form',+ icon: ClipboardList,+ props: formPresenceExample,+ },+ {+ value: 'cursorTracking',+ label: 'Cursor',+ icon: MousePointer,+ props: cursorTrackingExample,+ },+ {+ value: 'whiteboard',+ label: 'Whiteboard',+ icon: PenTool,+ props: whiteboardExample,+ },+ {+ value: 'tictactoe',+ label: 'XO',+ icon: Hash,+ props: ticTacToeExample,+ },+ {+ value: 'emoji',+ label: 'Reactions',+ icon: Smile,+ props: emojiPickerExample,+ },+ {+ value: 'platformer',+ label: 'Platformer',+ icon: Gamepad2,+ props: platformer3DExample,+ },+ {+ value: 'annotation',+ label: 'Annotation',+ icon: StickyNote,+ props: iframeAnnotationExample,+ },+ {+ value: 'logs',+ label: 'Logs',+ icon: FileText,+ props: logViewerExample,+ },+]++export default function RealtimeShowcase() {+ // Use numeric index for active tab+ const [activeTabIndex, setActiveTabIndex] = useState(0)++ const handleTabChange = (value: string) => {+ const index = EXAMPLES.findIndex((ex) => ex.value === value)+ if (index !== -1) {+ setActiveTabIndex(index)+ }+ }++ const handleNext = useCallback(() => {+ if (activeTabIndex < EXAMPLES.length - 1) {+ setActiveTabIndex(activeTabIndex + 1)+ }+ }, [activeTabIndex])++ const handlePrevious = useCallback(() => {+ if (activeTabIndex > 0) {+ setActiveTabIndex(activeTabIndex - 1)+ }+ }, [activeTabIndex])++ // Get the current example from the index+ const currentExample = EXAMPLES[activeTabIndex]++ return (+ <div className="bg-surface-75/50 border border-muted rounded-lg h-auto lg:h-[600px]">+ <Tabs_Shadcn_+ value={currentExample.value}+ onValueChange={handleTabChange}+ className="w-full h-full flex flex-col lg:flex-row border-b border-muted h-full items-stretch"+ >+ {/* Desktop sidebar tabs - hidden on mobile */}+ <div className="hidden lg:block w-48 px-6 py-8 border-r border-muted h-full">+ <h2 className="text-xs uppercase text-foreground-light font-mono mb-4">Examples</h2>+ <TabsList_Shadcn_ className="border-none flex flex-col h-auto justify-start items-stretch gap-2 bg-transparent">+ {EXAMPLES.map((example) => (+ <TabsTrigger_Shadcn_+ key={example.value}+ value={example.value}+ className="justify-start px-2 py-2 h-auto data-[state=active]:bg-transparent data-[state=active]:border-none border-none p-0 data-[state=active]:text-foreground"+ >+ <example.icon strokeWidth={1.5} size={16} className="mr-3" />+ {example.label}+ </TabsTrigger_Shadcn_>+ ))}+ </TabsList_Shadcn_>+ </div>++ {/* Mobile horizontal tabs - shown only on mobile */}+ <div className="lg:hidden px-2 py-2 border-b border-muted w-full overflow-x-auto">+ <TabsList_Shadcn_ className="border-none flex flex-row h-auto justify-start items-center gap-2 bg-transparent w-max">+ {EXAMPLES.map((example) => (+ <TabsTrigger_Shadcn_+ key={example.value}+ value={example.value}+ className="whitespace-nowrap justify-start px-3 py-2 h-auto data-[state=active]:bg-surface-100 data-[state=active]:border-none rounded-md"+ >+ <example.icon strokeWidth={1.5} size={14} className="mr-2" />+ {example.label}+ </TabsTrigger_Shadcn_>+ ))}+ </TabsList_Shadcn_>+ </div>++ {/* Tab Content - render ExampleLayout with props from current example */}+ <div className="flex-1 h-full overflow-hidden">+ <div className="mt-0 border-0 p-0 m-0 h-full overflow-hidden">+ <ExampleLayout+ key={currentExample.value}+ {...currentExample.props}+ onNext={activeTabIndex < EXAMPLES.length - 1 ? handleNext : undefined}+ onPrevious={activeTabIndex > 0 ? handlePrevious : undefined}+ />+ </div>+ </div>+ </Tabs_Shadcn_>+ </div>+ )+}diff --git a/apps/www/components/Realtime/sandpack-styles.css b/apps/www/components/Realtime/sandpack-styles.cssnew file mode 100644index 00000000000..48a59db6a4a--- /dev/null+++ b/apps/www/components/Realtime/sandpack-styles.css@@ -0,0 +1,47 @@+/* Make Sandpack take full height - with higher specificity */+html body .sp-wrapper {+ height: 100% !important;+ min-height: 100% !important;+}++html body .sp-layout {+ height: 100% !important;+ border: none !important;+ display: flex !important;+ flex-direction: column !important;+}++html body .sp-stack {+ height: 100% !important;+ flex: 1 !important;+}++/* Fix for Sandpack preview */+html body .sp-preview-container {+ height: 100% !important;+}++html body .sp-preview-iframe {+ height: 100% !important;+}++/* Fix for Sandpack editor */+html body .sp-editor {+ height: 100% !important;+ overflow: auto !important;+}++html body .cm-editor {+ height: 100% !important;+ overflow: auto !important;+}++/* Remove unnecessary borders */+html body .sp-tabs {+ border-bottom: none !important;+}++/* Fix for Sandpack layout when both components are rendered */+html body .sp-layout > div {+ flex: 1 !important;+}diff --git a/apps/www/components/Realtime/sandpack.tsx b/apps/www/components/Realtime/sandpack.tsxnew file mode 100644index 00000000000..e0ab9375a3c--- /dev/null+++ b/apps/www/components/Realtime/sandpack.tsx@@ -0,0 +1,55 @@+'use client'++import { SandpackProvider, SandpackLayout, SandpackPreview } from '@codesandbox/sandpack-react'+import './sandpack-styles.css' // Import custom Sandpack styles++type SandpackProps = {+ files: Record<string, string>+ dependencies?: Record<string, string>+}++export default function SandpackWrapper({ files, dependencies = {} }: SandpackProps) {+ // Ensure we have the required files for React template+ const completeFiles = {+ '/App.js': files['/App.js'] || files['App.js'] || '',+ '/styles.css': files['/styles.css'] || files['styles.css'] || '',+ ...files,+ }++ // Default dependencies+ const defaultDependencies = {+ '@supabase/supabase-js': 'latest',+ 'lucide-react': 'latest',+ }++ return (+ <div className="h-full w-full">+ <SandpackProvider+ template="react"+ files={completeFiles}+ customSetup={{+ dependencies: {+ ...defaultDependencies,+ ...dependencies,+ },+ }}+ options={{+ experimental_enableServiceWorker: true,+ visibleFiles: ['/App.js'],+ initMode: 'user-visible',+ activeFile: '/App.js',+ externalResources: ['https://cdn.tailwindcss.com'],+ }}+ >+ <SandpackLayout className="!h-full !min-h-full !border-none !bg-surface-50 !rounded-none !flex !flex-col">+ <SandpackPreview+ showNavigator={false}+ showRefreshButton={false}+ showOpenInCodeSandbox={false}+ className="!h-full !flex-1 !border-none"+ />+ </SandpackLayout>+ </SandpackProvider>+ </div>+ )+}diff --git a/apps/www/components/code-display.tsx b/apps/www/components/code-display.tsxnew file mode 100644index 00000000000..410d4bde791--- /dev/null+++ b/apps/www/components/code-display.tsx@@ -0,0 +1,23 @@+'use client'++import React from 'react'++type CodeDisplayProps = {+ code: string+ title?: string+}++export default function CodeDisplay({ code, title = 'Code' }: CodeDisplayProps) {+ return (+ <div className="h-full flex flex-col">+ <div className="bg-neutral-900 border-b border-neutral-700/50 text-neutral-400 text-xs py-2 px-4">+ {title}+ </div>+ <div className="bg-neutral-900 p-4 overflow-auto flex-1">+ <pre className="text-xs text-neutral-300 overflow-auto">+ <code>{code}</code>+ </pre>+ </div>+ </div>+ )+}diff --git a/apps/www/package.json b/apps/www/package.jsonindex ac242864784..2467c95216e 100644--- a/apps/www/package.json+++ b/apps/www/package.json@@ -18,6 +18,7 @@},"dependencies": {"@code-hike/mdx": "^0.9.0",+ "@codesandbox/sandpack-react": "^2.20.0","@hcaptcha/react-hcaptcha": "^1.11.1","@heroicons/react": "^1.0.6","@mdx-js/react": "^2.3.0",diff --git a/apps/www/pages/realtime.tsx b/apps/www/pages/realtime.tsxindex a659e4c77b8..8a75a9618c7 100644--- a/apps/www/pages/realtime.tsx+++ b/apps/www/pages/realtime.tsx@@ -1,5 +1,4 @@import ApiExamples from 'data/products/realtime/api-examples'-import AppExamples from 'data/products/realtime/app-examples'import MainProducts from '~/data/MainProducts'import { NextSeo } from 'next-seo'import Link from 'next/link'@@ -12,6 +11,7 @@ import ProductsNav from '~/components/Products/ProductsNav'import APISection from '~/components/Sections/APISection'import ProductHeader from '~/components/Sections/ProductHeader'import RealtimeStyles from '~/styles/realtime.module.css'+import RealtimeShowcase from '~/components/Realtime/realtime-showcase'import { Grid, Layers, Menu } from 'lucide-react'import { PRODUCT_NAMES } from 'shared-data/products'@@ -181,40 +181,15 @@ function RealtimePage() {</div></div></SectionContainer>-- <SectionContainer className="flex flex-col gap-8">- <div className="flex flex-col items-center justify-center">- <h2 className="h3">What you can build with Realtime</h2>- <p className="p mx-auto text-center lg:w-1/2">+ <SectionContainer className="!pb-0 !mb-0">+ <div className="mb-12 prose">+ <h3>What you can build with Realtime</h3>+ <p className="text-foreground-light mt-0">Build any kind of Realtime application with ease, including any of these scenarios.</p></div>- <div className="grid gap-10 grid-cols-2 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4">- {AppExamples.map((example) => {- return (- <>- <div className="flex flex-col gap-3">- <Image- alt={example.title}- src={{- light: `/images/realtime/example-apps/light/${example.img}?type=1`,- dark: `/images/realtime/example-apps/dark/${example.img}`,- }}- className="bg-surface-100 rounded-lg"- layout="fill"- objectFit="contain"- />- <div className="prose">- <h4>{example.title}</h4>- <p className="text-sm">{example.description}</p>- </div>- </div>- </>- )- })}- </div>+ <RealtimeShowcase /></SectionContainer>-<SectionContainer><APISectiontitle="Simple and convenient APIs"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8f37db7d3b4..998586693f3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -549,7 +549,7 @@ importers:version: 0.2.15'@graphiql/react':specifier: ^0.19.4- version: 0.19.4(@codemirror/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 0.19.4(@codemirror/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])'@graphiql/toolkit':specifier: ^0.9.1@@ -1179,6 +1179,9 @@ importers:'@code-hike/mdx':specifier: ^0.9.0version: 0.9.0([email protected])([email protected])+ '@codesandbox/sandpack-react':+ specifier: ^2.20.0'@hcaptcha/react-hcaptcha':specifier: ^1.11.1@@ -2662,8 +2665,26 @@ packages:peerDependencies:react: ^16.8.3 || ^17 || ^18- '@codemirror/[email protected]':- resolution: {integrity: sha512-rtjk5ifyMzOna1c7PBu7J1VCt0PvA5wy3o8eMVnxMKb7z8KA7JFecvD04dSn14vj/bBaAbqRsGed5OjtofEnLA==}+ '@codemirror/[email protected]':+ resolution: {integrity: sha512-PHHBXFomUs5DF+9tCOM/UoW6XQ4R44lLNNhRaW9PKPTU0D7lIjRg3ElxaJnTwsl/oHiR93WSXDBrekhoUGCPtg==}++ '@codemirror/[email protected]':+ resolution: {integrity: sha512-q8VPEFaEP4ikSlt6ZxjB3zW72+7osfAYW9i8Zu943uqbKuz6utc1+F170hyLUCUltXORjQXRyYQNfkckzA/bPQ==}++ '@codemirror/[email protected]':+ resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}++ '@codemirror/[email protected]':+ resolution: {integrity: sha512-aQv37pIMSlueybId/2PVSP6NPnmurFDVmZwzc7jszd2KAF8qd4VBbvNYPXWQq90WIARjsdVkPbw29pszmHws3Q==}++ '@codemirror/[email protected]':+ resolution: {integrity: sha512-8PR3vIWg7pSu7ur8A07pGiYHgy3hHj+mRYRCSG8q+mPIrl0F02rgpGv+DsQTHRTc30rydOsf5PZ7yjKFg2Ackw==}++ '@codemirror/[email protected]':+ resolution: {integrity: sha512-A7+f++LodNNc1wGgoRDTt78cOwWm9KVezApgjOMp1W4hM0898nsqBXwF+sbePE7ZRcjN7Sa1Z5m2oN27XkmEjQ==}++ '@codemirror/[email protected]':+ resolution: {integrity: sha512-u4q7PnZlJUojeRe8FJa/njJcMctISGgPQ4PnWsd9268R4ZTtU+tfFYmwkBvgcrK2+QQ8tYFVALVb5fVJykKc5A==}'@codemirror/[email protected]':resolution: {integrity: sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA==}@@ -2671,6 +2692,18 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-ZQ0V5ovw/miKEXTvjgzRyjnrk9TwriUB1k4R5p7uNnHR9Hus+D1SXHGdJshijEzPFjU25xea/7nhIeSqYFKdbA==}+ '@codesandbox/[email protected]':+ resolution: {integrity: sha512-2VRS6JDSk+M+pg56GA6CryyUSGPjBEe8Pnae0QL3jJF1mJZJVMDKr93gJRtBbLkfZN6LD/DwMtf+2L0bpWrjqg==}++ '@codesandbox/[email protected]':+ resolution: {integrity: sha512-CMV4nr1zgKzVpx4I3FYvGRM5YT0VaQhALMW9vy4wZRhEyWAtJITQIqZzrTGWqB1JvV7V72dVEUCUPLfYz5hgJQ==}++ '@codesandbox/[email protected]':+ resolution: {integrity: sha512-takd1YpW/PMQ6KPQfvseWLHWklJovGY8QYj8MtWnskGKbjOGJ6uZfyZbcJ6aCFLQMpNyjTqz9AKNbvhCOZ1TUQ==}+ peerDependencies:+ react: ^16.8.0 || ^17 || ^18 || ^19+ react-dom: ^16.8.0 || ^17 || ^18 || ^19+'@contentlayer2/[email protected]':resolution: {integrity: sha512-ZJ+Iiu2rVI50x60XoqnrsO/Q8eqFX5AlP1L0U/3ygaAas3tnOqTzQZ1UsxYQMpJzcLok24ddlhKfQKbCMUJPiQ==}@@ -3618,9 +3651,18 @@ packages:'@lezer/[email protected]':resolution: {integrity: sha512-w7ojc8ejBqr2REPsWxJjrMFsA/ysDCFICn8zEOR9mrqzOu2amhITYuLD8ag6XZf0CFXDrhKqw7+tW8cX66NaDA==}+ '@lezer/[email protected]':+ resolution: {integrity: sha512-V5/89eDapjeAkWPBpWEfQjZ1Hag3aYUUJOL8213X0dFRuXJ4BXa5NKl9USzOnaLod4AOpmVCkduir2oKwZYZtg==}+'@lezer/[email protected]':resolution: {integrity: sha512-Z5duk4RN/3zuVO7Jq0pGLJ3qynpxUVsh7IbUbGj88+uV2ApSAn6kWg2au3iJb+0Zi7kKtqffIESgNcRXWZWmSA==}+ '@lezer/[email protected]':+ resolution: {integrity: sha512-dqpT8nISx/p9Do3AchvYGV3qYc4/rKr3IBZxlHmpIKam56P47RSHkSF5f13Vu9hebS1jM0HmtJIwLbWz1VIY6w==}++ '@lezer/[email protected]':+ resolution: {integrity: sha512-lL+1fcuxWYPURMM/oFZLEDm0XuLN128QPV+VuGtKpeaOGdcl9F2LYC3nh1S9LkPqx9M0mndZFdXCipNAZpzIkQ==}+'@lezer/[email protected]':resolution: {integrity: sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA==}@@ -5225,6 +5267,16 @@ packages:'@react-dnd/[email protected]':resolution: {integrity: sha512-/RVXdLvJxLg4QKvMoM5WlwNR9ViO9z8B/qPcc+C0Sa/teJY7QG7kJ441DwzOjMYEY7GmU4dj5EcGHIkKZiQZCA==}+ '@react-hook/[email protected]':+ resolution: {integrity: sha512-mWU3BMkmmzyYMSuhO9wu3eJVP21N8TcgYm9bZnTrMwuM818bEk+0NRM3hP+c/TqA9Ln5C7qE53p1H0QMtzYdvQ==}+ peerDependencies:+ react: '>=16.8'++ '@react-hook/[email protected]':+ resolution: {integrity: sha512-IwEphTD75liO8g+6taS+4oqz+nnroocNfWVHWz7j+N+ZO2vYrc6PV1q7GQhuahL0IOR7JccFTsFKQ/mb6iZWAg==}+ peerDependencies:+ react: '>=16.8'+'@react-router/[email protected]':resolution: {integrity: sha512-z3++B3H6k/GyMoR05CUiy2ney5ZxFWJ8YLyVN8wBU2h4aVscqxxVoX9GyrMvjz81VPtrzf0S2iPTJ758ZVmEIg==}engines: {node: '>=20.0.0'}@@ -5940,6 +5992,9 @@ packages:'@speed-highlight/[email protected]':resolution: {integrity: sha512-0dxmVj4gxg3Jg879kvFS/msl4s9F3T9UXC1InxgOf7t5NvcPD97u/WTA5vL/IxWHMn7qSxBozqrnnE2wvl1m8g==}+ '@stitches/[email protected]':+ resolution: {integrity: sha512-Gfkvwk9o9kE9r9XNBmJRfV8zONvXThnm1tcuojL04Uy5uRyqg93DC83lDebl0rocZCfKSjUv+fWYtMQmEDJldg==}+'@stripe/[email protected]':resolution: {integrity: sha512-+JzYFgUivVD7koqYV7LmLlt9edDMAwKH7XhZAHFQMo7NeRC+6D2JmQGzp9tygWerzwttwFLlExGp4rAOvD6l9g==}peerDependencies:@@ -7141,6 +7196,9 @@ packages:resolution: {integrity: sha512-Ao95qWLpDPXXM+WrmwcKbl6uNlC5tjnowlaRYtuVDHHoygjtIPfDUoK9NthrlZsQSKjZXlmji2TrBUAVbiH0LQ==}+ resolution: {integrity: sha512-PMqBCBvrOVDRqLGooQb+z+t1Q0PiPyurUQeZRR5uHBOVZcW8B04KMmnT12USnhpNX2wCPagWzLVppQMUG3u0Dw==}+resolution: {integrity: sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==}@@ -7673,6 +7731,9 @@ packages:resolution: {integrity: sha512-CSbhY4cFEJRe6/GQzIk5qXZ4Jeg5pcsP7b5peFSDpffpe1cqjASH/n9UTjBwOp6XpMSTwQ8Za2K5V02ueA7Tmw==}+ resolution: {integrity: sha512-cA8uCj0qSoG9e0kevyOWXwPaELRPVg5Pxp6WskLMwerx257Zfnh8Nl0JBH59d7wQzij2CK7qEfJQK3RjuKKIug==}+resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==}engines: {node: '>=6'}@@ -7965,6 +8026,9 @@ packages:resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}+ resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}+resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==}engines: {node: '>=12.0.0'}@@ -8122,6 +8186,10 @@ packages:resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==}engines: {node: '>=12'}+ resolution: {integrity: sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}@@ -8572,9 +8640,20 @@ packages:resolution: {integrity: sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==}+ engines: {node: '>=0.10'}++ resolution: {integrity: sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==}+resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==}+ resolution: {integrity: sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==}engines: {node: '>=12'}@@ -8598,6 +8677,9 @@ packages:resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}engines: {node: '>=6'}+ resolution: {integrity: sha512-GwBr6yViW3ttx1kb7/Oh+gKQ1/TrhYwxKqVmg5gS+BK+Qe2KrOa/Vh7w3HPBvgGf0LfcDGoY9I6NHKoA5Hozhw==}+resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}@@ -8812,6 +8894,10 @@ packages:deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options.hasBin: true+ resolution: {integrity: sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==}+ engines: {node: '>=0.10'}+resolution: {integrity: sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}@@ -8884,6 +8970,9 @@ packages:resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==}+resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}engines: {node: '>=6'}@@ -8940,6 +9029,9 @@ packages:resolution: {integrity: sha512-xsZH6PXaER4XoV+NiT7JHp1bJodJVT+cxeSH1G0f0tlT0lJqYuHUP3bUx2HtfTDvOagMINYp8rsqusxud3RXhw==}+ resolution: {integrity: sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==}+resolution: {integrity: sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==}engines: {node: '>=0.10.0'}@@ -9786,6 +9878,9 @@ packages:resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}engines: {node: '>=12'}+ resolution: {integrity: sha512-fn4bQ0Xq8FTej09YC/jqKZwtijpvARlRp6wxL5WTA6yPe2YWSJ5RJh7Nm79rK2qB0wr6iDQzH60XGq5V/7u8YQ==}+resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==}@@ -11445,6 +11540,9 @@ packages:react: ^16.8 || ^17 || ^18react-dom: ^16.8 || ^17 || ^18+ resolution: {integrity: sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==}+resolution: {integrity: sha512-b81XSLihMwCfwiUVRRja3LphLo4uBBMZEzBBWMaISbKTwOmq3wPknIETy/8000tr7Gq4WmbuFYPS7jOYIf+ZJw==}engines: {node: '>=18.17.0'}@@ -11820,6 +11918,9 @@ packages:resolution: {integrity: sha512-ERAyNnZOfqM+Ao3RAvIXkYh5joP220yf59gVe2X/cI6SiCxIdi4c9HZKZD8R6q/RDXEje1THBju6iExiSsgJaQ==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+ resolution: {integrity: sha512-AlWY719RF02ujitly7Kk/0QlV+pXGFDHrHf9O2OKqyqgBieaPOIeuSkL8sRK6j2WK+/ZAURq2kZsY0d8JapUiw==}+resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==}@@ -12488,6 +12589,9 @@ packages:date-fns: ^2.28.0react: ^16.8.0 || ^17.0.0 || ^18.0.0+ resolution: {integrity: sha512-ES0GolSrKO8wsKbsEkVeiR/ZAaHQTY4zDh1UW8DImVmm8oaGLl3ijJDvSGe+qDRKPZdPRnDtWWnSvvrgxXdThQ==}+resolution: {integrity: sha512-Wu3dw5aDJmOGw8WjH1I1/yTH+vlXEL4vmjk5p+MHxP8HuHJS1lAGeIdG/hze1AvNeXWo/JgULV87LyQOr+r5jw==}@@ -13508,6 +13612,9 @@ packages:resolution: {integrity: sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==}+ resolution: {integrity: sha512-ZUyfgGDdFRbZGGJQ1YhiM930Yczz5VlbJObrQLlk24+qNHVQx4OlLcYswEUo3bIyNAbQUIUR9Yr5/Hqjzqb4zA==}+resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==}engines: {node: '>= 0.8'}@@ -13539,6 +13646,9 @@ packages:resolution: {integrity: sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==}+ resolution: {integrity: sha512-12KWeb+wixJohmnwNFerbyiBrAlq5qJLwIt38etRtKtmmHyDSoGlIqFE9wx+4IwG0aDjI7GV8tc8ZccjWZZtTg==}+resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==}@@ -14130,6 +14240,9 @@ packages:resolution: {integrity: sha512-G6zXWS1dLj6eagy6sVhOMQiLtJdxQBHIA9Z6HFUNLOlr6MFOgzV8wvmidtPONfPtEUv0uZsy77XJNzTAfwPDaA==}engines: {node: '>=16'}+ resolution: {integrity: sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==}+resolution: {integrity: sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==}engines: {node: '>= 0.4'}@@ -15942,7 +16055,51 @@ snapshots:transitivePeerDependencies:- encoding- '@codemirror/[email protected]':+ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/language': 6.11.0+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ '@lezer/common': 1.2.3++ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/language': 6.11.0+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ '@lezer/common': 1.2.3++ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/autocomplete': 6.18.6+ '@codemirror/language': 6.11.0+ '@codemirror/state': 6.5.2+ '@lezer/common': 1.2.3+ '@lezer/css': 1.1.10++ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/autocomplete': 6.18.6+ '@codemirror/lang-css': 6.3.1+ '@codemirror/lang-javascript': 6.2.3+ '@codemirror/language': 6.11.0+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ '@lezer/common': 1.2.3+ '@lezer/css': 1.1.10+ '@lezer/html': 1.3.10++ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/autocomplete': 6.18.6+ '@codemirror/language': 6.11.0+ '@codemirror/lint': 6.8.4+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ '@lezer/common': 1.2.3+ '@lezer/javascript': 1.4.21++ '@codemirror/[email protected]':dependencies:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.4@@ -15951,6 +16108,12 @@ snapshots:'@lezer/lr': 1.4.2style-mod: 4.1.2+ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ crelt: 1.0.6+'@codemirror/[email protected]':dependencies:'@marijn/find-cluster-break': 1.0.2@@ -15961,6 +16124,44 @@ snapshots:style-mod: 4.1.2w3c-keyname: 2.2.8+ '@codesandbox/[email protected]':+ dependencies:+ outvariant: 1.4.3+ strict-event-emitter: 0.4.6++ '@codesandbox/[email protected]':+ dependencies:+ '@codesandbox/nodebox': 0.1.8+ buffer: 6.0.3+ dequal: 2.0.3+ mime-db: 1.53.0+ outvariant: 1.4.0+ static-browser-server: 1.0.3++ dependencies:+ '@codemirror/autocomplete': 6.18.6+ '@codemirror/commands': 6.8.0+ '@codemirror/lang-css': 6.3.1+ '@codemirror/lang-html': 6.4.9+ '@codemirror/lang-javascript': 6.2.3+ '@codemirror/language': 6.11.0+ '@codemirror/state': 6.5.2+ '@codemirror/view': 6.36.4+ '@codesandbox/sandpack-client': 2.19.8+ '@lezer/highlight': 1.2.1+ '@react-hook/intersection-observer': 3.1.2([email protected])+ '@stitches/core': 1.2.8+ anser: 2.3.2+ clean-set: 1.1.2+ dequal: 2.0.3+ escape-carriage: 1.3.1+ lz-string: 1.5.0+ react: 18.2.0+ react-devtools-inline: 4.4.0+ react-dom: 18.2.0([email protected])+ react-is: 17.0.2+dependencies:@@ -16558,7 +16759,7 @@ snapshots:'@gar/[email protected]': {}- '@graphiql/[email protected](@codemirror/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])':+ '@graphiql/[email protected](@codemirror/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])':dependencies:'@graphiql/toolkit': 0.9.1(@types/[email protected])([email protected]([email protected]))([email protected])@@ -16569,7 +16770,7 @@ snapshots:'@types/codemirror': 5.60.10clsx: 1.2.1codemirror: 5.65.15copy-to-clipboard: 3.3.3graphql: 16.8.1@@ -17038,10 +17239,28 @@ snapshots:'@lezer/[email protected]': {}+ '@lezer/[email protected]':+ dependencies:+ '@lezer/common': 1.2.3+ '@lezer/highlight': 1.2.1+ '@lezer/lr': 1.4.2+'@lezer/[email protected]':dependencies:'@lezer/common': 1.2.3+ '@lezer/[email protected]':+ dependencies:+ '@lezer/common': 1.2.3+ '@lezer/highlight': 1.2.1+ '@lezer/lr': 1.4.2++ '@lezer/[email protected]':+ dependencies:+ '@lezer/common': 1.2.3+ '@lezer/highlight': 1.2.1+ '@lezer/lr': 1.4.2+'@lezer/[email protected]':dependencies:'@lezer/common': 1.2.3@@ -18869,6 +19088,16 @@ snapshots:'@react-dnd/[email protected]': {}+ '@react-hook/[email protected]([email protected])':+ dependencies:+ '@react-hook/passive-layout-effect': 1.2.1([email protected])+ intersection-observer: 0.10.0+ react: 18.2.0++ '@react-hook/[email protected]([email protected])':+ dependencies:+ react: 18.2.0+'@react-router/[email protected](@types/[email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@babel/core': 7.26.10([email protected])@@ -19810,6 +20039,8 @@ snapshots:'@speed-highlight/[email protected]': {}+ '@stitches/[email protected]': {}+'@stripe/[email protected](@stripe/[email protected])([email protected]([email protected]))([email protected])':dependencies:'@stripe/stripe-js': 5.5.0@@ -21696,6 +21927,8 @@ snapshots:+ [email protected]: {}+dependencies:string-width: 4.2.3@@ -22370,6 +22603,8 @@ snapshots:+ [email protected]: {}+@@ -22447,9 +22682,9 @@ snapshots:estree-walker: 3.0.3periscopic: 3.1.0dependencies:- '@codemirror/language': 6.0.0+ '@codemirror/language': 6.11.0'@types/codemirror': 0.0.90codemirror: 5.65.15graphql: 16.8.1@@ -22670,6 +22905,8 @@ snapshots:optional: true+ [email protected]: {}+dependencies:luxon: 3.5.0@@ -22827,6 +23064,11 @@ snapshots:d3-selection: 3.0.0d3-transition: 3.0.1([email protected])+ dependencies:+ es5-ext: 0.10.64+ type: 2.7.3+@@ -23291,8 +23533,26 @@ snapshots:is-date-object: 1.0.5is-symbol: 1.0.4+ dependencies:+ es6-iterator: 2.0.3+ es6-symbol: 3.1.4+ esniff: 2.0.1+ next-tick: 1.1.0++ dependencies:+ d: 1.0.2+ es5-ext: 0.10.64+ es6-symbol: 3.1.4++ dependencies:+ d: 1.0.2+ ext: 1.7.0+optionalDependencies:'@esbuild/aix-ppc64': 0.20.2@@ -23379,6 +23639,8 @@ snapshots:+ [email protected]: {}+@@ -23656,6 +23918,13 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ d: 1.0.2+ es5-ext: 0.10.64+ event-emitter: 0.3.5+ type: 2.7.3+dependencies:acorn: 8.11.3@@ -23738,6 +24007,11 @@ snapshots:+ dependencies:+ d: 1.0.2+ es5-ext: 0.10.64+@@ -23809,6 +24083,10 @@ snapshots:+ dependencies:+ type: 2.7.3+dependencies:is-extendable: 0.1.1@@ -24919,6 +25197,8 @@ snapshots:+ [email protected]: {}+dependencies:loose-envify: 1.4.0@@ -27454,6 +27734,8 @@ snapshots:react: 18.2.0react-dom: 18.2.0([email protected])+ [email protected]: {}+[email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]):dependencies:'@next/env': 14.2.26@@ -28030,6 +28312,8 @@ snapshots:strip-ansi: 7.1.0wcwidth: 1.0.1+ [email protected]: {}+@@ -28721,6 +29005,10 @@ snapshots:date-fns: 2.30.0react: 18.2.0+ dependencies:+ es6-symbol: 3.1.4+dependencies:dnd-core: 16.0.1@@ -30068,6 +30356,13 @@ snapshots:+ dependencies:+ '@open-draft/deferred-promise': 2.2.0+ dotenv: 16.4.7+ mime-db: 1.53.0+ outvariant: 1.4.3+@@ -30095,6 +30390,8 @@ snapshots:optionalDependencies:bare-events: 2.5.4+ [email protected]: {}+@@ -30801,6 +31098,8 @@ snapshots:+ [email protected]: {}+dependencies:call-bind: 1.0.7diff --git a/turbo.json b/turbo.jsonindex 61988aaa14a..9cf118492e4 100644--- a/turbo.json+++ b/turbo.json@@ -102,6 +102,8 @@"NEXT_PUBLIC_AUTH_DETECT_SESSION_IN_URL","NEXT_PUBLIC_GOTRUE_URL","NEXT_PUBLIC_BASE_PATH",+ "NEXT_PUBLIC_EXAMPLES_SUPABASE_ANON_KEY",+ "NEXT_PUBLIC_EXAMPLES_SUPABASE_URL",// These envs are technically passthrough env vars because they're only used on the server side of Nextjs"LIVE_SUPABASE_COM_SERVICE_ROLE_KEY","GITHUB_CHANGELOG_APP_ID",