tldraw
This is a real-time collaborative example of the tldraw whiteboard editor with React and Yorkie JS SDK.
useMultiplayerState.ts
1import { useCallback, useEffect, useRef, useState } from 'react';2import {3 TDUserStatus,4 TDAsset,5 TDBinding,6 TDShape,7 TDUser,8 TldrawApp,9} from '@tldraw/tldraw';10import { useThrottleCallback } from '@react-hook/throttle';11import * as yorkie from '@yorkie-js/sdk';12import { uniqueNamesGenerator, names } from 'unique-names-generator';13import { isEqual } from 'es-toolkit';1415import type { YorkieDocType, YorkiePresenceType } from './types';1617type Doc = yorkie.Document<YorkieDocType, YorkiePresenceType>;1819export type Status = 'connecting' | 'connected' | 'offline' | 'error';20export type Peer = { id: string; name: string; color: string; isMe: boolean };2122// Peer colours are picked from the client ID, so every tab agrees on them.23const peerColors = [24 '#fc8539',25 '#fdc433',26 '#23c176',27 '#3c9af1',28 '#f44954',29 '#855cf9',30];3132function peerColor(clientID: string) {33 let hash = 0;34 for (const char of clientID) {35 hash = (hash * 31 + char.charCodeAt(0)) | 0;36 }37 return peerColors[Math.abs(hash) % peerColors.length];38}3940/**41 * `replacePageContent` replaces the canvas with the shapes, bindings and42 * assets in the Yorkie document.43 */44function replacePageContent(app: TldrawApp, doc: Doc) {45 const root = doc.getRoot();46 app.replacePageContent(47 root.shapes.toJS() as Record<string, TDShape>,48 root.bindings.toJS() as Record<string, TDBinding>,49 root.assets.toJS() as Record<string, TDAsset>,50 );51}5253/**54 * `updateRecord` writes only the properties that changed, so concurrent edits55 * to different properties of the same shape are both kept.56 */57function updateRecord<T extends object>(58 records: Record<string, yorkie.JSONObject<T>>,59 id: string,60 value: T | undefined,61) {62 if (!value) {63 delete records[id];64 return;65 }66 if (!records[id]) {67 records[id] = value as yorkie.JSONObject<T>;68 return;69 }70 const current = records[id].toJS() as T;71 for (const key of Object.keys(value) as Array<keyof T>) {72 if (!isEqual(value[key], current[key]) && value[key] !== undefined) {73 (records[id] as T)[key] = value[key];74 }75 }76}7778/**79 * `useMultiplayerState` connects a tldraw app to a Yorkie document: shapes80 * and bindings live in the document root, and each user's cursor and81 * selection live in their presence.82 */83export function useMultiplayerState(roomId: string) {84 const [app, setApp] = useState<TldrawApp>();85 const [status, setStatus] = useState<Status>('connecting');86 const [peers, setPeers] = useState<Array<Peer>>([]);87 // The attached document, for the tldraw callbacks below. It is set only88 // while the effect that owns it is mounted.89 const docRef = useRef<Doc | undefined>(undefined);9091 const onMount = useCallback(92 (app: TldrawApp) => {93 app.loadRoom(roomId);94 app.setIsLoading(true);95 // Undo and redo go through Yorkie's history (see onUndo), not tldraw's.96 app.pause();97 // tldraw creates its app in a state initializer, which StrictMode runs98 // twice in development; both apps call onMount. The first one is the99 // app tldraw renders, so keep it.100 setApp((current) => current ?? app);101 },102 [roomId],103 );104105 const onUndo = useCallback(() => {106 const doc = docRef.current;107 if (app && doc?.history.canUndo()) {108 doc.history.undo();109 replacePageContent(app, doc);110 }111 }, [app]);112113 const onRedo = useCallback(() => {114 const doc = docRef.current;115 if (app && doc?.history.canRedo()) {116 doc.history.redo();117 replacePageContent(app, doc);118 }119 }, [app]);120121 // tldraw passes only the records each call changed, and the throttled122 // flush below sees only the last call's arguments. So every call adds its123 // records to these pending maps; a later value for the same ID wins, and124 // `undefined` means the record was deleted.125 const pendingShapes = useRef<Record<string, TDShape | undefined>>({});126 const pendingBindings = useRef<Record<string, TDBinding | undefined>>({});127 const pendingAssets = useRef<Record<string, TDAsset | undefined>>({});128129 // Write the pending records to the document as one change.130 const writePending = useCallback(() => {131 const doc = docRef.current;132 const shapes = pendingShapes.current;133 const bindings = pendingBindings.current;134 const assets = pendingAssets.current;135 const isEmpty = [shapes, bindings, assets].every(136 (records) => Object.keys(records).length === 0,137 );138 if (!doc || isEmpty) return;139140 pendingShapes.current = {};141 pendingBindings.current = {};142 pendingAssets.current = {};143 doc.update((root) => {144 for (const [id, shape] of Object.entries(shapes)) {145 updateRecord(root.shapes, id, shape);146 }147 for (const [id, binding] of Object.entries(bindings)) {148 updateRecord(root.bindings, id, binding);149 }150 for (const [id, asset] of Object.entries(assets)) {151 updateRecord(root.assets, id, asset);152 }153 });154 }, []);155156 // The second argument is a rate in calls per second, not milliseconds:157 // write at most 60 times a second.158 const flushPage = useThrottleCallback(writePending, 60, false);159160 const onChangePage = useCallback(161 (162 _app: TldrawApp,163 shapes: Record<string, TDShape | undefined>,164 bindings: Record<string, TDBinding | undefined>,165 assets: Record<string, TDAsset | undefined>,166 ) => {167 Object.assign(pendingShapes.current, shapes);168 Object.assign(pendingBindings.current, bindings);169 Object.assign(pendingAssets.current, assets);170 flushPage();171 },172 [flushPage],173 );174175 // Share the cursor and selection through presence.176 const onChangePresence = useThrottleCallback(177 (_app: TldrawApp, user: TDUser) => {178 docRef.current?.update((_root, presence) => {179 presence.set({ tdUser: user });180 });181 },182 60,183 false,184 );185186 useEffect(() => {187 if (!app) return;188189 // The client and document belong to this effect run. In development,190 // StrictMode runs the effect twice, so each run cleans up its own.191 let cancelled = false;192 const client = new yorkie.Client({193 rpcAddr: import.meta.env.VITE_YORKIE_API_ADDR,194 apiKey: import.meta.env.VITE_YORKIE_API_KEY,195 });196 const doc: Doc = new yorkie.Document(roomId, {197 enableDevtools: import.meta.env.DEV,198 });199200 const syncPeers = () => {201 const myID = client.getID();202 const presences = doc.getPresences().filter((p) => p.presence.tdUser);203 // A reloaded tab can briefly appear twice with the same tldraw user.204 const users = new Map(205 presences.map(({ presence }) => [presence.tdUser.id, presence.tdUser]),206 );207 app.updateUsers([...users.values()]);208 setPeers(209 presences.map(({ clientID, presence }) => ({210 id: clientID,211 name: String(presence.tdUser.metadata?.name ?? ''),212 color: presence.tdUser.color,213 isMe: clientID === myID,214 })),215 );216 };217218 const unsubs = [219 doc.subscribe('presence', (event) => {220 if (event.type === yorkie.DocEventType.Unwatched) {221 app.removeUser(event.value.presence.tdUser.id);222 }223 syncPeers();224 }),225 doc.subscribe((event) => {226 if (event.type === 'remote-change') {227 // Write local edits still waiting for the next flush first, so228 // replacing the canvas with the document does not drop them.229 writePending();230 replacePageContent(app, doc);231 }232 }),233 doc.subscribe('connection', (event) => {234 setStatus(235 event.value === yorkie.StreamConnectionStatus.Connected236 ? 'connected'237 : 'offline',238 );239 }),240 ];241242 const setup = async () => {243 await client.activate();244 if (cancelled) {245 // The effect was cleaned up while activating.246 await client.deactivate();247 return;248 }249250 const user: TDUser = {251 id: app.currentUser!.id,252 point: [0, 0],253 color: peerColor(client.getID()!),254 status: TDUserStatus.Connected,255 activeShapes: [],256 selectedIds: [],257 metadata: { name: uniqueNamesGenerator({ dictionaries: [names] }) },258 };259 await client.attach(doc, {260 initialRoot: { shapes: {}, bindings: {}, assets: {} } as YorkieDocType,261 initialPresence: { tdUser: user },262 });263 if (cancelled) return;264265 docRef.current = doc;266 replacePageContent(app, doc);267 syncPeers();268 app.zoomToFit();269 if (app.zoom > 1) app.resetZoom();270 app.setIsLoading(false);271 };272273 setup().catch(() => {274 if (!cancelled) setStatus('error');275 });276277 return () => {278 cancelled = true;279 for (const unsub of unsubs) unsub();280 if (docRef.current === doc) docRef.current = undefined;281 // Deactivating also detaches the document. While `activate` is still282 // in flight this is a no-op, and `setup` deactivates instead.283 client.deactivate().catch(() => {});284 };285 }, [app, roomId, writePending]);286287 return {288 status,289 peers,290 onMount,291 onChangePage,292 onChangePresence,293 onUndo,294 onRedo,295 };296}
Two clients on the same document. Edit in one and watch the other.This is one client. Open the example in another tab or on another device to watch edits sync.
- User 1