{% macro text_editor(field, label=True, autofocus=false) %}
	{{ field.label if label }}
	{{ field() }}
	<script>
	window.addEventListener("load", function(){
		var simplemde = new SimpleMDE({
			element: document.getElementById("{{field.name}}"),
			autofocus: {{ "true" if autofocus else "false" }},
			autosave: {
				enabled: true,
				uniqueId: "{{ request.path }}+{{ field.name }}",
				delay: 1000,
			},
			hideIcons: ["guide", "side-by-side", "fullscreen", "heading"],
			showIcons: ["code", "table", "horizontal-rule", "ordered-list",
				"unordered-list", "heading-1", "heading-2", "heading-3",
				"strikethrough"
			],
			insertTexts: {
				image: ["![](https://", ")"],
				link: ["[", "](https://)"],
			},
			previewRender: function(plainText, preview) { // Async method
				data = {text: plainText};
				fetch('{{ url_for("api_markdown") }}', {
					method: "POST",
					headers: {
						'Content-Type': 'application/json',
						'X-CSRFToken': '{{ csrf_token() }}'
					},
					body: JSON.stringify(data)
				})
				.then(response => response.text())
				.then(data => preview.innerHTML = data);
				return "Chargement…";
			},
			spellChecker: false, // Uses CDN jsdelivr.net
			forceSync: true,
			tabSize: 4,
			shortcuts: {
				toggleFullScreen: null,
			},
			status: false,
		});

		// Ctrl+Enter submits form
		ta = document.querySelector("div.CodeMirror");
		ta.addEventListener('keydown', function(e) {
			var keyCode = e.keyCode || e.which;
			if (e.ctrlKey && keyCode == 13) {
				var e = e.target;
				while(! (e instanceof HTMLFormElement)) {
					e = e.parentNode;
				}
				try {
					e.submit();
				} catch(exception) {
					e.submit.click();
				}
			}
		});
	});

	</script>
	{% for error in field.errors %}
		<span class="msgerror">{{ error }}</span>
	{% endfor %}
{% endmacro %}
