I’ve been trying to implement an open file function in my project using FileReader and the editor.setState()
function without much success.
In one of my CodeMirror 5 projects, I could use editor.setValue
to append the contents to the editor.
function loadfile(input) {
const reader = new FileReader()
reader.onload = function(e) {
editor.setValue(e.target.result);
}
reader.readAsText(input.files[0]);
};
In CodeMirror 6, I assume that I would have to create a new EditorState with the document set to the output of the FileReader object. Then you would set the editor state with editor.setState()
with the new EditorState as its argument.
Here is what I have so far, but it doesn’t seem to work as intended.
editor.ts:
function loadfile(input: { files: Blob[]; } | undefined) {
const reader = new FileReader()
reader.onload = function(e) {
const newState = EditorState.create({
doc: e.target!.result as string,
extensions: [
markdown({
base: markdownLanguage,
codeLanguages: languages
}),
basicDarkTheme,
lineNumbers(),
highlightActiveLineGutter(),
highlightSpecialChars(),
history(),
foldGutter(),
drawSelection(),
dropCursor(),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
syntaxHighlighting(basicDarkHighlightStyle, {fallback: true}),
bracketMatching(),
closeBrackets(),
autocompletion(),
rectangularSelection(),
crosshairCursor(),
highlightActiveLine(),
highlightSelectionMatches(),
keymap.of([
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
...[indentWithTab]
]),
EditorView.updateListener.of(function(e) {
clearTimeout(previewDelay);
previewDelay = window.setTimeout(updatePreview, 250);
})
]
});
editor.setState(newState);
}
reader.readAsText(input!.files[0]);
};
const file = document.getElementById('open')!.onload = () => {
loadfile(this!);
}
index.html:
<input type="file" id="open">
I’ve read the migration guide, the docs, and numerous resources for hours but nothing has clicked in. I feel that the fault here would be the lack of understanding of how this system works. If I can get some hints or guidance, that would be great.
Thanks!