PCv5/app/static/scripts/editor.js

74 lines
2.2 KiB
JavaScript

/* Add callbacks on text formatting buttons */
function editor_insert_around(e) {
let button = undefined;
let editor = undefined;
/* Grab the button and the parent editor block. The onclick event itself
usually reports the SVG in the button as the source */
let node = e.target || e.srcElement;
while(node != document.body) {
if(node.tagName == "BUTTON" && !button)
button = node;
if(node.classList.contains("editor") && !editor) {
editor = node;
break;
}
node = node.parentNode;
}
if(!button || !editor) return;
/* Find the textarea */
const ta = editor.querySelector("textarea");
ta.focus();
let indexStart = ta.selectionStart;
let indexEnd = ta.selectionEnd;
const before = button.dataset.before || "";
const after = button.dataset.after || "";
ta.value = ta.value.substring(0, indexStart)
+ before
+ ta.value.substring(indexStart, indexEnd)
+ after
+ ta.value.substring(indexEnd);
/* Restore selection */
if(indexStart != indexEnd) {
ta.selectionStart = indexStart;
ta.selectionEnd = indexEnd + before.length + after.length;
}
else {
ta.selectionStart = indexStart + before.length;
ta.selectionEnd = ta.selectionStart;
}
}
// Tab insert some spaces
// Ctrl+Enter send the form
ta = document.querySelector(".editor textarea");
ta.addEventListener('keydown', function(e) {
let keyCode = e.keyCode || e.which;
if (keyCode == 9) {
// TODO Add one tab to selected text without replacing it
e.preventDefault();
let start = e.target.selectionStart;
let end = e.target.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
e.target.value = e.target.value.substring(0, start) + "\t" + e.target.value.substring(end);
e.target.selectionEnd = start + 1;
}
if (e.ctrlKey && keyCode == 13) {
let t = e.target;
while(! (t instanceof HTMLFormElement)) {
t = t.parentNode;
}
try {
t.submit();
} catch(exception) {
t.submit.click();
}
}
});