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 Create React App with TypeScript.

1
npm create vite@latest realtime-notes-app -- --template react-ts
2
cd realtime-notes-app

2. Install SuperViz SDK

Next, install SuperViz, which will enable us to add real-time synchronization features to our application.

1
npm install @superviz/sdk uuid
  • @superviz/sdk: SDK for integrating real-time collaboration features, including synchronization.
  • 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.

1
npm install -D tailwindcss postcss autoprefixer
2
npx 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} */
2
export default {
3
content: [
4
"./index.html",
5
"./src/**/*.{js,ts,jsx,tsx}",
6
],
7
theme: {
8
extend: {},
9
},
10
plugins: [],
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.

1
VITE_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.

1
import { useCallback, useEffect, useRef, useState } from "react";
2
import SuperVizRoom, { LauncherFacade, MousePointers, Realtime, RealtimeComponentEvent, RealtimeComponentState, RealtimeMessage, WhoIsOnline } from '@superviz/sdk';
3
import { v4 as generateId } from 'uuid';
4
import { NoteNode } from "./components/note-node";
5
import { 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.

1
const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;
2
const ROOM_ID = 'video-huddle-application';
3
const 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.

1
export default function App() {
2
const [initialized, setInitialized] = useState(false);
3
const [notes, setNotes] = useState<Note[]>([]);
4
const superviz = useRef<LauncherFacade | null>(null);
5
const channel = useRef<any | 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.

1
const initialize = useCallback(async () => {
2
if (initialized) return;
3
4
superviz.current = await SuperVizRoom(apiKey, {
5
roomId: ROOM_ID,
6
participant: {
7
id: PARTICIPANT_ID,
8
name: 'my participant',
9
},
10
group: {
11
id: 'video-huddle-application',
12
name: 'video-huddle-application',
13
},
14
environment: 'dev',
15
debug: true,
16
})

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.

1
const realtime = new Realtime();
2
realtime.subscribe(RealtimeComponentEvent.REALTIME_STATE_CHANGED, (state) => {
3
if (state !== RealtimeComponentState.STARTED) return;
4
5
channel.current = realtime.connect('video-huddle-application');
6
channel.current.subscribe('note-change', (event: RealtimeMessage) => {
7
const note = event.data as Note;
8
9
if (event.participantId === PARTICIPANT_ID || !note) return;
10
11
setNotes(previous => {
12
return previous.map(n => {
13
if (n.id === note.id) {
14
return note;
15
}
16
17
return n;
18
});
19
});
20
});
21
});

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.

1
const mousePointers = new MousePointers('mouse-container');
2
const whoIsOnline = new WhoIsOnline();
3
superviz.current.addComponent(mousePointers);
4
superviz.current.addComponent(realtime);
5
superviz.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.

1
setInitialized(true);
2
setNotes([
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.

1
const handleNoteChange = useCallback((note: Note) => {
2
setNotes((prevNotes) => {
3
return prevNotes.map(n => {
4
if (n.id === note.id) {
5
return note;
6
}
7
8
return n;
9
});
10
});
11
12
if (channel.current) {
13
channel.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.

1
useEffect(() => {
2
initialize();
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.

1
return (
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
{
9
notes.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:

1
import React, { useState } from "react";
2
import { Note } from "../common/types";
3
4
interface NoteNodeProps {
5
note: Note;
6
onChange: (note: Note) => void;
7
}
8
9
export const NoteNode: React.FC<NoteNodeProps> = ({ note, onChange }) => {
10
const [title, setTitle] = useState(note.title);
11
const [content, setContent] = useState(note.content);
12
13
const handleTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
14
const newTitle = event.target.value;
15
setTitle(newTitle);
16
onChange({ ...note, title: newTitle });
17
};
18
19
const handleContentChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
20
const newContent = event.target.value;
21
setContent(newContent);
22
onChange({ ...note, content: newContent });
23
};
24
25
return (
26
<div className="note-node p-4 bg-white rounded shadow-lg" style={{ position: "absolute", left: note.x, top: note.y }}>
27
<input
28
type="text"
29
value={title}
30
onChange={handleTitleChange}
31
className="font-bold mb-2 w-full border-none focus:outline-none"
32
/>
33
<textarea
34
value={content}
35
onChange={handleContentChange}
36
className="w-full border-none focus:outline-none"
37
rows={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.

1
export interface Note {
2
id: string;
3
title: string;
4
content: string;
5
x: number;
6
y: 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:

  1. App.tsx
    • Initializes the SuperViz environment.
    • Sets up participant information and room details.
    • Handles real-time synchronization and mouse pointers.
  2. NoteNode.tsx
    • Displays individual notes with editable fields.
    • Handles local state updates and propagates changes to the parent component.
  3. 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:

1
npm 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.