tldraw/apps/vscode/editor/src/ChangeResponder.tsx
alex a0628f9cb2
tldraw_final_v6_final(old version).docx.pdf (#2998)
Rename `@tldraw/tldraw` to just `tldraw`! `@tldraw/tldraw` still exists
as an alias to `tldraw` for folks who are still using that.

### Test Plan

- [x] Unit Tests
- [ ] End to end tests

### Release Notes

- The `@tldraw/tldraw` package has been renamed to `tldraw`. You can
keep using the old version if you want though!
2024-02-29 16:06:19 +00:00

69 lines
1.5 KiB
TypeScript

import React from 'react'
import {
debounce,
parseAndLoadDocument,
serializeTldrawJson,
useDefaultHelpers,
useEditor,
} from 'tldraw'
// @ts-ignore
import type { VscodeMessage } from '../../messages'
import '../public/index.css'
import { vscode } from './utils/vscode'
export const ChangeResponder = () => {
const editor = useEditor()
const { addToast, clearToasts, msg } = useDefaultHelpers()
React.useEffect(() => {
// When a message is received from the VS Code extension, handle it
function handleMessage({ data: message }: MessageEvent<VscodeMessage>) {
switch (message.type) {
// case 'vscode:undo': {
// editor.undo()
// break
// }
// case 'vscode:redo': {
// editor.redo()
// break
// }
case 'vscode:revert': {
parseAndLoadDocument(editor, message.data.fileContents, msg, addToast)
break
}
}
}
window.addEventListener('message', handleMessage)
return () => {
clearToasts()
window.removeEventListener('message', handleMessage)
}
}, [editor, msg, addToast, clearToasts])
React.useEffect(() => {
// When the history changes, send the new file contents to VSCode
const handleChange = debounce(async () => {
vscode.postMessage({
type: 'vscode:editor-updated',
data: {
fileContents: await serializeTldrawJson(editor.store),
},
})
}, 250)
vscode.postMessage({
type: 'vscode:editor-loaded',
})
editor.on('change-history', handleChange)
return () => {
handleChange()
editor.off('change-history', handleChange)
}
}, [editor])
return null
}