editor: Add preview

This commit is contained in:
Eragon 2022-05-12 23:02:40 +02:00
parent e6ae16c43d
commit f5573c0900
Signed by: Eragon
GPG Key ID: 087126EBFC725006
3 changed files with 49 additions and 7 deletions

View File

@ -2,9 +2,11 @@ from app import app
from app.utils.filters.markdown import md
from flask import request, abort
from werkzeug.exceptions import BadRequestKeyError
from app import csrf
class API():
@app.route("/api/markdown", methods=["POST"])
@csrf.exempt
def api_markdown():
try:
markdown = request.get_json()['text']

View File

@ -12,8 +12,9 @@ function editor_event_source(event)
usually reports the SVG in the button as the source */
let node = event.target || event.srcElement;
while(node != document.body) {
if(node.tagName == "BUTTON" && !button)
if(node.tagName == "BUTTON" && !button) {
button = node;
}
if(node.classList.contains("editor") && !editor) {
editor = node;
break;
@ -123,10 +124,11 @@ function editor_set_title(event, level, diff)
});
}
// Tab insert some spaces
// Ctrl+Enter send the form
previewTimeout = null;
ta = document.querySelector(".editor textarea");
ta.addEventListener('keydown', function(e) {
// Tab insert some spaces
// Ctrl+Enter send the form
let keyCode = e.keyCode || e.which;
if (keyCode == 9) {
// TODO Add one tab to selected text without replacing it
@ -149,4 +151,39 @@ ta.addEventListener('keydown', function(e) {
t.submit.click();
}
}
// Set a timeout for refreshing the preview
if (previewTimeout != null) {
clearTimeout(previewTimeout);
}
previewTimeout = setTimeout(preview, 1000);
});
function preview() {
const previewArea = document.querySelector("#editor_content_preview");
const textarea = document.querySelector(".editor textarea");
const payload = {text: ta.value};
const headers = new Headers();
headers.append("Content-Type", "application/json");
const params = {
method: "POST",
body: JSON.stringify(payload),
headers
};
console.log(payload);
fetch("/api/markdown", params).then(
(response) => {
response.text().then(
(text) => {
previewArea.innerHTML = text;
}
);
});
}

View File

@ -121,14 +121,17 @@
{{ field.label if label }}
{{ field() }}
<!-- Load the script -->
<script>
window.addEventListener("load", function(){});
</script>
<div id="editor_content_preview">
</div>
<!-- Display errors -->
{% for error in field.errors %}
<span class="msgerror">{{ error }}</span>
{% endfor %}
<!-- Load the script -->
<script>
window.addEventListener("load", function(){});
</script>
</div>
{% endmacro %}