|
| 1 | +import { EditorState, Extension, type ReactCodeMirrorRef } from '@uiw/react-codemirror'; |
| 2 | +import { useEffect, useRef, useState } from 'react'; |
| 3 | +import { yCollab } from 'y-codemirror.next'; |
| 4 | +import * as Y from 'yjs'; |
| 5 | +import { SocketIOProvider } from 'y-socket.io'; |
| 6 | + |
| 7 | +import { COLLAB_SERVICE } from '@/services/api-clients'; |
| 8 | +import { extensions as baseExtensions } from '@/lib/editor/extensions'; |
| 9 | + |
| 10 | +// credit: https://github.com/yjs/y-websocket |
| 11 | +const usercolors = [ |
| 12 | + { color: '#30bced', light: '#30bced33' }, |
| 13 | + { color: '#6eeb83', light: '#6eeb8333' }, |
| 14 | + { color: '#ffbc42', light: '#ffbc4233' }, |
| 15 | + { color: '#ecd444', light: '#ecd44433' }, |
| 16 | + { color: '#ee6352', light: '#ee635233' }, |
| 17 | + { color: '#9ac2c9', light: '#9ac2c933' }, |
| 18 | + { color: '#8acb88', light: '#8acb8833' }, |
| 19 | + { color: '#1be7ff', light: '#1be7ff33' }, |
| 20 | +]; |
| 21 | + |
| 22 | +const getRandomColor = () => { |
| 23 | + return usercolors[Math.floor(Math.random() * usercolors.length)]; |
| 24 | +}; |
| 25 | + |
| 26 | +// TODO: Test if collab logic works |
| 27 | +export const useCollab = (roomId: string) => { |
| 28 | + const editorRef = useRef<ReactCodeMirrorRef>(null); |
| 29 | + const [extensions, setExtensions] = useState<Array<Extension>>([baseExtensions]); |
| 30 | + useEffect(() => { |
| 31 | + if (editorRef.current) { |
| 32 | + const doc = new Y.Doc(); |
| 33 | + let provider = null; |
| 34 | + try { |
| 35 | + provider = new SocketIOProvider(COLLAB_SERVICE, roomId, doc, {}); |
| 36 | + } catch (err) { |
| 37 | + const { name, message } = err as Error; |
| 38 | + console.log( |
| 39 | + `An error occurred connecting to the Collab Server: ${JSON.stringify({ name, message })}` |
| 40 | + ); |
| 41 | + return; |
| 42 | + } |
| 43 | + if (!provider.socket.connected) { |
| 44 | + console.log('Failed to connect'); |
| 45 | + return; |
| 46 | + } |
| 47 | + const ytext = doc.getText('codemirror'); |
| 48 | + const undoManager = new Y.UndoManager(ytext); |
| 49 | + const awareness = provider.awareness; |
| 50 | + const { color, light } = getRandomColor(); |
| 51 | + awareness.setLocalStateField('user', { |
| 52 | + name: `Anon`, |
| 53 | + color: color, |
| 54 | + colorLight: light, |
| 55 | + }); |
| 56 | + const collabExt = yCollab(ytext, awareness, { undoManager }); |
| 57 | + editorRef.current.state = EditorState.create({ |
| 58 | + doc: ytext.toJSON(), |
| 59 | + }); |
| 60 | + setExtensions([...extensions, collabExt]); |
| 61 | + return () => { |
| 62 | + doc.destroy(); |
| 63 | + provider.disconnect(); |
| 64 | + }; |
| 65 | + } |
| 66 | + }, [editorRef]); |
| 67 | + return { |
| 68 | + editorRef, |
| 69 | + extensions, |
| 70 | + }; |
| 71 | +}; |
0 commit comments