2021-11-22 14:00:24 +00:00
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
|
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
2022-03-24 09:05:35 +00:00
|
|
|
import React, { useState, useRef, useCallback } from 'react'
|
2022-01-10 15:13:52 +00:00
|
|
|
import type { TldrawApp, TDUser, TDShape, TDBinding, TDDocument, TDAsset } from '@tldraw/tldraw'
|
2021-11-22 14:00:24 +00:00
|
|
|
import { useRedo, useUndo, useRoom, useUpdateMyPresence } from '@liveblocks/react'
|
|
|
|
import { LiveMap, LiveObject } from '@liveblocks/client'
|
|
|
|
|
|
|
|
declare const window: Window & { app: TldrawApp }
|
|
|
|
|
|
|
|
export function useMultiplayerState(roomId: string) {
|
2022-03-24 09:05:35 +00:00
|
|
|
const [app, setApp] = useState<TldrawApp>()
|
|
|
|
const [error, setError] = useState<Error>()
|
|
|
|
const [loading, setLoading] = useState(true)
|
2021-11-22 14:00:24 +00:00
|
|
|
|
|
|
|
const room = useRoom()
|
2021-11-22 16:27:01 +00:00
|
|
|
const onUndo = useUndo()
|
|
|
|
const onRedo = useRedo()
|
2021-11-22 14:00:24 +00:00
|
|
|
const updateMyPresence = useUpdateMyPresence()
|
|
|
|
|
2022-03-24 09:05:35 +00:00
|
|
|
const rLiveShapes = useRef<LiveMap<string, TDShape>>()
|
|
|
|
const rLiveBindings = useRef<LiveMap<string, TDBinding>>()
|
|
|
|
const rLiveAssets = useRef<LiveMap<string, TDAsset>>()
|
2021-11-22 14:00:24 +00:00
|
|
|
|
2021-12-02 17:59:51 +00:00
|
|
|
// Callbacks --------------
|
|
|
|
|
|
|
|
// Put the state into the window, for debugging.
|
2022-03-24 09:05:35 +00:00
|
|
|
const onMount = useCallback(
|
2021-12-02 17:59:51 +00:00
|
|
|
(app: TldrawApp) => {
|
|
|
|
app.loadRoom(roomId)
|
|
|
|
app.pause() // Turn off the app's own undo / redo stack
|
|
|
|
window.app = app
|
|
|
|
setApp(app)
|
|
|
|
},
|
|
|
|
[roomId]
|
|
|
|
)
|
|
|
|
|
|
|
|
// Update the live shapes when the app's shapes change.
|
2022-03-24 09:05:35 +00:00
|
|
|
const onChangePage = useCallback(
|
2021-12-02 17:59:51 +00:00
|
|
|
(
|
|
|
|
app: TldrawApp,
|
|
|
|
shapes: Record<string, TDShape | undefined>,
|
2022-01-10 15:13:52 +00:00
|
|
|
bindings: Record<string, TDBinding | undefined>,
|
|
|
|
assets: Record<string, TDAsset | undefined>
|
2021-12-02 17:59:51 +00:00
|
|
|
) => {
|
|
|
|
room.batch(() => {
|
|
|
|
const lShapes = rLiveShapes.current
|
|
|
|
const lBindings = rLiveBindings.current
|
2022-01-10 15:13:52 +00:00
|
|
|
const lAssets = rLiveAssets.current
|
2021-12-02 17:59:51 +00:00
|
|
|
|
2022-01-10 15:13:52 +00:00
|
|
|
if (!(lShapes && lBindings && lAssets)) return
|
2021-12-02 17:59:51 +00:00
|
|
|
|
|
|
|
Object.entries(shapes).forEach(([id, shape]) => {
|
|
|
|
if (!shape) {
|
|
|
|
lShapes.delete(id)
|
|
|
|
} else {
|
|
|
|
lShapes.set(shape.id, shape)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
Object.entries(bindings).forEach(([id, binding]) => {
|
|
|
|
if (!binding) {
|
|
|
|
lBindings.delete(id)
|
|
|
|
} else {
|
|
|
|
lBindings.set(binding.id, binding)
|
|
|
|
}
|
|
|
|
})
|
2022-01-10 15:13:52 +00:00
|
|
|
|
|
|
|
Object.entries(assets).forEach(([id, asset]) => {
|
|
|
|
if (!asset) {
|
|
|
|
lAssets.delete(id)
|
|
|
|
} else {
|
|
|
|
lAssets.set(asset.id, asset)
|
|
|
|
}
|
|
|
|
})
|
2021-12-02 17:59:51 +00:00
|
|
|
})
|
|
|
|
},
|
|
|
|
[room]
|
|
|
|
)
|
|
|
|
|
|
|
|
// Handle presence updates when the user's pointer / selection changes
|
2022-03-24 09:05:35 +00:00
|
|
|
const onChangePresence = useCallback(
|
2021-12-02 17:59:51 +00:00
|
|
|
(app: TldrawApp, user: TDUser) => {
|
|
|
|
updateMyPresence({ id: app.room?.userId, user })
|
|
|
|
},
|
|
|
|
[updateMyPresence]
|
|
|
|
)
|
|
|
|
|
|
|
|
// Document Changes --------
|
|
|
|
|
2021-11-22 14:00:24 +00:00
|
|
|
React.useEffect(() => {
|
|
|
|
const unsubs: (() => void)[] = []
|
|
|
|
if (!(app && room)) return
|
|
|
|
// Handle errors
|
|
|
|
unsubs.push(room.subscribe('error', (error) => setError(error)))
|
|
|
|
|
|
|
|
// Handle changes to other users' presence
|
|
|
|
unsubs.push(
|
|
|
|
room.subscribe('others', (others) => {
|
|
|
|
app.updateUsers(
|
|
|
|
others
|
|
|
|
.toArray()
|
|
|
|
.filter((other) => other.presence)
|
|
|
|
.map((other) => other.presence!.user)
|
|
|
|
.filter(Boolean)
|
|
|
|
)
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
// Handle events from the room
|
|
|
|
unsubs.push(
|
|
|
|
room.subscribe(
|
|
|
|
'event',
|
|
|
|
(e: { connectionId: number; event: { name: string; userId: string } }) => {
|
|
|
|
switch (e.event.name) {
|
|
|
|
case 'exit': {
|
|
|
|
app?.removeUser(e.event.userId)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
// Send the exit event when the tab closes
|
|
|
|
function handleExit() {
|
|
|
|
if (!(room && app?.room)) return
|
|
|
|
room?.broadcastEvent({ name: 'exit', userId: app.room.userId })
|
|
|
|
}
|
|
|
|
|
|
|
|
window.addEventListener('beforeunload', handleExit)
|
|
|
|
unsubs.push(() => window.removeEventListener('beforeunload', handleExit))
|
|
|
|
|
2021-12-02 17:59:51 +00:00
|
|
|
let stillAlive = true
|
|
|
|
|
2021-11-22 14:00:24 +00:00
|
|
|
// Setup the document's storage and subscriptions
|
|
|
|
async function setupDocument() {
|
|
|
|
const storage = await room.getStorage<any>()
|
|
|
|
|
2022-01-10 15:13:52 +00:00
|
|
|
// Migrate previous versions
|
|
|
|
const version = storage.root.get('version')
|
|
|
|
|
|
|
|
// Initialize (get or create) maps for shapes/bindings/assets
|
2021-11-22 14:00:24 +00:00
|
|
|
|
|
|
|
let lShapes: LiveMap<string, TDShape> = storage.root.get('shapes')
|
2022-01-10 15:13:52 +00:00
|
|
|
if (!lShapes || !('_serialize' in lShapes)) {
|
2021-11-22 14:00:24 +00:00
|
|
|
storage.root.set('shapes', new LiveMap<string, TDShape>())
|
|
|
|
lShapes = storage.root.get('shapes')
|
|
|
|
}
|
|
|
|
rLiveShapes.current = lShapes
|
|
|
|
|
|
|
|
let lBindings: LiveMap<string, TDBinding> = storage.root.get('bindings')
|
2022-01-10 15:13:52 +00:00
|
|
|
if (!lBindings || !('_serialize' in lBindings)) {
|
2021-11-22 14:00:24 +00:00
|
|
|
storage.root.set('bindings', new LiveMap<string, TDBinding>())
|
|
|
|
lBindings = storage.root.get('bindings')
|
|
|
|
}
|
|
|
|
rLiveBindings.current = lBindings
|
|
|
|
|
2022-01-10 15:13:52 +00:00
|
|
|
let lAssets: LiveMap<string, TDAsset> = storage.root.get('assets')
|
|
|
|
if (!lAssets || !('_serialize' in lAssets)) {
|
|
|
|
storage.root.set('assets', new LiveMap<string, TDAsset>())
|
|
|
|
lAssets = storage.root.get('assets')
|
|
|
|
}
|
|
|
|
rLiveAssets.current = lAssets
|
2021-11-22 14:00:24 +00:00
|
|
|
|
|
|
|
if (!version) {
|
|
|
|
// The doc object will only be present if the document was created
|
|
|
|
// prior to the current multiplayer implementation. At this time, the
|
|
|
|
// document was a single LiveObject named 'doc'. If we find a doc,
|
|
|
|
// then we need to move the shapes and bindings over to the new structures
|
|
|
|
// and then mark the doc as migrated.
|
|
|
|
const doc = storage.root.get('doc') as LiveObject<{
|
|
|
|
uuid: string
|
|
|
|
document: TDDocument
|
|
|
|
migrated?: boolean
|
|
|
|
}>
|
|
|
|
|
2021-12-02 17:59:51 +00:00
|
|
|
// No doc? No problem. This was likely a newer document
|
2021-11-22 14:00:24 +00:00
|
|
|
if (doc) {
|
|
|
|
const {
|
|
|
|
document: {
|
|
|
|
pages: {
|
|
|
|
page: { shapes, bindings },
|
|
|
|
},
|
2022-01-10 15:13:52 +00:00
|
|
|
assets,
|
2021-11-22 14:00:24 +00:00
|
|
|
},
|
2021-12-02 17:59:51 +00:00
|
|
|
} = doc.toObject()
|
2021-11-26 15:14:10 +00:00
|
|
|
|
2021-12-02 17:59:51 +00:00
|
|
|
Object.values(shapes).forEach((shape) => lShapes.set(shape.id, shape))
|
|
|
|
Object.values(bindings).forEach((binding) => lBindings.set(binding.id, binding))
|
2022-01-10 15:13:52 +00:00
|
|
|
Object.values(assets).forEach((asset) => lAssets.set(asset.id, asset))
|
2021-11-22 14:00:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Save the version number for future migrations
|
2022-01-10 15:13:52 +00:00
|
|
|
storage.root.set('version', 2.1)
|
2021-11-22 14:00:24 +00:00
|
|
|
|
2021-12-02 17:59:51 +00:00
|
|
|
// Subscribe to changes
|
|
|
|
const handleChanges = () => {
|
|
|
|
app?.replacePageContent(
|
|
|
|
Object.fromEntries(lShapes.entries()),
|
2022-01-10 15:13:52 +00:00
|
|
|
Object.fromEntries(lBindings.entries()),
|
|
|
|
Object.fromEntries(lAssets.entries())
|
2021-12-02 17:59:51 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (stillAlive) {
|
|
|
|
unsubs.push(room.subscribe(lShapes, handleChanges))
|
|
|
|
|
|
|
|
// Update the document with initial content
|
|
|
|
handleChanges()
|
2021-11-22 14:00:24 +00:00
|
|
|
|
2021-12-02 17:59:51 +00:00
|
|
|
setLoading(false)
|
|
|
|
}
|
|
|
|
}
|
2021-11-22 14:00:24 +00:00
|
|
|
setupDocument()
|
|
|
|
|
|
|
|
return () => {
|
2021-12-02 17:59:51 +00:00
|
|
|
stillAlive = false
|
2021-11-22 14:00:24 +00:00
|
|
|
unsubs.forEach((unsub) => unsub())
|
|
|
|
}
|
|
|
|
}, [room, app])
|
|
|
|
|
|
|
|
return {
|
2021-11-22 16:27:01 +00:00
|
|
|
onUndo,
|
|
|
|
onRedo,
|
2021-11-22 14:00:24 +00:00
|
|
|
onMount,
|
|
|
|
onChangePage,
|
|
|
|
onChangePresence,
|
|
|
|
error,
|
|
|
|
loading,
|
|
|
|
}
|
|
|
|
}
|