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.

59 lines
2.1 KiB

  1. import {EditorState, EditorView, basicSetup} from "@codemirror/basic-setup"
  2. import {markdown} from "@codemirror/lang-markdown"
  3. import {tagExtension} from "@codemirror/state"
  4. import {oneDark, oneDarkHighlightStyle} from "@codemirror/theme-one-dark"
  5. let editableTag = Symbol();
  6. let editor = new EditorView({
  7. state: EditorState.create({
  8. extensions: [basicSetup, markdown(), oneDark, oneDarkHighlightStyle, tagExtension(editableTag, EditorView.editable.of(document.getElementById('submit') != null))]
  9. }),
  10. parent: document.querySelector("#editor")
  11. });
  12. const setEditorContents = (text) => {
  13. editor.dispatch({
  14. changes: {from: 0, to: editor.state.doc.length, insert: text}
  15. })
  16. };
  17. const syncEditor = (event) => {
  18. event.preventDefault();
  19. const successAlert = document.querySelector('#success-alert');
  20. const errorAlert = document.querySelector('#error-alert');
  21. fetch('/save', {
  22. method: 'POST',
  23. headers: { "Content-Type": "application/json; charset=utf-8" },
  24. body: editor.state.sliceDoc()
  25. })
  26. .then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
  27. .then(response => {
  28. // here you do what you want with response
  29. console.log(response);
  30. successAlert.innerHTML = response.msg;
  31. successAlert.style.display = "block";
  32. errorAlert.style.display = "none";
  33. })
  34. .catch(err => {
  35. console.log(err);
  36. errorAlert.innerHTML = err.msg;
  37. errorAlert.style.display = "block";
  38. successAlert.style.display = "none";
  39. });
  40. };
  41. // If we're on the create paste page, set up the submit listener
  42. if (document.getElementById('submit') != null) {
  43. const submitButton = document.querySelector("#submit");
  44. submitButton.addEventListener("click", syncEditor);
  45. }
  46. // If we're on the public paste display page, copy the text from the contents div and then delete it
  47. if (document.getElementById('contents') != null) {
  48. const contentsDiv = document.querySelector("#contents");
  49. setEditorContents(contentsDiv.textContent);
  50. contentsDiv.remove();
  51. }