You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

60 lines
2.1 KiB

import {EditorState, EditorView, basicSetup} from "@codemirror/basic-setup"
import {markdown} from "@codemirror/lang-markdown"
import {tagExtension} from "@codemirror/state"
import {oneDark, oneDarkHighlightStyle} from "@codemirror/theme-one-dark"
let editableTag = Symbol();
let editor = new EditorView({
state: EditorState.create({
extensions: [basicSetup, markdown(), oneDark, oneDarkHighlightStyle, tagExtension(editableTag, EditorView.editable.of(document.getElementById('submit') != null))]
}),
parent: document.querySelector("#editor")
});
const setEditorContents = (text) => {
editor.dispatch({
changes: {from: 0, to: editor.state.doc.length, insert: text}
})
};
const syncEditor = (event) => {
event.preventDefault();
const successAlert = document.querySelector('#success-alert');
const errorAlert = document.querySelector('#error-alert');
fetch('/save', {
method: 'POST',
headers: { "Content-Type": "application/json; charset=utf-8" },
body: editor.state.sliceDoc()
})
.then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
.then(response => {
// here you do what you want with response
console.log(response);
successAlert.innerHTML = response.msg;
successAlert.style.display = "block";
errorAlert.style.display = "none";
})
.catch(err => {
console.log(err);
errorAlert.innerHTML = err.msg;
errorAlert.style.display = "block";
successAlert.style.display = "none";
});
};
// If we're on the create paste page, set up the submit listener
if (document.getElementById('submit') != null) {
const submitButton = document.querySelector("#submit");
submitButton.addEventListener("click", syncEditor);
}
// If we're on the public paste display page, copy the text from the contents div and then delete it
if (document.getElementById('contents') != null) {
const contentsDiv = document.querySelector("#contents");
setEditorContents(contentsDiv.textContent);
contentsDiv.remove();
}