In this tutorial, we will guide you through adding real-time synchronization to a productivity tool using SuperViz. Real-time synchronization is a crucial feature for collaborative applications, allowing multiple users to interact with shared content simultaneously and see each other's changes as they happen. With SuperViz, you can build interactive tools that update live, providing a seamless collaborative experience for users.
We'll demonstrate how to integrate real-time synchronization into a notes application, enabling users to collaborate on notes with real-time updates. This setup allows multiple participants to edit notes, move elements, and see changes instantly as they happen. Let's get started!
Prerequisite
To follow this tutorial, you will need a SuperViz account and a developer token. If you already have an account and a developer token, you can move on to the next step.
Create an account
To create an account, go to https://dashboard.superviz.com/register and create an account using either Google or an email/password. It's important to note that when using an email/password, you will receive a confirmation link that you'll need to click to verify your account.
Retrieving a Developer Token
To use the SDK, you’ll need to provide a developer token, as this token is essential for associating SDK requests with your account. You can retrieve both development and production SuperViz tokens from the dashboard..
Copy and save the developer token, as you will need it in the next steps of this tutorial.
Step 1: Set Up Your React Application
To begin, you'll need to set up a new React project where we will integrate the SuperViz SDK for real-time synchronization.
1. Create a New React Project
First, create a new React application using Vite with TypeScript.
1npm create vite@latest realtime-notes-app -- --template react-ts2cd realtime-notes-app
2. Install SuperViz SDK
Next, install SuperViz, which will enable us to add real-time synchronization features to our application.
1npm install @superviz/sdk @superviz/realtime uuid
- @superviz/sdk: SDK for integrating real-time collaboration features, including synchronization.
- @superviz/realtime: SuperViz Real-Time library for integrating real-time synchronization into your application.
- uuid: A library for generating unique identifiers, useful for creating unique participant IDs.
3. Configure tailwind
In this tutorial, we'll use the Tailwind css framework. First, install the tailwind package.
1npm install -D tailwindcss postcss autoprefixer2npx tailwindcss init -p
We then need to configure the template path. Open tailwind.config.js
in the root of the project and insert the following code.
1/** @type {import('tailwindcss').Config} */2export default {3content: [4"./index.html",5"./src/**/*.{js,ts,jsx,tsx}",6],7theme: {8extend: {},9},10plugins: [],11}
Then we need to add the tailwind directives to the global CSS file. (src/index.css)
1@tailwind base;2@tailwind components;3@tailwind utilities;
4. Set Up Environment Variables
Create a .env
file in your project root and add your SuperViz developer key. This key will be used to authenticate your application with SuperViz services.
1VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_DEVELOPER_KEY
Step 2: Implement the Main Application
In this step, we'll implement the main application logic to initialize SuperViz and handle real-time synchronization in a notes application.
1. Implement the App Component
Open src/App.tsx
and set up the main application component using SuperViz to manage the collaborative environment.
1import { useCallback, useEffect, useRef, useState } from "react";2import SuperVizRoom, {3LauncherFacade,4MousePointers,5WhoIsOnline,6} from "@superviz/sdk";7import { Realtime, type Channel } from "@superviz/realtime/client";8import { v4 as generateId } from "uuid";9import { NoteNode } from "./components/note-node";10import { Note } from "./common/types";
Explanation:
- Imports: Import necessary components from React, SuperViz SDK, and UUID for managing state, initializing SuperViz, and generating unique identifiers.
2. Define Constants
Define constants for the API key, room ID, and participant ID.
1const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;2const ROOM_ID = 'video-huddle-application';3const PARTICIPANT_ID = generateId();
Explanation:
- apiKey: Retrieves the SuperViz API key from environment variables.
- ROOM_ID: Defines the room ID for the SuperViz session.
- PARTICIPANT_ID: Generates a unique participant ID using the
uuid
library.
3. Create the App Component
Set up the main App
component and initialize state variables.
1export default function App() {2const [initialized, setInitialized] = useState(false);3const [notes, setNotes] = useState<Note[]>([]);4const superviz = useRef<LauncherFacade | null>(null);5const channel = useRef<Channel | null>(null);
Explanation:
- initialized: A state variable to track whether the SuperViz environment has been set up.
- notes: A state variable to manage the list of notes in the application.
- superviz: A ref to store the SuperViz room instance.
- channel: A ref to store the real-time communication channel.
4. Initialize SuperViz and Real-Time Components
Create an initialize
function to set up the SuperViz environment and configure real-time synchronization.
1const initialize = useCallback(async () => {2if (initialized) return;34superviz.current = await SuperVizRoom(apiKey, {5roomId: ROOM_ID,6participant: {7id: PARTICIPANT_ID,8name: 'my participant',9},10group: {11id: 'video-huddle-application',12name: 'video-huddle-application',13},14})
Explanation:
- initialize: An asynchronous function that initializes the SuperViz room and checks if it's already initialized to prevent duplicate setups.
- SuperVizRoom: Configures the room, participant, and group details for the session.
5. Set Up Real-Time Synchronization
Within the initialize
function, set up real-time synchronization for notes.
1const realtime = new Realtime(apiKey, {2participant: {3id: PARTICIPANT_ID,4name,5},6});78channel.current = await realtime.connect("realtime-sync");910channel.current.subscribe<Note>("note-change", (event) => {11const note = event.data;1213if (event.participantId === PARTICIPANT_ID || !note) return;1415setNotes((previous) => {16return previous.map((n) => {17if (n.id === note.id) {18return note;19}2021return n;22});23});24});
Explanation:
- Realtime: Initializes the real-time component for synchronization.
- RealtimeComponentEvent.REALTIME_STATE_CHANGED: Subscribes to changes in the real-time component state.
- note-change Subscription: Listens for note changes and updates the local state accordingly, ignoring changes from the current participant to avoid redundancy.
6. Add Mouse Pointers and Online Status
Enhance the application with mouse pointers and online status indicators.
1const mousePointers = new MousePointers('mouse-container');2const whoIsOnline = new WhoIsOnline();3superviz.current.addComponent(mousePointers);4superviz.current.addComponent(whoIsOnline)
Explanation:
- MousePointers: Displays real-time mouse pointers to show where other participants are interacting.
- WhoIsOnline: Shows a list of currently online participants in the session.
7. Initialize Notes
Set the initial state of notes with example content.
1setInitialized(true);2setNotes([3{ id: 'note-1', title: `Unicorn's Shopping List`, content: 'Rainbow sprinkles, cloud fluff, and pixie dust', x: 20, y: 50 },4{ id: 'note-2', title: `Zombie's To-Do List`, content: 'Find brains, practice groaning, shuffle aimlessly', x: 20, y: 50 },5{ id: 'note-3', title: `Alien's Earth Observations`, content: 'Humans obsessed with cat videos and avocado toast. Fascinating!', x: 20, y: 50 },6]);7}, [initialized, setNotes]);
Explanation:
- setInitialized: Marks the application as initialized to prevent reinitialization.
- setNotes: Sets the initial notes with predefined content, positioning them on the screen.
8. Handle Note Changes
Implement the handleNoteChange
function to manage updates to notes.
1const handleNoteChange = useCallback((note: Note) => {2setNotes((prevNotes) => {3return prevNotes.map(n => {4if (n.id === note.id) {5return note;6}78return n;9});10});1112if (channel.current) {13channel.current.publish('note-change', note);14}15}, []);
Explanation:
- handleNoteChange: Updates the local state of notes when a note is edited and publishes the change to other participants.
- channel.current.publish: Sends the updated note to all participants through the real-time channel.
9. Use Effect Hook for Initialization
Use the useEffect
hook to trigger the initialize
function on component mount.
1useEffect(() => {2initialize();3}, [initialize]);
Explanation:
- useEffect: Calls the
initialize
function once when the component mounts, setting up the SuperViz environment and real-time synchronization.
10. Render the Application
Return the JSX structure for rendering the application, including notes and collaboration features.
1return (2<>3<div className='w-full h-full bg-gray-200 flex items-center justify-center flex-col'>4<header className='w-full p-5 bg-purple-400 flex items-center justify-between'>5<h2 className='text-white text-2xl font-bold'>Real-Time Sync</h2>6</header>7<main id="mouse-container" className='flex-1 p-20 flex w-full gap-2 items-center justify-center overflow-hidden'>8{9notes.map((note, index) => (10<NoteNode key={index} note={note} onChange={handleNoteChange} />11))12}13</main>14</div>15</>16)
Explanation:
- Header: Displays the title of the application.
- Main Container: Wraps the notes and collaboration elements, providing a space for interaction.
- NoteNode Component: Renders each note, allowing for real-time updates and changes.
Step 3: Create the NoteNode Component
The NoteNode
component is responsible for displaying individual notes and handling edits.
1. Create the NoteNode Component
Create a new file named src/components/note-node.tsx
and add the following implementation:
1import React, { useState } from "react";2import { Note } from "../common/types";34interface NoteNodeProps {5note: Note;6onChange: (note: Note) => void;7}89export const NoteNode: React.FC<NoteNodeProps> = ({ note, onChange }) => {10const [title, setTitle] = useState(note.title);11const [content, setContent] = useState(note.content);1213const handleTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {14const newTitle = event.target.value;15setTitle(newTitle);16onChange({ ...note, title: newTitle });17};1819const handleContentChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {20const newContent = event.target.value;21setContent(newContent);22onChange({ ...note, content: newContent });23};2425return (26<div className="note-node p-4 bg-white rounded shadow-lg" style={{ position: "absolute", left: note.x, top: note.y }}>27<input28type="text"29value={title}30onChange={handleTitleChange}31className="font-bold mb-2 w-full border-none focus:outline-none"32/>33<textarea34value={content}35onChange={handleContentChange}36className="w-full border-none focus:outline-none"37rows={5}38/>39</div>40);41}
Explanation:
- NoteNode Component: Displays each note with editable fields for title and content.
- handleTitleChange & handleContentChange: Updates the state and calls the
onChange
callback to propagate changes.
2. Define the Note Type
Create a new file named src/common/types.ts
and define the Note
type.
1export interface Note {2id: string;3title: string;4content: string;5x: number;6y: number;7}
Explanation:
- Note Type: Defines the structure of a note, including ID, title, content, and position.
Step 4: Understanding the Project Structure
Here's a quick overview of how the project structure supports real-time synchronization:
App.tsx
- Initializes the SuperViz environment.
- Sets up participant information and room details.
- Handles real-time synchronization and mouse pointers.
NoteNode.tsx
- Displays individual notes with editable fields.
- Handles local state updates and propagates changes to the parent component.
types.ts
- Defines the data structure for notes used throughout the application.
Step 5: Running the Application
1. Start the React Application
To run your application, use the following command in your project directory:
1npm run dev
This command will start the development server and open your application in the default web browser. You can interact with the notes and see updates in real-time as other participants join the session.
2. Test the Application
- Real-Time Notes: Open the application in multiple browser windows or tabs to simulate multiple participants and verify that changes made to notes are reflected in real-time for all users.
- Collaborative Interaction: Test the responsiveness of the application by editing notes and observing how changes appear for other participants.
Summary
In this tutorial, we built a collaborative notes application using SuperViz for real-time synchronization. We configured a React application to handle note editing, enabling multiple users to collaborate seamlessly on shared notes. This setup can be extended and customized to fit various scenarios where real-time collaboration and document editing are required.
Feel free to explore the full code and further examples in the GitHub repository for more details.