Skip to content

Instantly share code, notes, and snippets.

@zbeyens
Created July 18, 2023 09:23
Show Gist options
  • Save zbeyens/54f30e05761334d47b1fa6a1c9b21757 to your computer and use it in GitHub Desktop.
Save zbeyens/54f30e05761334d47b1fa6a1c9b21757 to your computer and use it in GitHub Desktop.
const RemoteSelection = ({ data, selectionRects, caretPosition }: CursorOverlayData<CursorData>) => {
if (!data) {
return null
}
return (
<>
{selectionRects.map((position, i) => (
<div
key={i}
style={{ backgroundColor: data.color, position: 'absolute', pointerEvents: 'none', zIndex: '1', ...position }}
/>
))}
{caretPosition && <Caret caretPosition={caretPosition} data={data} />}
</>
)
}
const RemoteCursorOverlayContent = ({ containerRef }: { containerRef?: RefObject<HTMLDivElement> }) => {
const [cursors] = useRemoteCursorOverlayPositions<CursorData>({ containerRef })
useEffect(() => {
const activeUsers: ActiveUser[] = []
cursors.forEach(cursor => {
if (cursor.data) {
activeUsers.push({ id: cursor.data.userId, color: cursor.data.color })
}
})
yjsActions.activeUsers(activeUsers)
}, [cursors])
return (
<>
{cursors.map(cursor => (
<RemoteSelection key={cursor.clientId} {...cursor} />
))}
</>
)
}
export const RemoteCursorOverlay = (props: { containerRef?: RefObject<HTMLDivElement> }) => {
const editor = usePlateEditorState()
const isRendered = usePlateSelectors().isRendered()
const isSynced = useYjsSelectors.isSynced()
const { disableCursors } = getPluginOptions<YjsPlugin>(editor, KEY_YJS)
const hidden = disableCursors || !editor.children.length || !isSynced || !isRendered
// existing issue with @slate-yjs/react https://github.com/BitPhinix/slate-yjs/issues/372
const { onChange } = editor
editor.onChange = () => {
flushSync(() => {
onChange()
})
}
if (hidden) return null
return <RemoteCursorOverlayContent {...props} />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment