Created
September 19, 2022 14:51
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {createEditor} from 'Lexical'; | |
import {createBinding, syncYjsChangesToLexical} from 'LexicalYjs'; | |
import {Doc, applyUpdate} from 'yjs'; | |
export default function exportYDoc( | |
yDocState: Uint8Array, | |
nodes: Array<Class<LexicalNode>>, | |
): SerializedEditorState { | |
const emptyFunction = () => {}; | |
const provider: Provider = { | |
awareness: { | |
getLocalState: () => null, | |
getStates: () => new Map(), | |
off: emptyFunction, | |
on: emptyFunction, | |
setLocalState: emptyFunction, | |
}, | |
connect: emptyFunction, | |
disconnect: emptyFunction, | |
off: emptyFunction, | |
on: emptyFunction, | |
}; | |
const editor = createEditor({ | |
namespace: 'headless', | |
nodes, | |
onError: error => { | |
throw error; | |
}, | |
}); | |
editor._headless = true; | |
const id = 'main'; | |
const docMap = new Map(); | |
const doc = new Doc(); | |
const binding = createBinding(editor, provider, id, doc, docMap); | |
const {root} = binding; | |
root | |
.getSharedType() | |
.observeDeep((events: Array<YEvent>, transaction?: Transaction) => { | |
if (transaction?.origin !== binding) { | |
syncYjsChangesToLexical(binding, provider, events); | |
} | |
}); | |
applyUpdate(doc, yDocState, null); | |
// Force sync update so that ydoc applied above is processed before we try exporting | |
editor.update(() => { | |
if (editor._pendingEditorState != null) { | |
editor._pendingEditorState._flushSync = true; | |
} | |
}); | |
// At this point editor is populated with data from YDoc | |
// and can either return lexical json, or run export to html or markdown | |
const json = editor.getEditorState().toJSON(); | |
const html = $generateHtmlFromNodes(editor, null); | |
let markdown; | |
editor.update(() => { | |
markdown = $convertToMarkdownString(TRANSFORMERS); | |
... | |
}); | |
return { | |
markdown, | |
json, | |
html, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment