Form Submitted Successfully!
Submitted by {submittedBy}
'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 (
Submitted by {submittedBy}