This binding binds a Y.Array to a Exacalidraw whiteboard.
npm install y-excalidraw> Excalidraw whiteboard binding for Yjs - Demo
This binding binds a Y.Array to a Excalidraw whiteboard.
```
npm install y-excalidraw
npm install y-excalidraw
`Example
`typescript
import * as React from "react";import { Excalidraw } from "@excalidraw/excalidraw";
import * as Y from "yjs";
import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types/types";
import { ExcalidrawBinding } from "y-excalidraw"
import { WebrtcProvider } from 'y-webrtc'
import * as random from 'lib0/random'
export const usercolors = [
{ color: '#30bced', light: '#30bced33' },
{ color: '#6eeb83', light: '#6eeb8333' },
{ color: '#ffbc42', light: '#ffbc4233' },
{ color: '#ecd444', light: '#ecd44433' },
{ color: '#ee6352', light: '#ee635233' },
{ color: '#9ac2c9', light: '#9ac2c933' },
{ color: '#8acb88', light: '#8acb8833' },
{ color: '#1be7ff', light: '#1be7ff33' }
]
export const userColor = usercolors[random.uint32() % usercolors.length]
const ydoc = new Y.Doc()
const yElements = ydoc.getArray>('elements'); // structure = {el: NonDeletedExcalidrawElement, pos: string}
const yAssets = ydoc.getMap('assets');
const provider = new WebrtcProvider('y-excalidraw-demo-room', ydoc)
provider.awareness.setLocalStateField('user', {
name: 'Anonymous ' + Math.floor(Math.random() * 100),
color: userColor.color,
colorLight: userColor.light
})
export default function App() {
const [api, setApi] = React.useState(null);
const [binding, setBindings] = React.useState(null);
const excalidrawRef = React.useRef(null);
React.useEffect(() => {
if (!api) return;
const binding = new ExcalidrawBinding(
yElements,
yAssets,
api,
provider.awareness,
// excalidraw dom is needed to override the undo/redo buttons in the UI as there is no way to override it via props in excalidraw
// You might need to pass {trackedOrigins: new Set()} to undomanager depending on whether your provider sets an origin or not
{excalidrawDom: excalidrawRef.current, undoManager: new Y.UndoManager(yElements)},
);
setBindings(binding);
return () => {
setBindings(null);
binding.destroy();
};
}, [api]);
const initData = {
elements: yjsToExcalidraw(yElements)
}
return (
initialData={initData} // Need to set the initial data
excalidrawAPI={setApi}
onPointerUpdate={binding?.onPointerUpdate}
theme="light"
/>
);
}
`If you want to get the excalidraw array, you can use the utility function
`typescript
import { yjsToExcalidraw } from "y-excalidraw"console.log("Excalidraw json", yjsToExcalidraw(yElements))
``